Search in sources :

Example 46 with HttpExchange

use of com.sun.net.httpserver.HttpExchange in project connect-java-library by urbanairship.

the class StreamConnectionTest method testConnectionBadRequest.

@Test
public void testConnectionBadRequest() throws Exception {
    Answer httpAnswer = new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            HttpExchange exchange = (HttpExchange) invocation.getArguments()[0];
            exchange.sendResponseHeaders(403, 0L);
            exchange.close();
            return null;
        }
    };
    doAnswer(httpAnswer).when(serverHandler).handle(Matchers.<HttpExchange>any());
    expectedException.expect(ConnectionException.class);
    stream = new StreamConnection(descriptor(), http, connectionRetryStrategy, consumer, url);
    stream.read(Optional.<StartPosition>absent());
}
Also used : Mockito.doAnswer(org.mockito.Mockito.doAnswer) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpExchange(com.sun.net.httpserver.HttpExchange) Test(org.junit.Test)

Example 47 with HttpExchange

use of com.sun.net.httpserver.HttpExchange in project connect-java-library by urbanairship.

the class StreamConnectionTest method testConnectionRetry.

@Test
public void testConnectionRetry() throws Exception {
    Answer errorAnswer = new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            HttpExchange exchange = (HttpExchange) invocation.getArguments()[0];
            exchange.sendResponseHeaders(500, 0L);
            exchange.close();
            return null;
        }
    };
    final CountDownLatch successAnswerLatch = new CountDownLatch(1);
    Answer successAnswer = new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            HttpExchange exchange = (HttpExchange) invocation.getArguments()[0];
            exchange.sendResponseHeaders(200, 0L);
            successAnswerLatch.countDown();
            return null;
        }
    };
    doAnswer(errorAnswer).doAnswer(errorAnswer).doAnswer(successAnswer).when(serverHandler).handle(Matchers.<HttpExchange>any());
    ConnectionRetryStrategy strat = mock(ConnectionRetryStrategy.class);
    when(strat.shouldRetry(anyInt())).thenAnswer(new Answer<Boolean>() {

        @Override
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            Integer i = (Integer) invocation.getArguments()[0];
            return i < 3;
        }
    });
    when(strat.getPauseMillis(anyInt())).thenReturn(0L);
    ExecutorService thread = Executors.newSingleThreadExecutor();
    stream = new StreamConnection(descriptor(), http, strat, consumer, url);
    try {
        thread.submit(new Runnable() {

            @Override
            public void run() {
                try {
                    stream.read(Optional.<StartPosition>absent());
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        assertTrue(successAnswerLatch.await(10, TimeUnit.SECONDS));
        ArgumentCaptor<Integer> captor = ArgumentCaptor.forClass(Integer.class);
        verify(strat, times(2)).shouldRetry(captor.capture());
        assertEquals(ImmutableList.of(1, 2), captor.getAllValues());
    } finally {
        stream.close();
        thread.shutdownNow();
    }
}
Also used : HttpExchange(com.sun.net.httpserver.HttpExchange) CountDownLatch(java.util.concurrent.CountDownLatch) StartPosition(com.urbanairship.connect.client.model.request.StartPosition) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) ExecutorService(java.util.concurrent.ExecutorService) ConnectionRetryStrategy(com.urbanairship.connect.client.consume.ConnectionRetryStrategy) Test(org.junit.Test)

Example 48 with HttpExchange

use of com.sun.net.httpserver.HttpExchange in project connect-java-library by urbanairship.

the class StreamConnectionTest method testConnectRedirect.

@Test
public void testConnectRedirect() throws Exception {
    final String leaderHost = "SRV=" + randomAlphanumeric(15);
    final AtomicReference<String> receivedLeaderHost = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);
    Answer firstHttpAnswer = new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            HttpExchange exchange = (HttpExchange) invocation.getArguments()[0];
            exchange.getResponseHeaders().add("Set-Cookie", leaderHost);
            exchange.sendResponseHeaders(307, 0L);
            exchange.close();
            return null;
        }
    };
    Answer secondHttpAnswer = new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            HttpExchange exchange = (HttpExchange) invocation.getArguments()[0];
            String value = exchange.getRequestHeaders().getFirst("Cookie");
            receivedLeaderHost.set(value);
            exchange.sendResponseHeaders(200, 0L);
            exchange.close();
            latch.countDown();
            return null;
        }
    };
    doAnswer(firstHttpAnswer).doAnswer(secondHttpAnswer).when(serverHandler).handle(Matchers.<HttpExchange>any());
    stream = new StreamConnection(descriptor(), http, connectionRetryStrategy, consumer, url);
    read(stream, Optional.<StartPosition>absent());
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertEquals(leaderHost, receivedLeaderHost.get());
}
Also used : Mockito.doAnswer(org.mockito.Mockito.doAnswer) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpExchange(com.sun.net.httpserver.HttpExchange) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.anyString(org.mockito.Matchers.anyString) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 49 with HttpExchange

