Search in sources :

Example 51 with Headers

use of com.sun.net.httpserver.Headers in project component-runtime by Talend.

the class HttpClientFactoryImplTest method createTestServer.

private HttpServer createTestServer(int responseStatus) throws IOException {
    final HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    server.createContext("/").setHandler(httpExchange -> {
        final Headers headers = httpExchange.getRequestHeaders();
        final byte[] bytes;
        try (final BufferedReader in = new BufferedReader(new InputStreamReader(httpExchange.getRequestBody(), StandardCharsets.UTF_8))) {
            bytes = (httpExchange.getRequestMethod() + "@" + headers.keySet().stream().sorted().filter(k -> !asList("Accept", "Host", "User-agent").contains(k)).map(k -> k + "=" + headers.getFirst(k)).collect(joining("/")) + "@" + httpExchange.getRequestURI().toASCIIString() + "@" + in.lines().collect(joining("\n"))).getBytes(StandardCharsets.UTF_8);
        }
        httpExchange.sendResponseHeaders(responseStatus, bytes.length);
        httpExchange.getResponseBody().write(bytes);
        httpExchange.close();
    });
    return server;
}
Also used : Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) HttpURLConnection(java.net.HttpURLConnection) HttpServer(com.sun.net.httpserver.HttpServer) HttpClient(org.talend.sdk.component.api.service.http.HttpClient) Response(org.talend.sdk.component.api.service.http.Response) Decoder(org.talend.sdk.component.api.service.http.Decoder) HashMap(java.util.HashMap) HttpException(org.talend.sdk.component.api.service.http.HttpException) Path(org.talend.sdk.component.api.service.http.Path) Collections.singletonList(java.util.Collections.singletonList) Encoder(org.talend.sdk.component.api.service.http.Encoder) Internationalized(org.talend.sdk.component.api.internationalization.Internationalized) Collectors.toMap(java.util.stream.Collectors.toMap) Query(org.talend.sdk.component.api.service.http.Query) Arrays.asList(java.util.Arrays.asList) ParameterModelService(org.talend.sdk.component.runtime.manager.reflect.ParameterModelService) Map(java.util.Map) Headers(com.sun.net.httpserver.Headers) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Request(org.talend.sdk.component.api.service.http.Request) Collections.emptyMap(java.util.Collections.emptyMap) JsonbBuilder(javax.json.bind.JsonbBuilder) Collection(java.util.Collection) IOException(java.io.IOException) Codec(org.talend.sdk.component.api.service.http.Codec) XmlRootElement(javax.xml.bind.annotation.XmlRootElement) InputStreamReader(java.io.InputStreamReader) InetSocketAddress(java.net.InetSocketAddress) Collectors.joining(java.util.stream.Collectors.joining) StandardCharsets(java.nio.charset.StandardCharsets) Test(org.junit.jupiter.api.Test) Header(org.talend.sdk.component.api.service.http.Header) Stream(java.util.stream.Stream) Type(java.lang.reflect.Type) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Data(lombok.Data) Service(org.talend.sdk.component.api.service.Service) BufferedReader(java.io.BufferedReader) ReflectionService(org.talend.sdk.component.runtime.manager.reflect.ReflectionService) AllArgsConstructor(lombok.AllArgsConstructor) NoArgsConstructor(lombok.NoArgsConstructor) InputStreamReader(java.io.InputStreamReader) InetSocketAddress(java.net.InetSocketAddress) Headers(com.sun.net.httpserver.Headers) HttpServer(com.sun.net.httpserver.HttpServer) BufferedReader(java.io.BufferedReader)

Example 52 with Headers

use of com.sun.net.httpserver.Headers in project component-runtime by Talend.

the class CaptureJUnit4HttpApiTest method doCapture.

