<commit_before>/**
 * Copyright (C) 2014 Stratio (http://stratio.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.stratio.ingestion.serializer.elasticsearch;

import static org.apache.flume.sink.elasticsearch.ElasticSearchEventSerializer.charset;
import static org.elasticsearch.node.NodeBuilder.nodeBuilder;

import java.io.IOException;
import java.net.URL;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.event.EventBuilder;
import org.apache.flume.sink.elasticsearch.ElasticSearchIndexRequestBuilderFactory;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.collect.Maps;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.node.Node;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.stratio.ingestion.serializer.elasticsearch.ElasticSearchSerializerWithMapping;

public class TestElasticSearchSerializerWithMapping {
	
	private final static String INDEX_PREFIX = "flume";
	private final static String INDEX_TYPE = "log";
	private final static String MAPPING_PATH = "/mapping.json";
	private final static String TIMESTAMP_HEADER = "timestamp";
	private final static long DAY_IN_MILLIS = 86400000;

	private Node node;
	private ElasticSearchSerializerWithMapping serializer;
	private Client client;
	private String expectedESMapping = "";
	
	@Before
	public void setUpES() throws IOException {
		String jsonMapping = IOUtils.toString(this.getClass()
                .getResourceAsStream(MAPPING_PATH));
		expectedESMapping = Strings.trimAllWhitespace("{\"" + INDEX_TYPE + "\":" + jsonMapping + "}");
		
		URL resourceUrl = getClass().getResource(MAPPING_PATH);
		Context context = new Context();
		context.put("mappingFile", resourceUrl.getPath());
		serializer = new ElasticSearchSerializerWithMapping();
		serializer.configure(context);
		
		ImmutableSettings.Builder ESSettings = ImmutableSettings.settingsBuilder()
                .put("http.enabled", "false")
                .put("cluster.name", "test");
		node = nodeBuilder().local(true).settings(ESSettings.build()).node();
		client = node.client();	
	}
	
	@Test
	public void sameTimestampEventsShouldCreateOnlyOneIndexWithTheExpectedMapping() throws IOException {
		Event event = createExampleEvent(System.currentTimeMillis());
		String indexName = getIndexName(INDEX_PREFIX, Long.parseLong(event.getHeaders().get(TIMESTAMP_HEADER)));
		
		serializer.createIndexRequest(client, INDEX_PREFIX, INDEX_TYPE, event);	
		serializer.createIndexRequest(client, INDEX_PREFIX, INDEX_TYPE, event);
		ImmutableOpenMap<String, MappingMetaData> mappings = getIndices().get(indexName).getMappings();
		String mappingActual = mappings.get(INDEX_TYPE).source().string();
		<commit_msg>[elasticsearch-serializer] Close ES client and node after each test.<commit_after>/**
 * Copyright (C) 2014 Stratio (http://stratio.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.stratio.ingestion.serializer.elasticsearch;

import static org.apache.flume.sink.elasticsearch.ElasticSearchEventSerializer.charset;
import static org.elasticsearch.node.NodeBuilder.nodeBuilder;

import java.io.IOException;
import java.net.URL;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.event.EventBuilder;
import org.apache.flume.sink.elasticsearch.ElasticSearchIndexRequestBuilderFactory;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.collect.Maps;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.node.Node;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.stratio.ingestion.serializer.elasticsearch.ElasticSearchSerializerWithMapping;

public class TestElasticSearchSerializerWithMapping {
	
	private final static String INDEX_PREFIX = "flume";
	private final static String INDEX_TYPE = "log";
	private final static String MAPPING_PATH = "/mapping.json";
	private final static String TIMESTAMP_HEADER = "timestamp";
	private final static long DAY_IN_MILLIS = 86400000;

	private Node node;
	private ElasticSearchSerializerWithMapping serializer;
	private Client client;
	private String expectedESMapping = "";
	
	@Before
	public void setUpES() throws IOException {
		String jsonMapping = IOUtils.toString(this.getClass()
                .getResourceAsStream(MAPPING_PATH));
		expectedESMapping = Strings.trimAllWhitespace("{\"" + INDEX_TYPE + "\":" + jsonMapping + "}");
		
		URL resourceUrl = getClass().getResource(MAPPING_PATH);
		Context context = new Context();
		context.put("mappingFile", resourceUrl.getPath());
		serializer = new ElasticSearchSerializerWithMapping();
		serializer.configure(context);
		
		ImmutableSettings.Builder ESSettings = ImmutableSettings.settingsBuilder()
                .put("http.enabled", "false")
                .put("cluster.name", "test");
		node = nodeBuilder().local(true).settings(ESSettings.build()).node();
		client = node.client();	
	}

    @After
    public void tearDownES() throws IOException {
        client.close();
        node.close();
    }
	
	@Test
	public void sameTimestampEventsShouldCreateOnlyOneIndexWithTheExpectedMapping() throws IOException {
		Event event = createExampleEvent(System.currentTimeMillis());
		String indexName = getIndexName(INDEX_PREFIX, Long.parseLong(event.getHeaders().get(TIMESTAMP_HEADER)));
		
		serializer.createIndexRequest(client, INDEX_PREFIX, INDEX_TYPE, event);	
		serializer.createIndexRequest(client, INDEX_PREFIX, INDEX_TYPE, event);
		ImmutableOpenMap<String, MappingMetaData> mappings = getIndices().get(indexName).getMappings();
		String mappingActual = mappings.get(INDEX_TYPE).source().string();
		
{'fraction_non_alphanumeric': 0.10022213511041422, 'fraction_numerical': 0.004181366784267607, 'mean_word_length': 5.346600331674958, 'pattern_counts': {'":': 2, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2283827', 'n_tokens_mistral': 2161, 'n_tokens_neox': 2090, 'n_words': 514}