use of com.sun.net.httpserver.HttpExchange in project connect-java-library by urbanairship.

the class StreamConnectionTest method testRequestWithRelativeOffsetEarliest.

@Test
public void testRequestWithRelativeOffsetEarliest() throws Exception {
    final AtomicReference<String> body = new AtomicReference<>();
    final CountDownLatch received = new CountDownLatch(1);
    Answer httpAnswer = new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            HttpExchange exchange = (HttpExchange) invocation.getArguments()[0];
            int length = Integer.parseInt(exchange.getRequestHeaders().getFirst(HttpHeaders.CONTENT_LENGTH));
            byte[] bytes = new byte[length];
            exchange.getRequestBody().read(bytes);
            body.set(new String(bytes, UTF_8));
            exchange.sendResponseHeaders(200, 0L);
            received.countDown();
            return null;
        }
    };
    doAnswer(httpAnswer).when(serverHandler).handle(Matchers.<HttpExchange>any());
    StreamQueryDescriptor descriptor = descriptor();
    stream = new StreamConnection(descriptor, http, connectionRetryStrategy, consumer, url);
    read(stream, Optional.of(StartPosition.relative(StartPosition.RelativePosition.EARLIEST)));
    assertTrue(received.await(10, TimeUnit.SECONDS));
    JsonObject bodyObj = parser.parse(body.get()).getAsJsonObject();
    assertEquals("EARLIEST", bodyObj.get("start").getAsString());
}
Also used : Mockito.doAnswer(org.mockito.Mockito.doAnswer) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpExchange(com.sun.net.httpserver.HttpExchange) JsonObject(com.google.gson.JsonObject) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.anyString(org.mockito.Matchers.anyString) CountDownLatch(java.util.concurrent.CountDownLatch) StreamQueryDescriptor(com.urbanairship.connect.client.model.StreamQueryDescriptor) Test(org.junit.Test)

Example 50 with HttpExchange

use of com.sun.net.httpserver.HttpExchange in project connect-java-library by urbanairship.

the class StreamConnectionTest method testAuth.

@Test
public void testAuth() throws Exception {
    final AtomicReference<String> authorization = new AtomicReference<>();
    final AtomicReference<String> appKeyHeader = new AtomicReference<>();
    final CountDownLatch received = new CountDownLatch(1);
    Answer httpAnswer = new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            HttpExchange exchange = (HttpExchange) invocation.getArguments()[0];
            authorization.set(exchange.getRequestHeaders().getFirst(HttpHeaders.AUTHORIZATION));
            appKeyHeader.set(exchange.getRequestHeaders().getFirst("X-UA-Appkey"));
            exchange.sendResponseHeaders(200, 0L);
            received.countDown();
            return null;
        }
    };
    doAnswer(httpAnswer).when(serverHandler).handle(Matchers.<HttpExchange>any());
    StreamQueryDescriptor descriptor = descriptor();
    stream = new StreamConnection(descriptor, http, connectionRetryStrategy, consumer, url);
    read(stream, Optional.<StartPosition>absent());
    assertTrue(received.await(10, TimeUnit.SECONDS));
    assertTrue(authorization.get().toLowerCase().startsWith("bearer"));
    String token = authorization.get().substring("bearer ".length());
    assertEquals(descriptor.getCreds().getAppKey(), appKeyHeader.get());
    assertEquals(descriptor.getCreds().getToken(), token);
}
Also used : Mockito.doAnswer(org.mockito.Mockito.doAnswer) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpExchange(com.sun.net.httpserver.HttpExchange) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.anyString(org.mockito.Matchers.anyString) CountDownLatch(java.util.concurrent.CountDownLatch) StreamQueryDescriptor(com.urbanairship.connect.client.model.StreamQueryDescriptor) Test(org.junit.Test)

Aggregations

HttpExchange (com.sun.net.httpserver.HttpExchange)56 Test (org.junit.Test)36 IOException (java.io.IOException)25 HttpHandler (com.sun.net.httpserver.HttpHandler)22 InetSocketAddress (java.net.InetSocketAddress)19 OutputStream (java.io.OutputStream)18 Mockito.doAnswer (org.mockito.Mockito.doAnswer)16 InvocationOnMock (org.mockito.invocation.InvocationOnMock)16 Answer (org.mockito.stubbing.Answer)16 CountDownLatch (java.util.concurrent.CountDownLatch)12 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)12 HttpServer (com.sun.net.httpserver.HttpServer)11 Matchers.anyString (org.mockito.Matchers.anyString)11 Headers (com.sun.net.httpserver.Headers)10 AtomicReference (java.util.concurrent.atomic.AtomicReference)10 StreamQueryDescriptor (com.urbanairship.connect.client.model.StreamQueryDescriptor)9 InputStream (java.io.InputStream)9 JsonObject (com.google.gson.JsonObject)8 ByteArrayInputStream (java.io.ByteArrayInputStream)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4