Search in sources :

Example 36 with Headers

use of com.sun.net.httpserver.Headers in project heron by twitter.

the class NetworkUtilsTest method testReadHttpRequestBody.

@Test
public void testReadHttpRequestBody() throws Exception {
    byte[] expectedBytes = "TO READ".getBytes();
    InputStream is = Mockito.spy(new ByteArrayInputStream(expectedBytes));
    HttpExchange exchange = Mockito.mock(HttpExchange.class);
    Headers headers = Mockito.mock(Headers.class);
    Mockito.doReturn(Integer.toString(expectedBytes.length)).when(headers).getFirst(Matchers.anyString());
    Mockito.doReturn(headers).when(exchange).getRequestHeaders();
    Mockito.doReturn(is).when(exchange).getRequestBody();
    Assert.assertArrayEquals(expectedBytes, NetworkUtils.readHttpRequestBody(exchange));
    Mockito.verify(is, Mockito.atLeastOnce()).close();
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Headers(com.sun.net.httpserver.Headers) HttpExchange(com.sun.net.httpserver.HttpExchange) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 37 with Headers

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

the class RxHttpTest method startServer.

@BeforeClass
public static void startServer() throws Exception {
    server = HttpServer.create(new InetSocketAddress(0), 100);
    server.setExecutor(Executors.newFixedThreadPool(10, r -> new Thread(r, "HttpServer")));
    port = server.getAddress().getPort();
    server.createContext("/empty", exchange -> {
        ignore(exchange.getRequestBody());
        int port1 = exchange.getRemoteAddress().getPort();
        exchange.getResponseHeaders().add("X-Test-Port", "" + port1);
        statusCounts.incrementAndGet(statusCode.get());
        exchange.sendResponseHeaders(statusCode.get(), -1L);
        exchange.close();
    });
    server.createContext("/echo", exchange -> {
        Headers headers = exchange.getRequestHeaders();
        int contentLength = Integer.parseInt(headers.getFirst("Content-Length"));
        String contentEnc = headers.getFirst("Content-Encoding");
        if (contentEnc != null) {
            exchange.getResponseHeaders().add("Content-Encoding", contentEnc);
        }
        int code = statusCode.get();
        if (contentLength > 512 && !"gzip".equals(contentEnc)) {
            code = 400;
        }
        statusCounts.incrementAndGet(code);
        exchange.sendResponseHeaders(code, contentLength);
        try (InputStream input = exchange.getRequestBody();
            OutputStream output = exchange.getResponseBody()) {
            byte[] buf = new byte[1024];
            int length;
            while ((length = input.read(buf)) > 0) {
                output.write(buf, 0, length);
            }
        }
        exchange.close();
    });
    server.createContext("/relativeRedirect", exchange -> {
        ignore(exchange.getRequestBody());
        if (redirects.get() <= 0) {
            statusCounts.incrementAndGet(statusCode.get());
            exchange.getResponseHeaders().add("Location", "/empty");
            exchange.sendResponseHeaders(statusCode.get(), -1L);
            exchange.close();
        } else {
            redirects.decrementAndGet();
            statusCounts.incrementAndGet(302);
            exchange.getResponseHeaders().add("Location", "/relativeRedirect");
            exchange.sendResponseHeaders(302, -1L);
            exchange.close();
        }
    });
    server.createContext("/absoluteRedirect", exchange -> {
        String host = "http://" + exchange.getRequestHeaders().getFirst("Host");
        ignore(exchange.getRequestBody());
        if (redirects.get() <= 0) {
            statusCounts.incrementAndGet(302);
            exchange.getResponseHeaders().add("Location", host + "/empty");
            exchange.sendResponseHeaders(302, -1L);
            exchange.close();
        } else {
            redirects.decrementAndGet();
            statusCounts.incrementAndGet(302);
            exchange.getResponseHeaders().add("Location", host + "/absoluteRedirect");
            exchange.sendResponseHeaders(302, -1L);
            exchange.close();
        }
    });
    server.createContext("/notModified", exchange -> {
        ignore(exchange.getRequestBody());
        statusCounts.incrementAndGet(304);
        exchange.sendResponseHeaders(304, -1L);
        exchange.close();
    });
    server.createContext("/redirectNoLocation", exchange -> {
        ignore(exchange.getRequestBody());
        statusCounts.incrementAndGet(302);
        exchange.sendResponseHeaders(302, -1L);
        exchange.close();
    });
    server.createContext("/readTimeout", exchange -> {
        ignore(exchange.getRequestBody());
        // So we can track retries
        statusCounts.incrementAndGet(statusCode.get());
        Object lock = new Object();
        try {
            synchronized (lock) {
                lock.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    server.start();
    set(client + ".niws.client.MaxAutoRetriesNextServer", "" + retries);
    set(client + ".niws.client.RetryDelay", "100");
    set(client + ".niws.client.ReadTimeout", "1000");
}
Also used : HttpServer(com.sun.net.httpserver.HttpServer) BeforeClass(org.junit.BeforeClass) RunWith(org.junit.runner.RunWith) InstanceInfo(com.netflix.appinfo.InstanceInfo) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Actions(rx.functions.Actions) ServerSocket(java.net.ServerSocket) SettableConfig(com.netflix.archaius.api.config.SettableConfig) ByteBuf(io.netty.buffer.ByteBuf) Charset(java.nio.charset.Charset) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ReadTimeoutException(io.netty.handler.timeout.ReadTimeoutException) Map(java.util.Map) Headers(com.sun.net.httpserver.Headers) ConnectException(java.net.ConnectException) URI(java.net.URI) AtomicIntegerArray(java.util.concurrent.atomic.AtomicIntegerArray) HttpClientRequest(io.reactivex.netty.protocol.http.client.HttpClientRequest) Before(org.junit.Before) OutputStream(java.io.OutputStream) AfterClass(org.junit.AfterClass) DefaultSettableConfig(com.netflix.archaius.config.DefaultSettableConfig) HttpMethod(io.netty.handler.codec.http.HttpMethod) Test(org.junit.Test) IOException(java.io.IOException) JUnit4(org.junit.runners.JUnit4) InetSocketAddress(java.net.InetSocketAddress) Executors(java.util.concurrent.Executors) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientResponse(io.reactivex.netty.protocol.http.client.HttpClientResponse) Assert(org.junit.Assert) InputStream(java.io.InputStream) InetSocketAddress(java.net.InetSocketAddress) Headers(com.sun.net.httpserver.Headers) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) BeforeClass(org.junit.BeforeClass)

Example 38 with Headers

use of com.sun.net.httpserver.Headers in project cosmic by MissionCriticalCloud.

the class ConsoleProxyThumbnailHandler method doHandle.

private void doHandle(final HttpExchange t) throws IllegalArgumentException, IOException {
    final String queries = t.getRequestURI().getQuery();
    final Map<String, String> queryMap = getQueryMap(queries);
    int width = 0;
    int height = 0;
    int port = 0;
    final String ws = queryMap.get("w");
    final String hs = queryMap.get("h");
    final String host = queryMap.get("host");
    final String portStr = queryMap.get("port");
    final String sid = queryMap.get("sid");
    String tag = queryMap.get("tag");
    final String ticket = queryMap.get("ticket");
    final String console_url = queryMap.get("consoleurl");
    final String console_host_session = queryMap.get("sessionref");
    if (tag == null) {
        tag = "";
    }
    if (ws == null || hs == null || host == null || portStr == null || sid == null) {
        throw new IllegalArgumentException();
    }
    try {
        width = Integer.parseInt(ws);
        height = Integer.parseInt(hs);
        port = Integer.parseInt(portStr);
    } catch (final NumberFormatException e) {
        throw new IllegalArgumentException(e);
    }
    final ConsoleProxyClientParam param = new ConsoleProxyClientParam();
    param.setClientHostAddress(host);
    param.setClientHostPort(port);
    param.setClientHostPassword(sid);
    param.setClientTag(tag);
    param.setTicket(ticket);
    param.setClientTunnelUrl(console_url);
    param.setClientTunnelSession(console_host_session);
    final ConsoleProxyClient viewer = ConsoleProxy.getVncViewer(param);
    if (!viewer.isHostConnected()) {
        // use generated image instead of static
        final BufferedImage img = generateTextImage(width, height, "Connecting");
        final ByteArrayOutputStream bos = new ByteArrayOutputStream(8196);
        javax.imageio.ImageIO.write(img, "jpg", bos);
        final byte[] bs = bos.toByteArray();
        final Headers hds = t.getResponseHeaders();
        hds.set("Content-Type", "image/jpeg");
        hds.set("Cache-Control", "no-cache");
        hds.set("Cache-Control", "no-store");
        t.sendResponseHeaders(200, bs.length);
        final OutputStream os = t.getResponseBody();
        os.write(bs);
        os.close();
        if (s_logger.isInfoEnabled()) {
            s_logger.info("Console not ready, sent dummy JPG response");
        }
        return;
    }
    final Image scaledImage = viewer.getClientScaledImage(width, height);
    final BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
    final Graphics2D bufImageGraphics = bufferedImage.createGraphics();
    bufImageGraphics.drawImage(scaledImage, 0, 0, null);
    final ByteArrayOutputStream bos = new ByteArrayOutputStream(8196);
    javax.imageio.ImageIO.write(bufferedImage, "jpg", bos);
    final byte[] bs = bos.toByteArray();
    final Headers hds = t.getResponseHeaders();
    hds.set("Content-Type", "image/jpeg");
    hds.set("Cache-Control", "no-cache");
    hds.set("Cache-Control", "no-store");
    t.sendResponseHeaders(200, bs.length);
    final OutputStream os = t.getResponseBody();
    os.write(bs);
    os.close();
}
Also used : Headers(com.sun.net.httpserver.Headers) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) BufferedImage(java.awt.image.BufferedImage) Graphics2D(java.awt.Graphics2D)

Example 39 with Headers

use of com.sun.net.httpserver.Headers in project cosmic by MissionCriticalCloud.

the class ConsoleProxyResourceHandler method doHandle.

private void doHandle(final HttpExchange t) throws IOException {
    final String path = t.getRequestURI().getPath();
    if (s_logger.isInfoEnabled()) {
        s_logger.info("Get resource request for " + path);
    }
    int i = path.indexOf("/", 1);
    final String filepath = path.substring(i + 1);
    i = path.lastIndexOf(".");
    final String extension = (i == -1) ? "" : path.substring(i + 1);
    final String contentType = getContentType(extension);
    if (!validatePath(filepath)) {
        if (s_logger.isInfoEnabled()) {
            s_logger.info("Resource access is forbidden, uri: " + path);
        }
        // forbidden
        t.sendResponseHeaders(403, -1);
        return;
    }
    final File f = new File("./" + filepath);
    if (f.exists()) {
        final long lastModified = f.lastModified();
        final String ifModifiedSince = t.getRequestHeaders().getFirst("If-Modified-Since");
        if (ifModifiedSince != null) {
            final long d = Date.parse(ifModifiedSince);
            if (d + 1000 >= lastModified) {
                final Headers hds = t.getResponseHeaders();
                hds.set("Content-Type", contentType);
                t.sendResponseHeaders(304, -1);
                if (s_logger.isInfoEnabled()) {
                    s_logger.info("Sent 304 file has not been " + "modified since " + ifModifiedSince);
                }
                return;
            }
        }
        final long length = f.length();
        final Headers hds = t.getResponseHeaders();
        hds.set("Content-Type", contentType);
        hds.set("Last-Modified", new Date(lastModified).toGMTString());
        t.sendResponseHeaders(200, length);
        responseFileContent(t, f);
        if (s_logger.isInfoEnabled()) {
            s_logger.info("Sent file " + path + " with content type " + contentType);
        }
    } else {
        if (s_logger.isInfoEnabled()) {
            s_logger.info("file does not exist" + path);
        }
        t.sendResponseHeaders(404, -1);
    }
}
Also used : Headers(com.sun.net.httpserver.Headers) File(java.io.File) Date(java.util.Date)

Example 40 with Headers

use of com.sun.net.httpserver.Headers in project azure-tools-for-java by Microsoft.

the class RequestDetail method getRequestDetail.

public static RequestDetail getRequestDetail(@NotNull HttpExchange httpExchange) {
    final Headers headers = httpExchange.getRequestHeaders();
    final String clusterName = headers.getFirst("Cluster-name");
    final String ResetType = headers.getFirst("Rest-type");
    // TODO :
    return null;
}
Also used : 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