Java Code Examples for com.sun.net.httpserver.Headers

The following are top voted examples for showing how to use com.sun.net.httpserver.Headers. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: amr2Fred   File: CompareHandler.java   View source code 10 votes vote down vote up
private void noTriple(HttpExchange he) {

        try {
            Headers responseHeaders = he.getResponseHeaders();
            FileHandler ext = new FileHandler();
            File tmp;
            responseHeaders.set(TYPE, PNG);
            ext.getFile(NOTRIPLE);
            tmp = new File(PAGESDIR + NOTRIPLE);
            he.sendResponseHeaders(200, tmp.length());
            try (OutputStream os = he.getResponseBody()) {
                Files.copy(tmp.toPath(), os);
                tmp.delete();
            }
        } catch (IOException ex) {
            Logger.getLogger(CompareHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
Example 2
Project: elasticsearch_my   File: RestClientSingleHostIntegTests.java   View source code 8 votes vote down vote up
@Override
public void handle(HttpExchange httpExchange) throws IOException {
    StringBuilder body = new StringBuilder();
    try (InputStreamReader reader = new InputStreamReader(httpExchange.getRequestBody(), Consts.UTF_8)) {
        char[] buffer = new char[256];
        int read;
        while ((read = reader.read(buffer)) != -1) {
            body.append(buffer, 0, read);
        }
    }
    Headers requestHeaders = httpExchange.getRequestHeaders();
    Headers responseHeaders = httpExchange.getResponseHeaders();
    for (Map.Entry<String, List<String>> header : requestHeaders.entrySet()) {
        responseHeaders.put(header.getKey(), header.getValue());
    }
    httpExchange.getRequestBody().close();
    httpExchange.sendResponseHeaders(statusCode, body.length() == 0 ? -1 : body.length());
    if (body.length() > 0) {
        try (OutputStream out = httpExchange.getResponseBody()) {
            out.write(body.toString().getBytes(Consts.UTF_8));
        }
    }
    httpExchange.close();
}
 
Example 3
Project: openjdk-jdk10   File: HttpOnly.java   View source code 8 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    Headers reqHeaders = t.getRequestHeaders();

    // some small sanity check
    List<String> cookies = reqHeaders.get("Cookie");
    for (String cookie : cookies) {
        if (!cookie.contains("JSESSIONID")
            || !cookie.contains("WILE_E_COYOTE"))
            t.sendResponseHeaders(400, -1);
    }

    // return some cookies so we can check getHeaderField(s)
    Headers respHeaders = t.getResponseHeaders();
    List<String> values = new ArrayList<>();
    values.add("ID=JOEBLOGGS; version=1; Path=" + URI_PATH);
    values.add("NEW_JSESSIONID=" + (SESSION_ID+1) + "; version=1; Path="
               + URI_PATH +"; HttpOnly");
    values.add("NEW_CUSTOMER=WILE_E_COYOTE2; version=1; Path=" + URI_PATH);
    respHeaders.put("Set-Cookie", values);
    values = new ArrayList<>();
    values.add("COOKIE2_CUSTOMER=WILE_E_COYOTE2; version=1; Path="
               + URI_PATH);
    respHeaders.put("Set-Cookie2", values);
    values.add("COOKIE2_JSESSIONID=" + (SESSION_ID+100)
               + "; version=1; Path=" + URI_PATH +"; HttpOnly");
    respHeaders.put("Set-Cookie2", values);

    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 4
Project: trap   File: CORSUtil.java   View source code 7 votes vote down vote up
public static void setCors(Headers requestHeaders, Headers responseHeaders)
{
	
	String origin = requestHeaders.getFirst("Origin");
	
	if (origin == null)
		origin = "null";
	
	responseHeaders.set("Allow", "GET,PUT,POST,DELETE,OPTIONS");
	responseHeaders.set("Access-Control-Allow-Origin", origin);
	responseHeaders.set("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
	responseHeaders.set("Access-Control-Allow-Headers", "Content-Type");
	responseHeaders.set("Access-Control-Request-Methods", "GET,PUT,POST,DELETE,OPTIONS");
	responseHeaders.set("Access-Control-Request-Headers", "Content-Type");
	responseHeaders.set("Access-Control-Max-Age", "3600");
}
 
Example 5
Project: graphflow   File: PlanViewerHttpServer.java   View source code 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    InputStream inputStream = exchange.getRequestBody();
    String query;
    String response;
    try (Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
        query = scanner.useDelimiter("\\A").next();
        logger.info("Query: " + query);
        inputStream.close();
        response = queryServer(query, ReturnType.JSON);
    } catch (Exception e) {
        logger.info("ERROR", e);
        response = new Message("ERROR: " + e.getMessage(), true).toJson().toString();
    }

    // Add the header to avoid error:
    // “No 'Access-Control-Allow-Origin' header is present on the requested resource”
    Headers responseHeaders = exchange.getResponseHeaders();
    responseHeaders.add("Access-Control-Allow-Origin", "*");
    exchange.sendResponseHeaders(200, response.length());

    OutputStream outputStream = exchange.getResponseBody();
    outputStream.write(response.getBytes());
    outputStream.close();
}
 
Example 6
Project: secondbase   File: PrometheusWebConsoleTest.java   View source code 6 votes vote down vote up
@Test
public void parseMetrics() throws IOException {
    final Counter counter = Counter
            .build("testcounter", "testdescription")
            .labelNames("one", "two")
            .register();
    counter.labels("1", "2").inc();
    final HttpExchange mockExchange = mock(HttpExchange.class);
    final OutputStream outputStream = new ByteArrayOutputStream();
    when(mockExchange.getResponseBody()).thenReturn(outputStream);
    final Headers headers = new Headers();
    when(mockExchange.getResponseHeaders()).thenReturn(headers);

    new PrometheusWebConsole().getServlet().handle(mockExchange);

    assertEquals(TextFormat.CONTENT_TYPE_004, headers.get("Content-Type").get(0));

    final String response = outputStream.toString();
    assertTrue(response.contains("# HELP testcounter testdescription"));
    assertTrue(response.contains("# TYPE testcounter counter"));
    assertTrue(response.contains("one=\"1\""));
    assertTrue(response.contains("two=\"2\""));
}
 
Example 7
Project: jdk8u-jdk   File: Deadlock.java   View source code 6 votes vote down vote up
@Override
public void handle (HttpExchange t)
    throws IOException
{
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    while (is.read() != -1);
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals("fred")) {
        error = true;
    }
    if (!p.getRealm().equals("[email protected]")) {
        error = true;
    }
    t.close();
}
 
Example 8
Project: WLT3Serial   File: WebServerTestHelper.java   View source code 6 votes vote down vote up
public void handle(HttpExchange exchange) {
	try {
		exchange.getRequestMethod();
		exchange.getRequestBody().close();
		Headers respHeaders = null;
		if(!accessed && (source == null)) { //context hasn't been accessed before
			source = exchange.getRemoteAddress().getHostString();
			accessed = true;
			respHeaders = exchange.getResponseHeaders();
			respHeaders.add("Content-Type","text/plain");
			exchange.sendResponseHeaders(200,path.length());
			OutputStream os = exchange.getResponseBody();
			os.write(path.getBytes());
			os.flush();
			os.close();
			accessList.put(path,source);
		} else {
			respHeaders = exchange.getResponseHeaders();
			exchange.sendResponseHeaders(404,0);
			exchange.getResponseBody().close();
		}
	} catch(Exception e) {
		System.err.println("Unforeseen error occurred!");
		e.printStackTrace();
	}
}
 
Example 9
Project: openjdk-jdk10   File: Deadlock.java   View source code 6 votes vote down vote up
@Override
public void handle (HttpExchange t)
    throws IOException
{
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    while (is.read() != -1);
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals("fred")) {
        error = true;
    }
    if (!p.getRealm().equals("[email protected]")) {
        error = true;
    }
    t.close();
}
 
Example 10
Project: openjdk-jdk10   File: Security.java   View source code 6 votes vote down vote up
@Override
public synchronized void handle(HttpExchange t)
        throws IOException {
    byte[] buf = new byte[2048];
    System.out.println("Server: " + t.getRequestURI());
    try (InputStream is = t.getRequestBody()) {
        while (is.read(buf) != -1) ;
    }
    increment();
    if (count() == 1) {
        Headers map = t.getResponseHeaders();
        String redirect = "/redirect/bar.txt";
        map.add("Location", redirect);
        t.sendResponseHeaders(301, -1);
        t.close();
    } else {
        String response = "Hello world";
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes(StandardCharsets.ISO_8859_1));
        t.close();
    }
}
 
