Package com.sun.net.httpserver

Examples of com.sun.net.httpserver.Headers


     * @param encode Flag indicating whether or not to Base64 encode the response payload.
     * @throws IOException if an error occurs while attempting to generate the HTTP response.
     */
    private void writeResponse(final HttpExchange http, boolean isGet, boolean pretty, ModelNode response, int status,
            boolean encode) throws IOException {
        final Headers responseHeaders = http.getResponseHeaders();
        responseHeaders.add("Content-Type", encode ? "application/dmr-encoded" : "application/json");
        responseHeaders.add("Access-Control-Allow-Origin", "*");
        http.sendResponseHeaders(status, 0);

        final OutputStream out = http.getResponseBody();
        final PrintWriter print = new PrintWriter(out);

View Full Code Here


    }

    @Override
    public Headers getRequestHeaders()
    {
        Headers headers = new Headers();
        Enumeration en = _req.getHeaderNames();
        while (en.hasMoreElements())
        {
            String name = (String) en.nextElement();
            Enumeration en2 = _req.getHeaders(name);
            while (en2.hasMoreElements())
            {
                String value = (String) en2.nextElement();
                headers.add(name, value);
            }
        }
        return headers;
    }
View Full Code Here

        return httpExchange.getRequestHeaders().getFirst(headerName);
    }

    @Override
    public void setResponseHeaders(Map<String,List<String>> headers) {
        Headers r = httpExchange.getResponseHeaders();
        r.clear();
        for(Map.Entry <String, List<String>> entry : headers.entrySet()) {
            String name = entry.getKey();
            List<String> values = entry.getValue();
            // ignore headers that interfere with our correct operations
            if (!name.equalsIgnoreCase("Content-Length") && !name.equalsIgnoreCase("Content-Type")) {
                r.put(name,new ArrayList<String>(values));
            }
        }
    }
View Full Code Here

            String requestMethod = exchange.getRequestMethod();
            if (requestMethod.equals("POST")) {
                /*
                 * Read the posted content
                 */
                Headers headers = exchange.getRequestHeaders();
                int responseCode = HTTP_RESPONSE_OK;
                String contentType = headers.getFirst("Content-Type");
                if (contentType != null && contentType.compareTo(HTTP_CONTENT_ZIP) == 0) {
                    zipped = true;
                }
                boolean outOfSequence = false;
                int bufferSize = 50000; // Default buffer size if no Content-Length header is present.
                String contentLength = headers.getFirst("Content-Length");
                if (contentLength != null) {
                    bufferSize = Integer.parseInt(contentLength);
                } else if (hop != null && hop.isLengthRequired()) {
                    responseCode = HTTP_RESPONSE_LENGTH_REQUIRED;
                }
                InputStream input = exchange.getRequestBody();
                byte[] messageBytes = new byte[bufferSize];
                int messageLength = input.read(messageBytes);
                input.close();
                String md5Reported = headers.getFirst("Content-MD5");
                if (md5Reported != null) {
                    String md5Computed = computeMd5(messageBytes, 0, messageLength);
                    if (md5Reported.compareTo(md5Computed) != 0) {
                        responseCode = HTTP_RESPONSE_MD5_MISMATCH;
                        Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
                                "MD5 reported as {0}, computed as {1}, length expected {2}, found {3}",
                                new Object[]{md5Reported, md5Computed, bufferSize, messageLength});
                    }
                } else if (hop != null && hop.isMd5Required()) {
                    responseCode = HTTP_RESPONSE_MD5_REQUIRED;
                }
                if (responseCode == HTTP_RESPONSE_OK) {
                    boolean completeMessage = true;
                    m.setSendingIpAddress(sendingIpAddress);
                    m.setSegmentCount(1);
                    m.setLongestSegmentLength(messageLength);
                    if (id > 0) {
                        completeMessage = false;
                        PartialMessage pm = null;
                        if (segment == 1) {
                            pm = new PartialMessage();
                            pm.id = id;
                            pm.segment = segment;
                            byte[] a = Arrays.copyOf(messageBytes, messageLength);
                            pm.messageSegments.add(a);
                            pm.length += messageLength;
                            partialMessages.put(sendingIpAddressAndPort, pm);
                        } else {
                            pm = partialMessages.get(sendingIpAddressAndPort);
                            if (pm != null) {
                                if (pm.id == id && ++pm.segment == segment) {
                                    byte[] a = Arrays.copyOf(messageBytes, messageLength);
                                    pm.messageSegments.add(a);
                                    pm.length += messageLength;
                                    if (end) {
                                        messageLength = pm.length;
                                        messageBytes = new byte[messageLength];
                                        int offset = 0;
                                        int longest = 0;
                                        for (byte[] seg : pm.messageSegments) {
                                            System.arraycopy(seg, 0, messageBytes, offset, seg.length);
                                            offset += seg.length;
                                            if (seg.length > longest) {
                                                longest = seg.length;
                                            }
                                        }
                                        m.setSegmentCount(pm.messageSegments.size());
                                        m.setLongestSegmentLength(longest);
                                        completeMessage = true;
                                        partialMessages.remove(sendingIpAddressAndPort);
                                    }
                                } else {
                                    if (pm.id != id) {
                                        Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
                                                "Message id mismatch from {0}. Expected id {1}, found {2}, expected sequence {3}, found {4}",
                                                new Object[]{sendingIpAddressAndPort, pm.id, id, pm.segment, segment});
                                    } else {
                                        Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
                                                "Message segment out of sequence from {0}, message id {1}, expected sequence {2}, found {3}",
                                                new Object[]{sendingIpAddressAndPort, id, pm.segment, segment});
                                    }
                                    outOfSequence = true;
                                    partialMessages.remove(sendingIpAddressAndPort);
                                }
                            } else {
                                Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
                                        "Received segment from {0}, id {1}, segment {2} but no partial message previously stored.",
                                        new Object[]{sendingIpAddressAndPort, id, segment});
                            }
                        }
                    }
                    if (completeMessage) {
                        m.setSendingIpAddress(sendingIpAddress);
                        if (zipped) {
                            m.setCompressedXml(messageBytes);
                            m.setCompressedXmlLength(messageLength);
                        } else {
                            String xml = new String(messageBytes, 0, messageLength);
                            m.setXml(xml);
                        }
                        /*
                         * Process the message.
                         */
                        mediator.processReceivedMessage(m);
                    }
                }
                if (!outOfSequence) {
                    /*
                     * Acknoweldge to the sender that we received the message.
                     * (Don't acknowledge an out-of-sequence message).
                     */
                    Headers responseHeaders = exchange.getResponseHeaders();
                    responseHeaders.set("Content-Type", "text/plain");
                    exchange.sendResponseHeaders(responseCode, 0);
                    OutputStream responseBody = exchange.getResponseBody();
                    responseBody.close();
                }
                exchange.close();
