/*
 * 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.facebook.presto.server;

import com.facebook.presto.client.QueryResults;
import com.facebook.presto.server.testing.TestingPrestoServer;
import io.airlift.http.client.HttpClient;
import io.airlift.http.client.HttpUriBuilder;
import io.airlift.http.client.Request;
import io.airlift.http.client.UnexpectedResponseException;
import io.airlift.http.client.jetty.JettyHttpClient;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.util.List;

import static com.facebook.presto.client.PrestoHeaders.PRESTO_USER;
import static com.facebook.presto.testing.assertions.Assert.assertEquals;
import static io.airlift.http.client.JsonResponseHandler.createJsonResponseHandler;
import static io.airlift.http.client.Request.Builder.prepareGet;
import static io.airlift.http.client.Request.Builder.preparePost;
import static io.airlift.http.client.StaticBodyGenerator.createStaticBodyGenerator;
import static io.airlift.json.JsonCodec.jsonCodec;
import static io.airlift.json.JsonCodec.listJsonCodec;
import static io.airlift.testing.Closeables.closeQuietly;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;

@Test(singleThreaded = true)
public class TestQueryStateInfoResource
{
    private TestingPrestoServer server;
    private HttpClient client;
    private QueryResults queryResults;

    TestQueryStateInfoResource()
            throws Exception
    {
        server = new TestingPrestoServer();
        client = new JettyHttpClient();
    }

    @BeforeClass
    public void setup()
    {
        Request request1 = preparePost()
                .setUri(HttpUriBuilder.uriBuilderFrom(server.getBaseUrl()).replacePath("/v1/statement").build())
                .setBodyGenerator(createStaticBodyGenerator("show catalogs", UTF_8))
                .setHeader(PRESTO_USER, "user1")
                .build();
        queryResults = client.execute(request1, createJsonResponseHandler(jsonCodec(QueryResults.class)));

        Request request2 = preparePost()
                .setUri(HttpUriBuilder.uriBuilderFrom(server.getBaseUrl()).replacePath("/v1/statement").build())
                .setBodyGenerator(createStaticBodyGenerator("show catalogs", UTF_8))
                .setHeader(PRESTO_USER, "user2")
                .build();
        client.execute(request2, createJsonResponseHandler(jsonCodec(QueryResults.class)));
    }

    @AfterClass(alwaysRun = true)
    public void teardown()
    {
        closeQuietly(server);
        closeQuietly(client);
    }

    @Test
    public void testGetAllQueryStateInfos()
    {
        List<QueryStateInfo> infos = client.execute(
                prepareGet().setUri(server.resolve("/v1/queryState")).build(),
                createJsonResponseHandler(listJsonCodec(QueryStateInfo.class)));

        assertEquals(infos.size(), 2);
    }

    @Test
    public void testGetQueryStateInfosForUser()
    {
        List<QueryStateInfo> infos = client.execute(
                prepareGet().setUri(server.resolve("/v1/queryState?user=user2")).build(),
                createJsonResponseHandler(listJsonCodec(QueryStateInfo.class)));

        assertEquals(infos.size(), 1);
    }

    @Test
    public void testGetQueryStateInfosForUserNoResult()
    {
        List<QueryStateInfo> infos = client.execute(
                prepareGet().setUri(server.resolve("/v1/queryState?user=user3")).build(),
                createJsonResponseHandler(listJsonCodec(QueryStateInfo.class)));

        assertTrue(infos.isEmpty());
    }

    @Test
    public void testGetQueryStateInfo()
    {
        QueryStateInfo info = client.execute(
                prepareGet().setUri(server.resolve("/v1/queryState/" + queryResults.getId())).build(),
                createJsonResponseHandler(jsonCodec(QueryStateInfo.class)));

        assertNotNull(info);
    }

    @Test(expectedExceptions = {UnexpectedResponseException.class}, expectedExceptionsMessageRegExp = ".*404: Not Found")
    public void testGetQueryStateInfoNo()
    {
        client.execute(
                prepareGet().setUri(server.resolve("/v1/queryState/123")).build(),
                createJsonResponseHandler(jsonCodec(QueryStateInfo.class)));
    }
}

@@ -749,54 +749,8 @@
 nt;%0A
-import io.airlift.http.client.HttpUriBuilder;%0A
 impo
@@ -780,24 +780,24 @@
 nt.Request;%0A
+
 import io.ai
@@ -1110,16 +1110,79 @@
 O_USER;%0A
+import static com.facebook.presto.execution.QueryState.QUEUED;%0A
 import s
@@ -1247,16 +1247,84 @@
 Equals;%0A
+import static io.airlift.http.client.HttpUriBuilder.uriBuilderFrom;%0A
 import s
@@ -2374,39 +2374,24 @@
     .setUri(
-HttpUriBuilder.
 uriBuilderFr
@@ -2785,31 +2785,16 @@
 .setUri(
-HttpUriBuilder.
 uriBuild
@@ -3011,32 +3011,32 @@
       .build();%0A
-
         client.e
@@ -3106,24 +3106,572 @@
 ts.class)));
+%0A%0A        boolean queued = true;%0A        while (queued) %7B%0A            queued = false;%0A            List%3CBasicQueryInfo%3E queryInfos = client.execute(%0A                    prepareGet().setUri(uriBuilderFrom(server.getBaseUrl()).replacePath(%22/v1/query%22).build()).build(),%0A                    createJsonResponseHandler(listJsonCodec(BasicQueryInfo.class)));%0A            assertEquals(queryInfos.size(), 2);%0A            for (BasicQueryInfo queryInfo : queryInfos) %7B%0A                queued = queued %7C%7C queryInfo.getState() == QUEUED;%0A            %7D%0A        %7D
 %0A    %7D%0A%0A    

Fix flaky TestQueryStateInfoResource