Example 11
Project: openjdk-jdk10   File: SmokeTest.java   View source code 6 votes vote down vote up
@Override
public synchronized void handle(HttpExchange t)
    throws IOException
{
    byte[] buf = new byte[2048];
    try (InputStream is = t.getRequestBody()) {
        while (is.read(buf) != -1) ;
    }

    Headers responseHeaders = t.getResponseHeaders();

    if (count++ < 1) {
        responseHeaders.add("Location", root + "/foo/" + count);
    } else {
        responseHeaders.add("Location", SmokeTest.midSizedFilename);
    }
    t.sendResponseHeaders(301, -1);
    t.close();
}
 
Example 12
Project: openjdk-jdk10   File: SmokeTest.java   View source code 6 votes vote down vote up
@Override
public synchronized void handle (HttpExchange t)
    throws IOException
{
    byte[] buf = new byte[2048];
    try (InputStream is = t.getRequestBody()) {
        while (is.read(buf) != -1) ;
    }

    Headers map = t.getResponseHeaders();
    String redirect = root + "/foo/" + Integer.toString(count);
    increment();
    map.add("Location", redirect);
    t.sendResponseHeaders(301, -1);
    t.close();
}
 
Example 13
Project: openjdk-jdk10   File: LightWeightHttpServer.java   View source code 6 votes vote down vote up
@Override
public synchronized void handle(HttpExchange t)
        throws IOException {
    byte[] buf = new byte[2048];
    try (InputStream is = t.getRequestBody()) {
        while (is.read(buf) != -1) ;
    }

    Headers map = t.getResponseHeaders();

    if (count++ < 1) {
        map.add("Location", root + "/foo/" + count);
    } else {
        map.add("Location", SmokeTest.midSizedFilename);
    }
    t.sendResponseHeaders(301, -1);
    t.close();
}
 
