Search in sources :

Example 41 with Headers

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

the class JerseyClientIntegrationTest method testRetryHandler.

@Test
void testRetryHandler() throws Exception {
    httpServer.createContext("/register", httpExchange -> {
        try {
            Headers requestHeaders = httpExchange.getRequestHeaders();
            assertThat(requestHeaders.get(TRANSFER_ENCODING)).containsExactly(CHUNKED);
            assertThat(requestHeaders.get(HttpHeaders.CONTENT_LENGTH)).isNull();
            assertThat(requestHeaders.get(HttpHeaders.CONTENT_ENCODING)).isNull();
            assertThat(requestHeaders.get(HttpHeaders.ACCEPT_ENCODING)).isNull();
            checkBody(httpExchange, false);
            httpExchange.getResponseHeaders().add(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON);
            httpExchange.sendResponseHeaders(200, 0);
            httpExchange.getResponseBody().write(JSON_TOKEN.getBytes(StandardCharsets.UTF_8));
            httpExchange.getResponseBody().close();
        } finally {
            httpExchange.close();
        }
    });
    httpServer.start();
    JerseyClientConfiguration configuration = new JerseyClientConfiguration();
    configuration.setGzipEnabled(false);
    configuration.setGzipEnabledForRequests(false);
    postRequest(configuration);
}
Also used : Headers(com.sun.net.httpserver.Headers) HttpHeaders(javax.ws.rs.core.HttpHeaders) Test(org.junit.jupiter.api.Test)

Example 42 with Headers

use of com.sun.net.httpserver.Headers in project cloudstack by apache.

the class ConsoleProxyThumbnailHandler method handle.

@Override
@SuppressWarnings("access")
public void handle(HttpExchange t) throws IOException {
    try {
        Thread.currentThread().setName("JPG Thread " + Thread.currentThread().getId() + " " + t.getRemoteAddress());
        if (s_logger.isDebugEnabled())
            s_logger.debug("ScreenHandler " + t.getRequestURI());
        long startTick = System.currentTimeMillis();
        doHandle(t);
        if (s_logger.isDebugEnabled())
            s_logger.debug(t.getRequestURI() + "Process time " + (System.currentTimeMillis() - startTick) + " ms");
    } catch (IllegalArgumentException e) {
        String response = "Bad query string";
        s_logger.error(response + ", request URI : " + t.getRequestURI());
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
    } catch (OutOfMemoryError e) {
        s_logger.error("Unrecoverable OutOfMemory Error, exit and let it be re-launched");
        System.exit(1);
    } catch (Throwable e) {
        s_logger.error("Unexpected exception while handing thumbnail request, ", e);
        String queries = t.getRequestURI().getQuery();
        Map<String, String> queryMap = getQueryMap(queries);
        int width = 0;
        int height = 0;
        String ws = queryMap.get("w");
        String hs = queryMap.get("h");
        try {
            width = Integer.parseInt(ws);
            height = Integer.parseInt(hs);
        } catch (NumberFormatException ex) {
            s_logger.debug("Cannot parse width: " + ws + " or height: " + hs, ex);
        }
        width = Math.min(width, 800);
        height = Math.min(height, 600);
        BufferedImage img = generateTextImage(width, height, "Cannot Connect");
        ByteArrayOutputStream bos = new ByteArrayOutputStream(8196);
        javax.imageio.ImageIO.write(img, "jpg", bos);
        byte[] bs = bos.toByteArray();
        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);
        OutputStream os = t.getResponseBody();
        os.write(bs);
        os.close();
        s_logger.error("Cannot get console, sent error JPG response for " + t.getRequestURI());
        return;
    } finally {
        t.close();
    }
}
Also used : Headers(com.sun.net.httpserver.Headers) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HashMap(java.util.HashMap) Map(java.util.Map) BufferedImage(java.awt.image.BufferedImage)

Example 43 with Headers

use of com.sun.net.httpserver.Headers in project cloudstack by apache.

the class ConsoleProxyThumbnailHandler method doHandle.

