Search in sources :

Example 41 with HttpExchange

use of com.sun.net.httpserver.HttpExchange in project metrics by dropwizard.

the class InstrumentedHttpAsyncClientsTest method registersExpectedExceptionMetrics.

@Test
public void registersExpectedExceptionMetrics() throws Exception {
    client = InstrumentedHttpAsyncClients.custom(metricRegistry, metricNameStrategy).disableAutomaticRetries().build();
    client.start();
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final SimpleHttpRequest request = SimpleHttpRequests.get("http://localhost:" + httpServer.getAddress().getPort() + "/");
    final String requestMetricName = "request";
    final String exceptionMetricName = "exception";
    httpServer.createContext("/", HttpExchange::close);
    httpServer.start();
    when(metricNameStrategy.getNameFor(any(), any(HttpRequest.class))).thenReturn(requestMetricName);
    when(metricNameStrategy.getNameFor(any(), any(Exception.class))).thenReturn(exceptionMetricName);
    try {
        final Future<SimpleHttpResponse> responseFuture = client.execute(request, new FutureCallback<SimpleHttpResponse>() {

            @Override
            public void completed(SimpleHttpResponse result) {
                fail();
            }

            @Override
            public void failed(Exception ex) {
                countDownLatch.countDown();
            }

            @Override
            public void cancelled() {
                fail();
            }
        });
        countDownLatch.await(5, TimeUnit.SECONDS);
        responseFuture.get(5, TimeUnit.SECONDS);
        fail();
    } catch (ExecutionException e) {
        assertThat(e).hasCauseInstanceOf(ConnectionClosedException.class);
        await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> assertThat(metricRegistry.getMeters()).containsKey("exception"));
    }
}
Also used : SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) HttpExchange(com.sun.net.httpserver.HttpExchange) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) CountDownLatch(java.util.concurrent.CountDownLatch) ExecutionException(java.util.concurrent.ExecutionException) IOException(java.io.IOException) ConnectionClosedException(org.apache.hc.core5.http.ConnectionClosedException) ExecutionException(java.util.concurrent.ExecutionException) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) Test(org.junit.Test)

Example 42 with HttpExchange

use of com.sun.net.httpserver.HttpExchange in project gradle by gradle.

the class GitHttpRepository method getRefsAction.

private Action<HttpExchange> getRefsAction() {
    return new ErroringAction<HttpExchange>() {

        @Override
        protected void doExecute(HttpExchange httpExchange) throws Exception {
            ProcessBuilder builder = new ProcessBuilder();
            Process process = builder.command("git", "upload-pack", "--advertise-refs", backingRepo.getWorkTree().getAbsolutePath()).redirectErrorStream(true).start();
            ByteArrayOutputStream content = new ByteArrayOutputStream();
            content.write("001e# service=git-upload-pack\n".getBytes());
            content.write("0000".getBytes());
            IOUtils.copy(process.getInputStream(), content);
            process.waitFor();
            int result = process.waitFor();
            if (result != 0) {
                throw new RuntimeException("Failed to run git upload-pack");
            }
            byte[] bytes = content.toByteArray();
            httpExchange.getResponseHeaders().add("content-type", "application/x-git-upload-pack-advertisement");
            httpExchange.sendResponseHeaders(200, bytes.length);
            httpExchange.getResponseBody().write(bytes);
        }
    };
}
Also used : ErroringAction(org.gradle.internal.ErroringAction) HttpExchange(com.sun.net.httpserver.HttpExchange) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 43 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)

Example 44 with HttpExchange

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

the class StreamConnectionTest method testCloseKillsConsume.

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

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            HttpExchange exchange = (HttpExchange) invocation.getArguments()[0];
            exchange.sendResponseHeaders(200, 0L);
            // hoping this is enough to force flushing data down the wire
            exchange.getResponseBody().write(randomAlphabetic(10000).getBytes(UTF_8));
            exchange.getResponseBody().write("\n".getBytes(UTF_8));
            exchange.getResponseBody().flush();
            return null;
        }
    };
    doAnswer(httpAnswer).when(serverHandler).handle(Matchers.<HttpExchange>any());
    final CountDownLatch latch = new CountDownLatch(1);
    Answer consumerAnswer = new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            latch.countDown();
            return null;
        }
    };
    doAnswer(consumerAnswer).when(consumer).accept(anyString());
    stream = new StreamConnection(descriptor(), http, connectionRetryStrategy, consumer, url);
    ExecutorService thread = Executors.newSingleThreadExecutor();
    Callable<Boolean> callable = new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            stream.read(Optional.<StartPosition>absent());
            return Boolean.TRUE;
        }
    };
    try {
        Future<Boolean> future = thread.submit(callable);
        // Wait till we get something from the server
        latch.await(1, TimeUnit.MINUTES);
        // Now kill the stream
        stream.close();
        // Consume future should return without issue now
        try {
            future.get(1, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            fail();
        }
    } finally {
        thread.shutdownNow();
    }
}
Also used : Mockito.doAnswer(org.mockito.Mockito.doAnswer) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpExchange(com.sun.net.httpserver.HttpExchange) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) ExecutorService(java.util.concurrent.ExecutorService) CountDownLatch(java.util.concurrent.CountDownLatch) Callable(java.util.concurrent.Callable) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Example 45 with HttpExchange

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

the class StreamConnectionTest method testExceptionDuringConsume.

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

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            HttpExchange exchange = (HttpExchange) invocation.getArguments()[0];
            exchange.sendResponseHeaders(200, 0L);
            exchange.getResponseBody().write(randomAlphabetic(10).getBytes(UTF_8));
            exchange.getResponseBody().write("\n".getBytes(UTF_8));
            exchange.getResponseBody().flush();
            return null;
        }
    };
    doAnswer(httpAnswer).when(serverHandler).handle(Matchers.<HttpExchange>any());
    doThrow(new RuntimeException("boom")).when(consumer).accept(anyString());
    stream = new StreamConnection(descriptor(), http, connectionRetryStrategy, consumer, url);
    expectedException.expect(RuntimeException.class);
    stream.read(Optional.<StartPosition>absent());
    stream.wait(100);
}
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)

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