Example 14
Project: openjdk-jdk10   File: HeadersTest1.java   View source code 6 votes vote down vote up
@Override
public void handle(HttpExchange he) throws IOException {
    List<String> l = he.getRequestHeaders().get("X-Bar");
    if (!l.contains("foo1") || !l.contains("foo2")) {
        for (String s : l) {
            System.out.println("HH: " + s);
        }
        he.sendResponseHeaders(500, -1);
        he.close();
        return;
    }
    Headers h = he.getResponseHeaders();
    h.add("X-Foo-Response", "resp1");
    h.add("X-Foo-Response", "resp2");
    he.sendResponseHeaders(200, RESPONSE.length());
    OutputStream os = he.getResponseBody();
    os.write(RESPONSE.getBytes(US_ASCII));
    os.close();
}
 
Example 15
Project: openjdk9   File: Deadlock.java   View source code 6 votes vote down vote up
@Override
public void handle (HttpExchange t)
    throws IOException
{
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    while (is.read() != -1);
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals("fred")) {
        error = true;
    }
    if (!p.getRealm().equals("[email protected]")) {
        error = true;
    }
    t.close();
}
 
Example 16
Project: openjdk9   File: LightWeightHttpServer.java   View source code 6 votes vote down vote up
@Override
public synchronized void handle(HttpExchange t)
        throws IOException {
    byte[] buf = new byte[2048];
    try (InputStream is = t.getRequestBody()) {
        while (is.read(buf) != -1) ;
    }

    Headers map = t.getResponseHeaders();

    if (count++ < 1) {
        map.add("Location", root + "/foo/" + count);
    } else {
        map.add("Location", SmokeTest.midSizedFilename);
    }
    t.sendResponseHeaders(301, -1);
    t.close();
}
 
Example 17
Project: openjdk9   File: HeadersTest1.java   View source code 6 votes vote down vote up
@Override
public void handle(HttpExchange he) throws IOException {
    String method = he.getRequestMethod();
    InputStream is = he.getRequestBody();
    List<String> l = he.getRequestHeaders().get("X-Bar");
    if (!l.contains("foo1") || !l.contains("foo2")) {
        for (String s : l)
            System.out.println("HH: " + s);
        he.sendResponseHeaders(500, -1);
        he.close();
        return;
    }
    Headers h = he.getResponseHeaders();
    h.add("X-Foo-Response", "resp1");
    h.add("X-Foo-Response", "resp2");
    he.sendResponseHeaders(200, RESPONSE.length());
    OutputStream os = he.getResponseBody();
    os.write(RESPONSE.getBytes(US_ASCII));
    os.close();
}
 
Example 18
Project: DigitalMediaServer   File: RemoteUtil.java   View source code 6 votes vote down vote up
/**
 * Write the given resource as an http response body.
 */