View Full Code Here

                new HttpHandler()
        {

            public void handle(HttpExchange exchange) throws IOException
            {
                Headers responseHeaders = exchange.getResponseHeaders();
                responseHeaders.set("Content-Type","text/plain");
                exchange.sendResponseHeaders(200,0);

                OutputStream responseBody = exchange.getResponseBody();
                Headers requestHeaders = exchange.getRequestHeaders();
                Set<String> keySet = requestHeaders.keySet();
                Iterator<String> iter = keySet.iterator();
                while (iter.hasNext())
                {
                    String key = iter.next();
                    List values = requestHeaders.get(key);
                    String s = key + " = " + values.toString() + "\n";
                    responseBody.write(s.getBytes());
                }
                responseBody.close();
View Full Code Here

    }

    @Override
    public Headers getRequestHeaders()
    {
        Headers headers = new Headers();
        Enumeration<?> en = _req.getHeaderNames();
        while (en.hasMoreElements())
        {
            String name = (String)en.nextElement();
            Enumeration<?> en2 = _req.getHeaders(name);
            while (en2.hasMoreElements())
            {
                String value = (String)en2.nextElement();
                headers.add(name,value);
            }
        }
        return headers;
    }
View Full Code Here

        HttpExchange exchange = prepareExchange("http://localhost:8080/jolokia/read/java.lang:type=Memory/HeapMemoryUsage?callback=data");

        // Simple GET method
        expect(exchange.getRequestMethod()).andReturn("GET");

        Headers header = new Headers();
        ByteArrayOutputStream out = prepareResponse(handler, exchange, header);

        handler.doHandle(exchange);

        assertEquals(header.getFirst("content-type"),"text/javascript; charset=utf-8");
        String result = out.toString("utf-8");
        assertTrue(result.endsWith("});"));
        assertTrue(result.startsWith("data({"));
    }
View Full Code Here

                                                "Origin",null
                                               );

        // Simple GET method
        prepareMemoryPostReadRequest(exchange);
        Headers header = new Headers();
        ByteArrayOutputStream out = prepareResponse(handler, exchange, header);

        handler.doHandle(exchange);

        assertEquals(header.getFirst("content-type"),"text/javascript; charset=utf-8");
        String result = out.toString("utf-8");
        assertTrue(result.endsWith("});"));
        assertTrue(result.startsWith("data({"));
        assertTrue(result.contains("\"used\""));

        assertEquals(header.getFirst("Cache-Control"),"no-cache");
        assertEquals(header.getFirst("Pragma"),"no-cache");
        SimpleDateFormat rfc1123Format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
        rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT"));

        String expires = header.getFirst("Expires");
        String date = header.getFirst("Date");

        Date parsedExpires = rfc1123Format.parse(expires);
        Date parsedDate = rfc1123Format.parse(date);
        assertTrue(parsedExpires.before(parsedDate) || parsedExpires.equals(parsedDate));
        Date now = new Date();
View Full Code Here

    public void invalidMethod() throws URISyntaxException, IOException, ParseException {
        HttpExchange exchange = prepareExchange("http://localhost:8080/");

        // Simple GET method
        expect(exchange.getRequestMethod()).andReturn("PUT");
        Headers header = new Headers();
        ByteArrayOutputStream out = prepareResponse(handler, exchange, header);
        handler.doHandle(exchange);

        JSONObject resp = (JSONObject) new JSONParser().parse(out.toString());
        assertTrue(resp.containsKey("error"));
View Full Code Here

            Configuration config = getConfig(ConfigKey.POLICY_LOCATION,params[0]);
            JolokiaHttpHandler newHandler = new JolokiaHttpHandler(config);
            HttpExchange exchange = prepareExchange("http://localhost:8080/jolokia/read/java.lang:type=Memory/HeapMemoryUsage");
            // Simple GET method
            expect(exchange.getRequestMethod()).andReturn("GET");
            Headers header = new Headers();
            ByteArrayOutputStream out = prepareResponse(handler, exchange, header);
            newHandler.start(false);
            try {
                newHandler.doHandle(exchange);
            } finally {
View Full Code Here

TOP

Related Classes of com.sun.net.httpserver.Headers

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.