private void doHandle(HttpExchange t) throws Exception, IllegalArgumentException {
    String queries = t.getRequestURI().getQuery();
    Map<String, String> queryMap = getQueryMap(queries);
    int width = 0;
    int height = 0;
    int port = 0;
    String ws = queryMap.get("w");
    String hs = queryMap.get("h");
    String host = queryMap.get("host");
    String portStr = queryMap.get("port");
    String sid = queryMap.get("sid");
    String tag = queryMap.get("tag");
    String ticket = queryMap.get("ticket");
    String console_url = queryMap.get("consoleurl");
    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 (NumberFormatException e) {
        throw new IllegalArgumentException(e);
    }
    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);
    ConsoleProxyClient viewer = ConsoleProxy.getVncViewer(param);
    if (!viewer.isHostConnected()) {
        // use generated image instead of static
        BufferedImage img = generateTextImage(width, height, "Connecting");
        ByteArrayOutputStream bos = new ByteArrayOutputStream(8196);
        javax.imageio.ImageIO.write(img, "jpg", bos);
        byte[] bs = bos.toByteArray();
        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);
        OutputStream os = t.getResponseBody();
        os.write(bs);
        os.close();
        if (s_logger.isInfoEnabled())
            s_logger.info("Console not ready, sent dummy JPG response");
        return;
    }
    {
        Image scaledImage = viewer.getClientScaledImage(width, height);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D bufImageGraphics = bufferedImage.createGraphics();
        bufImageGraphics.drawImage(scaledImage, 0, 0, null);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(8196);
        javax.imageio.ImageIO.write(bufferedImage, "jpg", bos);
        byte[] bs = bos.toByteArray();
        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);
        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 44 with Headers

use of com.sun.net.httpserver.Headers in project cloudstack by apache.

the class ConsoleProxyAjaxImageHandler method doHandle.

private void doHandle(HttpExchange t) throws Exception, IllegalArgumentException {
    String queries = t.getRequestURI().getQuery();
    Map<String, String> queryMap = ConsoleProxyHttpHandlerHelper.getQueryMap(queries);
    String host = queryMap.get("host");
    String portStr = queryMap.get("port");
    String sid = queryMap.get("sid");
    String tag = queryMap.get("tag");
    String ticket = queryMap.get("ticket");
    String keyStr = queryMap.get("key");
    String console_url = queryMap.get("consoleurl");
    String console_host_session = queryMap.get("sessionref");
    String w = queryMap.get("w");
    String h = queryMap.get("h");
    int key = 0;
    int width = 144;
    int height = 110;
    if (tag == null)
        tag = "";
    int port;
    if (host == null || portStr == null || sid == null)
        throw new IllegalArgumentException();
    try {
        port = Integer.parseInt(portStr);
    } catch (NumberFormatException e) {
        s_logger.warn("Invalid numeric parameter in query string: " + portStr);
        throw new IllegalArgumentException(e);
    }
    try {
        if (keyStr != null)
            key = Integer.parseInt(keyStr);
        if (null != w)
            width = Integer.parseInt(w);
        if (null != h)
            height = Integer.parseInt(h);
    } catch (NumberFormatException e) {
        s_logger.warn("Invalid numeric parameter in query string: " + keyStr);
        throw new IllegalArgumentException(e);
    }
    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);
    ConsoleProxyClient viewer = ConsoleProxy.getVncViewer(param);
    if (key == 0) {
        Image scaledImage = viewer.getClientScaledImage(width, height);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D bufImageGraphics = bufferedImage.createGraphics();
        bufImageGraphics.drawImage(scaledImage, 0, 0, null);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(8196);
        javax.imageio.ImageIO.write(bufferedImage, "jpg", bos);
        byte[] bs = bos.toByteArray();
        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);
        OutputStream os = t.getResponseBody();
        os.write(bs);
        os.close();
    } else {
        AjaxFIFOImageCache imageCache = viewer.getAjaxImageCache();
        byte[] img = imageCache.getImage(key);
        if (img != null) {
            Headers hds = t.getResponseHeaders();
            hds.set("Content-Type", "image/jpeg");
            t.sendResponseHeaders(200, img.length);
            OutputStream os = t.getResponseBody();
            try {
                os.write(img, 0, img.length);
            } finally {
                os.close();
            }
        } else {
            if (s_logger.isInfoEnabled())
                s_logger.info("Image has already been swept out, key: " + key);
            t.sendResponseHeaders(404, -1);
        }
    }
}
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 45 with Headers

use of com.sun.net.httpserver.Headers in project cloudstack by apache.

the class ConsoleProxyCmdHandler method doHandle.

public void doHandle(HttpExchange t) throws Exception {
    String path = t.getRequestURI().getPath();
    int i = path.indexOf("/", 1);
    String cmd = path.substring(i + 1);
    s_logger.info("Get CMD request for " + cmd);
    if (cmd.equals("getstatus")) {
        ConsoleProxyClientStatsCollector statsCollector = ConsoleProxy.getStatsCollector();
        Headers hds = t.getResponseHeaders();
        hds.set("Content-Type", "text/plain");
        t.sendResponseHeaders(200, 0);
        OutputStreamWriter os = new OutputStreamWriter(t.getResponseBody(), "UTF-8");
        statsCollector.getStatsReport(os);
        os.close();
    }
}
Also used : Headers(com.sun.net.httpserver.Headers) OutputStreamWriter(java.io.OutputStreamWriter)

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