/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you 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 org.elasticsearch.indexing;

import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicIntegerArray;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;

/**
 *
 */
public class IndexActionTests extends ElasticsearchIntegrationTest {

    @Test
    public void testCreatedFlag() throws Exception {
        createIndex("test");
        ensureGreen();

        IndexResponse indexResponse = client().prepareIndex("test", "type", "1").setSource("field1", "value1_1").execute().actionGet();
        assertTrue(indexResponse.isCreated());

        indexResponse = client().prepareIndex("test", "type", "1").setSource("field1", "value1_2").execute().actionGet();
        assertFalse(indexResponse.isCreated());

        client().prepareDelete("test", "type", "1").execute().actionGet();

        indexResponse = client().prepareIndex("test", "type", "1").setSource("field1", "value1_2").execute().actionGet();
        assertTrue(indexResponse.isCreated());

    }

    @Test
    public void testCreatedFlagWithFlush() throws Exception {
        createIndex("test");
        ensureGreen();

        IndexResponse indexResponse = client().prepareIndex("test", "type", "1").setSource("field1", "value1_1").execute().actionGet();
        assertTrue(indexResponse.isCreated());

        client().prepareDelete("test", "type", "1").execute().actionGet();

        flush();

        indexResponse = client().prepareIndex("test", "type", "1").setSource("field1", "value1_2").execute().actionGet();
        assertTrue(indexResponse.isCreated());
    }

    @Test
    public void testCreatedFlagParallelExecution() throws Exception {
        createIndex("test");
        ensureGreen();

        int threadCount = 20;
        final int docCount = 300;
        int taskCount = docCount * threadCount;

        final AtomicIntegerArray createdCounts = new AtomicIntegerArray(docCount);
        ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
        List<Callable<Void>> tasks = new ArrayList<>(taskCount);
        final Random random = getRandom();
        for (int i=0;i< taskCount; i++ ) {
            tasks.add(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    int docId = random.nextInt(docCount);
                    IndexResponse indexResponse = index("test", "type", Integer.toString(docId), "field1", "value");
                    if (indexResponse.isCreated()) createdCounts.incrementAndGet(docId);
                    return null;
                }
            });
        }

        threadPool.invokeAll(tasks);

        for (int i=0;i<docCount;i++) {
            assertThat(createdCounts.get(i), lessThanOrEqualTo(1));
        }
    }

    @Test
    public void testCreatedFlagWithExternalVersioning() throws Exception {
        createIndex("test");
        ensureGreen();

        IndexResponse indexResponse = client().prepareIndex("test", "type", "1").setSource("field1", "value1_1").setVersion(123)
                                              .setVersionType(VersionType.EXTERNAL).execute().actionGet();
        assertTrue(indexResponse.isCreated());
    }

    @Test
    public void testCreateFlagWithBulk() {
        createIndex("test");
        ensureGreen();

        BulkResponse bulkResponse = client().prepareBulk().add(client().prepareIndex("test", "type", "1").setSource("field1", "value1_1")).execute().actionGet();
        assertThat(bulkResponse.hasFailures(), equalTo(false));
        assertThat(bulkResponse.getItems().length, equalTo(1));
        IndexResponse indexResponse = bulkResponse.getItems()[0].getResponse();
        assertTrue(indexResponse.isCreated());
    }
}

@@ -862,32 +862,91 @@
 k.BulkResponse;%0A
+import org.elasticsearch.action.index.IndexRequestBuilder;%0A
 import org.elast
@@ -974,32 +974,32 @@
 .IndexResponse;%0A
-
 import org.elast
@@ -1364,16 +1364,102 @@
 Array;%0A%0A
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;%0A
 import s
@@ -1562,16 +1562,16 @@
 %0A *%0A */%0A
-
 public c
@@ -1632,16 +1632,981 @@
 Test %7B%0A%0A
+    /**%0A     * This test tries to simulate load while creating an index and indexing documents%0A     * while the index is being created.%0A     */%0A    @Test%0A    public void testAutoGenerateIdNoDuplicates() throws Exception %7B%0A        int numberOfIterations = randomIntBetween(10, 50);%0A        for (int i = 0; i %3C numberOfIterations; i++) %7B%0A            createIndex(%22test%22);%0A            int numOfDocs = randomIntBetween(10, 100);%0A            List%3CIndexRequestBuilder%3E builders = new ArrayList%3C%3E(numOfDocs);%0A            for (int j = 0; j %3C numOfDocs; j++) %7B%0A                builders.add(client().prepareIndex(%22test%22, %22type%22).setSource(%22field%22, %22value%22));%0A            %7D%0A            indexRandom(true, builders);%0A            int numOfChecks = randomIntBetween(5, 10);%0A            for (int j = 0; j %3C numOfChecks; j++) %7B%0A                assertHitCount(client().prepareSearch(%22test%22).get(), numOfDocs);%0A            %7D%0A            cluster().wipeIndices(%22test%22);%0A        %7D%0A    %7D%0A%0A
     @Tes

add a test that explicitly verifies no duplicates are created we do this test in other places in ES, but no dedicated test for it. This test was born out of the auto generate id work, but we should have this test regardless if it gets in or not