/*
 * Copyright 2010 Ning, Inc.
 *
 * Ning 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.asynchttpclient.async;

import static org.asynchttpclient.async.util.TestUtils.SIMPLE_TEXT_FILE;
import static org.asynchttpclient.async.util.TestUtils.SIMPLE_TEXT_FILE_STRING;
import static org.asynchttpclient.async.util.TestUtils.createSSLContext;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;

import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.AsyncHttpClientConfig.Builder;
import org.asynchttpclient.Response;
import org.testng.annotations.Test;

import javax.net.ssl.SSLHandshakeException;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.net.ConnectException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public abstract class BasicHttpsTest extends AbstractBasicHttpsTest {

    protected String getTargetUrl() {
        return String.format("https://127.0.0.1:%d/foo/test", port1);
    }

    @Test(groups = { "standalone", "default_provider" })
    public void zeroCopyPostTest() throws Exception {

        final AsyncHttpClient client = getAsyncHttpClient(new Builder().setSSLContext(createSSLContext(new AtomicBoolean(true))).build());
        try {
            Response resp = client.preparePost(getTargetUrl()).setBody(SIMPLE_TEXT_FILE).setHeader("Content-Type", "text/html").execute().get();
            assertNotNull(resp);
            assertEquals(resp.getStatusCode(), HttpServletResponse.SC_OK);
            assertEquals(resp.getResponseBody(), SIMPLE_TEXT_FILE_STRING);
        } finally {
            client.close();
        }
    }

    @Test(groups = { "standalone", "default_provider" })
    public void multipleSSLRequestsTest() throws Exception {
        final AsyncHttpClient c = getAsyncHttpClient(new Builder().setSSLContext(createSSLContext(new AtomicBoolean(true))).build());
        try {
            String body = "hello there";

            // once
            Response response = c.preparePost(getTargetUrl()).setBody(body).setHeader("Content-Type", "text/html").execute().get(TIMEOUT, TimeUnit.SECONDS);

            assertEquals(response.getResponseBody(), body);

            // twice
            response = c.preparePost(getTargetUrl()).setBody(body).setHeader("Content-Type", "text/html").execute().get(TIMEOUT, TimeUnit.SECONDS);

            assertEquals(response.getResponseBody(), body);
        } finally {
            c.close();
        }
    }

    @Test(groups = { "standalone", "default_provider" })
    public void multipleSSLWithoutCacheTest() throws Exception {
        AsyncHttpClient c = getAsyncHttpClient(new Builder().setSSLContext(createSSLContext(new AtomicBoolean(true))).setAllowSslConnectionPool(false).build());
        try {
            String body = "hello there";
            c.preparePost(getTargetUrl()).setBody(body).setHeader("Content-Type", "text/html").execute();

            c.preparePost(getTargetUrl()).setBody(body).setHeader("Content-Type", "text/html").execute();

            Response response = c.preparePost(getTargetUrl()).setBody(body).setHeader("Content-Type", "text/html").execute().get();

            assertEquals(response.getResponseBody(), body);
        } finally {
            c.close();
        }
    }

    @Test(groups = { "standalone", "default_provider" })
    public void reconnectsAfterFailedCertificationPath() throws Exception {
        AtomicBoolean trusted = new AtomicBoolean(false);
        AsyncHttpClient c = getAsyncHttpClient(new Builder().setSSLContext(createSSLContext(trusted)).build());
        try {
            String body = "hello there";

            // first request fails because server certificate is rejected
            Throwable cause = null;
            try {
                c.preparePost(getTargetUrl()).setBody(body).setHeader("Content-Type", "text/html").execute().get(TIMEOUT, TimeUnit.SECONDS);
            } catch (final ExecutionException e) {
                cause = e.getCause();
                if (cause instanceof ConnectException) {
                    //assertNotNull(cause.getCause());
                    assertTrue(cause.getCause() instanceof SSLHandshakeException, "Expected an SSLHandshakeException, got a " + cause.getCause());
                } else {
                   assertTrue(cause instanceof IOException, "Expected an IOException, got a " + cause);
                }
            }
            assertNotNull(cause);

            trusted.set(true);

            // second request should succeed
            Response response = c.preparePost(getTargetUrl()).setBody(body).setHeader("Content-Type", "text/html").execute().get(TIMEOUT, TimeUnit.SECONDS);

            assertEquals(response.getResponseBody(), body);
        } finally {
            c.close();
        }
    }
}

@@ -1150,16 +1150,42 @@
 sponse;%0A
+import org.testng.Assert;%0A
 import o
@@ -1234,34 +1234,106 @@
 net.ssl.
-SSLHandshakeExcept
+HostnameVerifier;%0Aimport javax.net.ssl.SSLHandshakeException;%0Aimport javax.net.ssl.SSLSess
 ion;%0Aimp
@@ -5587,11 +5587,1146 @@
  %7D%0A    %7D
+%0A%0A    @Test(timeOut = 5000)%0A    public void failInstantlyIfHostNamesDiffer() throws Exception %7B%0A        AsyncHttpClient client = null;%0A%0A        try %7B%0A            final Builder builder = new Builder().setHostnameVerifier(new HostnameVerifier() %7B%0A%0A                public boolean verify(String arg0, SSLSession arg1) %7B%0A                    return false;%0A                %7D%0A            %7D).setRequestTimeoutInMs(20000);%0A%0A            client = getAsyncHttpClient(builder.build());%0A%0A            try %7B%0A            client.prepareGet(%22https://github.com/AsyncHttpClient/async-http-client/issues/355%22).execute().get(TIMEOUT, TimeUnit.SECONDS);%0A            %0A            Assert.assertTrue(false, %22Shouldn't be here: should get an Exception%22);%0A            %7D catch (ExecutionException e) %7B%0A                Assert.assertTrue(e.getCause() instanceof ConnectException, %22Cause should be a ConnectException%22);%0A            %7D catch (Exception e) %7B%0A                Assert.assertTrue(false, %22Shouldn't be here: should get a ConnectException wrapping a ConnectException%22);%0A            %7D%0A            %0A        %7D finally %7B%0A            client.close();%0A        %7D%0A    %7D
 %0A%7D%0A

Add #355 test on master: both Netty and Grizzly are OK