public boolean write(String filename, HttpExchange t) throws IOException {
	InputStream stream = getInputStream(filename);
	if (stream != null) {
		Headers headers = t.getResponseHeaders();
		if (!headers.containsKey("Content-Type")) {
			String mime = getContentType(filename);
			if (mime != null) {
				headers.add("Content-Type", mime);
			}
		}
		// Note: available() isn't officially guaranteed to return the full
		// stream length but effectively seems to do so in our context.
		t.sendResponseHeaders(200, stream.available());
		dump(stream, t.getResponseBody());
		return true;
	}
	return false;
}
 
Example 19
Project: WatCA   File: WebServer.java   View source code 6 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    URI requestedUri = t.getRequestURI();
    String query = requestedUri.getRawQuery();
    URL ycsb = new URL("http://" + hostYCSB + ":" + portYCSB + "?" + query);
    try {
        InputStream in = ycsb.openStream();
        Headers h = t.getResponseHeaders();
        h.add("Content-Type", "text/html");
        t.sendResponseHeaders(200, 0);
        OutputStream os = t.getResponseBody();
        int i;
        while ((i = in.read()) != -1) {
            os.write(i);
            os.flush();
        }
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 20
Project: openbravo-pos   File: JettyHttpExchange.java   View source code 6 votes vote down vote up
@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;
}
 
Example 21
Project: cosmic   File: ConsoleProxyCmdHandler.java   View source code 6 votes vote down vote up
public void doHandle(final HttpExchange t) throws IOException {
    final String path = t.getRequestURI().getPath();
    final int i = path.indexOf("/", 1);
    final String cmd = path.substring(i + 1);
    s_logger.info("Get CMD request for " + cmd);
    if (cmd.equals("getstatus")) {
        final ConsoleProxyClientStatsCollector statsCollector = ConsoleProxy.getStatsCollector();

        final Headers hds = t.getResponseHeaders();
        hds.set("Content-Type", "text/plain");
        t.sendResponseHeaders(200, 0);
        final OutputStreamWriter os = new OutputStreamWriter(t.getResponseBody(), "UTF-8");
        statsCollector.getStatsReport(os);
        os.close();
    }
}
 
Example 22
Project: cosmic   File: ConsoleProxyAjaxHandler.java   View source code 6 votes vote down vote up
private void handleClientStart(final HttpExchange t, final ConsoleProxyClient viewer, final String title, final String guest) throws IOException {
    final List<String> languages = t.getRequestHeaders().get("Accept-Language");
    final String response = viewer.onAjaxClientStart(title, languages, guest);

    final Headers hds = t.getResponseHeaders();
    hds.set("Content-Type", "text/html");
    hds.set("Cache-Control", "no-cache");
    hds.set("Cache-Control", "no-store");
    t.sendResponseHeaders(200, response.length());

    final OutputStream os = t.getResponseBody();
    try {
        os.write(response.getBytes());
    } finally {
        os.close();
    }
}
 
Example 23
Project: jdk8u_jdk   File: Deadlock.java   View source code 6 votes vote down vote up
@Override
public void handle (HttpExchange t)
    throws IOException
{
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    while (is.read() != -1);
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals("fred")) {
        error = true;
    }
    if (!p.getRealm().equals("[email protected]")) {
        error = true;
    }
    t.close();
}
 
Example 24
Project: lookaside_java-1.8.0-openjdk   File: Deadlock.java   View source code 6 votes vote down vote up
@Override
public void handle (HttpExchange t)
    throws IOException
{
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    while (is.read() != -1);
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals("fred")) {
        error = true;
    }
    if (!p.getRealm().equals("[email protected]")) {
        error = true;
    }
    t.close();
}
 
Example 25
Project: Disco   File: TaxServer.java   View source code 6 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
	
	{
		Headers h = t.getResponseHeaders();
		String type="text/plain";
		h.add("Content-Type", type);
	}
	
	String response=USAGE;
	if(verbose2){System.out.println("Sending: "+response);}
	
	t.sendResponseHeaders(200, response.length());
	OutputStream os = t.getResponseBody();
	os.write(response.getBytes());
	os.close();
}
 