@Test
public void doCapture() throws Throwable {
    final HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    server.createContext("/").setHandler(httpExchange -> {
        final Headers headers = httpExchange.getRequestHeaders();
        final byte[] bytes;
        try (final BufferedReader in = new BufferedReader(new InputStreamReader(httpExchange.getRequestBody(), StandardCharsets.UTF_8))) {
            bytes = (httpExchange.getRequestMethod() + "@" + headers.keySet().stream().sorted().filter(k -> !asList("Accept", "Host", "User-agent").contains(k)).map(k -> k + "=" + headers.getFirst(k)).collect(joining("/")) + "@" + httpExchange.getRequestURI().toASCIIString() + "@" + in.lines().collect(joining("\n"))).getBytes(StandardCharsets.UTF_8);
        }
        httpExchange.sendResponseHeaders(200, bytes.length);
        httpExchange.getResponseBody().write(bytes);
        httpExchange.close();
    });
    server.start();
    final Path output = TEMPORARY_FOLDER.getRoot().toPath().toAbsolutePath().resolve("talend/testing/http/" + getClass().getName() + "_doCapture.json");
    try {
        new JUnit4HttpApiPerMethodConfigurator(API).apply(new Statement() {

            @Override
            public void evaluate() throws Throwable {
                final URL url = new URL("http://localhost:" + server.getAddress().getPort() + "/supertest");
                final HttpURLConnection connection = HttpURLConnection.class.cast(url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", API.getPort()))));
                connection.setConnectTimeout(30000);
                connection.setReadTimeout(20000);
                connection.setRequestProperty("Authorization", "should be filtered");
                connection.setRequestProperty("ok", "yes");
                assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
                connection.disconnect();
            }
        }, Description.createTestDescription(getClass(), "doCapture")).evaluate();
        assertTrue(output.toFile().exists());
        final String lines = Files.readAllLines(output).stream().collect(joining("\n"));
        assertEquals("[\n" + "  {\n" + "    \"request\":{\n" + "      \"headers\":{\n" + "        \"content-length\":\"0\",\n" + "        \"Accept\":\"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2\",\n" + "        \"ok\":\"yes\",\n" + "        \"Proxy-Connection\":\"keep-alive\"\n" + "      },\n" + "      \"method\":\"GET\",\n" + "      \"uri\":\"http://localhost:" + server.getAddress().getPort() + "/supertest\"\n" + "    },\n" + "    \"response\":{\n" + "      \"headers\":{\n" + "        \"Content-length\":\"105\"\n" + "      },\n" + "      \"payload\":\"GET@Authorization=should be filtered/Connection=keep-alive/Ok=yes/Proxy-connection=keep-alive@/supertest@\",\n" + "      \"status\":200\n" + "    }\n" + "  }\n" + "]", lines);
    } finally {
        server.stop(0);
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Statement(org.junit.runners.model.Statement) HttpServer(com.sun.net.httpserver.HttpServer) Files(java.nio.file.Files) TestRule(org.junit.rules.TestRule) URL(java.net.URL) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Description(org.junit.runner.Description) InputStreamReader(java.io.InputStreamReader) InetSocketAddress(java.net.InetSocketAddress) Collectors.joining(java.util.stream.Collectors.joining) StandardCharsets(java.nio.charset.StandardCharsets) ExternalResource(org.junit.rules.ExternalResource) Proxy(java.net.Proxy) Arrays.asList(java.util.Arrays.asList) Headers(com.sun.net.httpserver.Headers) RuleChain.emptyRuleChain(org.junit.rules.RuleChain.emptyRuleChain) BufferedReader(java.io.BufferedReader) ClassRule(org.junit.ClassRule) Path(java.nio.file.Path) Assert.assertEquals(org.junit.Assert.assertEquals) TemporaryFolder(org.junit.rules.TemporaryFolder) Path(java.nio.file.Path) InputStreamReader(java.io.InputStreamReader) InetSocketAddress(java.net.InetSocketAddress) Headers(com.sun.net.httpserver.Headers) Statement(org.junit.runners.model.Statement) URL(java.net.URL) Proxy(java.net.Proxy) HttpURLConnection(java.net.HttpURLConnection) HttpServer(com.sun.net.httpserver.HttpServer) BufferedReader(java.io.BufferedReader) Test(org.junit.Test)

Example 53 with Headers

use of com.sun.net.httpserver.Headers in project component-runtime by Talend.

the class CaptureJUnit4HttpsApiTest method doCapture.

@Test
public void doCapture() throws Throwable {
    final SelfSignedCertificate certificate = new SelfSignedCertificate();
    final SslContext nettyContext = SslContextBuilder.forServer(certificate.certificate(), certificate.privateKey()).trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(SslProvider.JDK).build();
    final HttpsServer server = HttpsServer.create(new InetSocketAddress(0), 0);
    server.setHttpsConfigurator(new HttpsConfigurator(JdkSslContext.class.cast(nettyContext).context()));
    server.createContext("/").setHandler(httpExchange -> {
        final Headers headers = httpExchange.getRequestHeaders();
        final byte[] bytes;
        try (final BufferedReader in = new BufferedReader(new InputStreamReader(httpExchange.getRequestBody(), StandardCharsets.UTF_8))) {
            bytes = (httpExchange.getRequestMethod() + "@" + headers.keySet().stream().sorted().filter(k -> !asList("Accept", "Host", "User-agent").contains(k)).map(k -> k + "=" + headers.getFirst(k)).collect(joining("/")) + "@" + httpExchange.getRequestURI().toASCIIString() + "@" + in.lines().collect(joining("\n"))).getBytes(StandardCharsets.UTF_8);
        }
        httpExchange.sendResponseHeaders(200, bytes.length);
        httpExchange.getResponseBody().write(bytes);
        httpExchange.close();
    });
    server.start();
    final Path output = TEMPORARY_FOLDER.getRoot().toPath().toAbsolutePath().resolve("talend/testing/http/" + getClass().getName() + "_doCapture.json");
    try {
        new JUnit4HttpApiPerMethodConfigurator(API).apply(new Statement() {

            @Override
            public void evaluate() throws Throwable {
                final URL url = new URL("https://localhost:" + server.getAddress().getPort() + "/supertest");
                final HttpsURLConnection connection = HttpsURLConnection.class.cast(url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", API.getPort()))));
                connection.setConnectTimeout(30000);
                connection.setReadTimeout(20000);
                connection.setHostnameVerifier((h, s) -> true);
                connection.setSSLSocketFactory(server.getHttpsConfigurator().getSSLContext().getSocketFactory());
                assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
                connection.disconnect();
            }
        }, Description.createTestDescription(getClass(), "doCapture")).evaluate();
        assertTrue(output.toFile().exists());
        final String lines = Files.readAllLines(output).stream().collect(joining("\n"));
        assertEquals("[\n" + "  {\n" + "    \"request\":{\n" + "      \"headers\":{\n" + "        \"content-length\":\"0\",\n" + "        \"Accept\":\"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2\",\n" + "        \"Connection\":\"keep-alive\"\n" + "      },\n" + "      \"method\":\"GET\",\n" + "      \"uri\":\"https://localhost:" + server.getAddress().getPort() + "/supertest\"\n" + "    },\n" + "    \"response\":{\n" + "      \"headers\":{\n" + "        \"Content-length\":\"37\"\n" + "      },\n" + "      \"payload\":\"GET@Connection=keep-alive@/supertest@\",\n" + "      \"status\":200\n" + "    }\n" + "  }\n" + "]", lines);
    } finally {
        server.stop(0);
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Statement(org.junit.runners.model.Statement) TestRule(org.junit.rules.TestRule) URL(java.net.URL) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) Proxy(java.net.Proxy) Arrays.asList(java.util.Arrays.asList) Headers(com.sun.net.httpserver.Headers) RuleChain.emptyRuleChain(org.junit.rules.RuleChain.emptyRuleChain) ClassRule(org.junit.ClassRule) Path(java.nio.file.Path) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) JdkSslContext(io.netty.handler.ssl.JdkSslContext) SslContext(io.netty.handler.ssl.SslContext) Files(java.nio.file.Files) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Description(org.junit.runner.Description) InputStreamReader(java.io.InputStreamReader) InetSocketAddress(java.net.InetSocketAddress) Collectors.joining(java.util.stream.Collectors.joining) StandardCharsets(java.nio.charset.StandardCharsets) ExternalResource(org.junit.rules.ExternalResource) SslProvider(io.netty.handler.ssl.SslProvider) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) BufferedReader(java.io.BufferedReader) HttpsConfigurator(com.sun.net.httpserver.HttpsConfigurator) HttpsServer(com.sun.net.httpserver.HttpsServer) Assert.assertEquals(org.junit.Assert.assertEquals) TemporaryFolder(org.junit.rules.TemporaryFolder) Path(java.nio.file.Path) HttpsConfigurator(com.sun.net.httpserver.HttpsConfigurator) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) JdkSslContext(io.netty.handler.ssl.JdkSslContext) InputStreamReader(java.io.InputStreamReader) InetSocketAddress(java.net.InetSocketAddress) Headers(com.sun.net.httpserver.Headers) Statement(org.junit.runners.model.Statement) URL(java.net.URL) Proxy(java.net.Proxy) BufferedReader(java.io.BufferedReader) HttpsServer(com.sun.net.httpserver.HttpsServer) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) JdkSslContext(io.netty.handler.ssl.JdkSslContext) SslContext(io.netty.handler.ssl.SslContext) Test(org.junit.Test)

Example 54 with Headers

use of com.sun.net.httpserver.Headers in project crate by crate.

the class AzureHttpHandler method sendError.

public static void sendError(final HttpExchange exchange, final RestStatus status) throws IOException {
    final Headers headers = exchange.getResponseHeaders();
    headers.add("Content-Type", "application/xml");
    // see Constants.HeaderConstants.CLIENT_REQUEST_ID_HEADER
    final String requestId = exchange.getRequestHeaders().getFirst("x-ms-client-request-id");
    if (requestId != null) {
        // see Constants.HeaderConstants.STORAGE_RANGE_HEADER
        headers.add("x-ms-request-id", requestId);
    }
    final String errorCode = toAzureErrorCode(status);
    // see Constants.HeaderConstants.ERROR_CODE
    headers.add("x-ms-error-code", errorCode);
    if ("HEAD".equals(exchange.getRequestMethod())) {
        exchange.sendResponseHeaders(status.getStatus(), -1L);
    } else {
        final byte[] response = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Error><Code>" + errorCode + "</Code><Message>" + status + "</Message></Error>").getBytes(StandardCharsets.UTF_8);
        exchange.sendResponseHeaders(status.getStatus(), response.length);
        exchange.getResponseBody().write(response);
    }
}
Also used : Headers(com.sun.net.httpserver.Headers)

Example 55 with Headers

use of com.sun.net.httpserver.Headers in project eureka by Netflix.

the class SimpleEurekaHttpServer method mapToEurekaHttpRequest.

private EurekaHttpRequest mapToEurekaHttpRequest(HttpExchange httpExchange) {
    Headers exchangeHeaders = httpExchange.getRequestHeaders();
    Map<String, String> headers = new HashMap<>();
    for (String key : exchangeHeaders.keySet()) {
        headers.put(key, exchangeHeaders.getFirst(key));
    }
    return new EurekaHttpRequest(httpExchange.getRequestMethod(), httpExchange.getRequestURI(), headers);
}
Also used : HashMap(java.util.HashMap) Headers(com.sun.net.httpserver.Headers)

Aggregations

Headers (com.sun.net.httpserver.Headers)56 OutputStream (java.io.OutputStream)23 IOException (java.io.IOException)17 InetSocketAddress (java.net.InetSocketAddress)12 InputStream (java.io.InputStream)10 HttpExchange (com.sun.net.httpserver.HttpExchange)9 Test (org.junit.Test)9 Test (org.junit.jupiter.api.Test)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 HttpServer (com.sun.net.httpserver.HttpServer)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 BufferedImage (java.awt.image.BufferedImage)5 BufferedReader (java.io.BufferedReader)5 InputStreamReader (java.io.InputStreamReader)5 Path (java.nio.file.Path)5 HashMap (java.util.HashMap)5 BeforeClass (org.junit.BeforeClass)5 Graphics2D (java.awt.Graphics2D)4 Image (java.awt.Image)4