Example 26
Project: lab-materials   File: ServerHandler.java   View source code 6 votes vote down vote up
private void sendResponse(HttpExchange httpExchange, Response response) {
    try (OutputStream os = httpExchange.getResponseBody()) {
        byte[] bytes = response.getBody().getBytes();

        Headers headers = httpExchange.getResponseHeaders();
        headers.add(Constants.REQUEST_HEADER_ACCESS_CONTROL,"*");
        httpExchange.sendResponseHeaders(response.getStatusCode(), bytes.length);

        os.write( bytes);
        // there is no need to close stream manually
        // as try-catch with auto-closable is used
        /**
         * {@see http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html}
         */
    } catch (IOException e) {
        logger.error("Could not send response", e);
    }
}
 
Example 27
Project: lab-materials   File: ServerHandler.java   View source code 6 votes vote down vote up
private void sendResponse(HttpExchange httpExchange, Response response) {
    try (OutputStream os = httpExchange.getResponseBody()) {
        byte[] bytes = response.getBody().getBytes();

        Headers headers = httpExchange.getResponseHeaders();
        headers.add(Constants.REQUEST_HEADER_ACCESS_CONTROL_ORIGIN,"*");
        httpExchange.sendResponseHeaders(response.getStatusCode(), bytes.length);

        os.write( bytes);
        // there is no need to close stream manually
        // as try-catch with auto-closable is used
        /**
         * {@see http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html}
         */
    } catch (IOException e) {
        logger.error("Could not send response", e);
    }
}
 
Example 28
Project: infobip-open-jdk-8   File: Deadlock.java   View source code 6 votes vote down vote up
@Override
public void handle (HttpExchange t)
    throws IOException
{
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    while (is.read() != -1);
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals("fred")) {
        error = true;
    }
    if (!p.getRealm().equals("[email protected]")) {
        error = true;
    }
    t.close();
}
 
Example 29
Project: jdk8u-dev-jdk   File: Deadlock.java   View source code 6 votes vote down vote up
@Override
public void handle (HttpExchange t)
    throws IOException
{
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    while (is.read() != -1);
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals("fred")) {
        error = true;
    }
    if (!p.getRealm().equals("[email protected]")) {
        error = true;
    }
    t.close();
}
 
Example 30
Project: heron   File: NetworkUtilsTest.java   View source code 6 votes vote down vote up
@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();
}
 
Example 31
Project: heron   File: NetworkUtilsTest.java   View source code 6 votes vote down vote up
@Test
public void testReadHttpRequestBodyFail() throws Exception {
  HttpExchange exchange = Mockito.mock(HttpExchange.class);
  Headers headers = Mockito.mock(Headers.class);
  Mockito.doReturn(headers).when(exchange).getRequestHeaders();

  Mockito.doReturn("-1").
      when(headers).getFirst(Matchers.anyString());
  Assert.assertArrayEquals(new byte[0], NetworkUtils.readHttpRequestBody(exchange));

  Mockito.doReturn("10").
      when(headers).getFirst(Matchers.anyString());
  InputStream inputStream = Mockito.mock(InputStream.class);
  Mockito.doReturn(inputStream).when(exchange).getRequestBody();
  Mockito.doThrow(new IOException("Designed IO exception for testing"))
      .when(inputStream).read(Matchers.any(byte[].class), Matchers.anyInt(), Matchers.anyInt());
  Assert.assertArrayEquals(new byte[0], NetworkUtils.readHttpRequestBody(exchange));
  Mockito.verify(inputStream, Mockito.atLeastOnce()).close();
}
 
Example 32
Project: JFaceUtils   File: BaseHttpHandler.java   View source code 6 votes vote down vote up
protected Map<String, Object> buildSafeHeadersMap(final Headers headers) {
	final Map<String, Object> headersToLog = new TreeMap<String, Object>();
	for (final Entry<String, List<String>> entry : headers.entrySet()) {
		final String key = entry.getKey();
		if (key != null) {
			final String lowerCaseKey = key.toLowerCase();
			for (final String maskedHeaderKey : maskedHeaderKeys) {
				if (lowerCaseKey.contains(maskedHeaderKey)) {
					headersToLog.put(key, "****");
					break;
				}
			}
			if (!headersToLog.containsKey(key)) {
				headersToLog.put(key, entry.getValue());
			}
		}
	}
	return headersToLog;
}
 
Example 33
Project: jdk7-jdk   File: Deadlock.java   View source code 6 votes vote down vote up
@Override
public void handle (HttpExchange t)
    throws IOException
{
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    while (is.read() != -1);
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals("fred")) {
        error = true;
    }
    if (!p.getRealm().equals("[email protected]")) {
        error = true;
    }
    t.close();
}
 
Example 34
Project: transfer-accelerator   File: ServerStatus.java   View source code 6 votes vote down vote up
public void handle(HttpExchange exchange) throws IOException {
  String requestMethod = exchange.getRequestMethod();
  if (requestMethod.equalsIgnoreCase("GET")) {
    boolean isHealthy = serverWithStats.isHealthy();
    Headers responseHeaders = exchange.getResponseHeaders();
    String response = "{ \"version\" : \"" + serverWithStats.getVersion() + "\"}";
    if (isHealthy) {
      responseHeaders.set("Content-Type", "text/html");
      exchange.sendResponseHeaders(200, response.getBytes().length);
    } else {
      responseHeaders.set("Content-Type", "text/html");
      exchange.sendResponseHeaders(500, response.getBytes().length);
    }
    OutputStream responseBody = exchange.getResponseBody();
    Headers requestHeaders = exchange.getRequestHeaders();
    responseBody.write(response.getBytes());
    responseBody.close();
  }
}
 
Example 35
Project: fourinone   File: ParkInetServer.java   View source code 6 votes vote down vote up
public void handle(HttpExchange exchange) throws IOException
{
    /*InputStream is = t.getRequestBody();
    String response = "response ok";
    t.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length());
    OutputStream os = t.getResponseBody();
    os.write(response.getBytes());
    os.close();
    */
    Headers responseHeaders = exchange.getResponseHeaders();
	responseHeaders.set("Content-Type", "text/html");
	String response = ConfigContext.getRequest(ConfigContext.getProp("RSPE404"));
	exchange.sendResponseHeaders(HttpURLConnection.HTTP_NOT_FOUND, response.length());
	OutputStream os = exchange.getResponseBody();
	os.write(response.getBytes());
	os.close();
}
 
Example 36
Project: fourinone   File: ParkInetServer.java   View source code 6 votes vote down vote up
public void handle(HttpExchange exchange) throws IOException
{
	String requestMethod = exchange.getRequestMethod();
	if(requestMethod.equalsIgnoreCase("GET"))
	{
		Headers responseHeaders = exchange.getResponseHeaders();
		responseHeaders.set("Content-Type", "text/plain");
		exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 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();
	}
}
 
Example 37
Project: openjdk-source-code-learn   File: Deadlock.java   View source code 6 votes vote down vote up
@Override
public void handle (HttpExchange t)
    throws IOException
{
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    while (is.read() != -1);
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals("fred")) {
        error = true;
    }
    if (!p.getRealm().equals("[email protected]")) {
        error = true;
    }
    t.close();
}
 
Example 38
Project: OLD-OpenJDK8   File: Deadlock.java   View source code 6 votes vote down vote up
@Override
public void handle (HttpExchange t)
    throws IOException
{
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    while (is.read() != -1);
    is.close();
    t.sendResponseHeaders(200, -1);
    HttpPrincipal p = t.getPrincipal();
    if (!p.getUsername().equals("fred")) {
        error = true;
    }
    if (!p.getRealm().equals("[email protected]")) {
        error = true;
    }
    t.close();
}
 
Example 39
Project: jflask   File: App.java   View source code 6 votes vote down vote up
private String getCookie(HttpExchange r, String name) {
  Headers headers = r.getRequestHeaders();
  if (headers != null) {
    List<String> cookies = headers.get("Cookie");
    if (cookies != null) {
      for (String cookieString : cookies) {
        String[] tokens = cookieString.split("\\s*;\\s*");
        for (String token : tokens) {
          if (token.startsWith(name) && token.charAt(name.length()) == '=') {
            return token.substring(name.length() + 1);
          }
        }
      }
    }
  }
  return null;
}
 
Example 40
Project: hsac-fitnesse-fixtures   File: HttpServer.java   View source code 6 votes vote down vote up
protected Charset getCharSet(Headers heHeaders) {
    Charset charset = UTF8;
    String contentTypeHeader = heHeaders.getFirst(HTTP.CONTENT_TYPE);
    if (contentTypeHeader != null) {
        try {
            ContentType contentType = ContentType.parse(contentTypeHeader);
            Charset contentTypeCharset = contentType.getCharset();
            if (contentTypeCharset != null) {
                charset = contentTypeCharset;
            }
        } catch (ParseException | UnsupportedCharsetException e) {
            // ignore, use default charset UTF8
        }
    }
    return charset;
}