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   Source Code and License 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   Source Code and License 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: Deadlock.java   Source Code and License 8 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 4
Project: openjdk-jdk10   File: HttpOnly.java   Source Code and License 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 5
Project: trap   File: CORSUtil.java   Source Code and License 8 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 6
Project: jflask   File: App.java   Source Code and License 7 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 7
Project: graphflow   File: PlanViewerHttpServer.java   Source Code and License 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 8
Project: secondbase   File: PrometheusWebConsoleTest.java   Source Code and License 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 9
Project: jdk8u-jdk   File: Deadlock.java   Source Code and License 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: WLT3Serial   File: WebServerTestHelper.java   Source Code and License 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 11
Project: openjdk-jdk10   File: Security.java   Source Code and License 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 12
Project: openjdk-jdk10   File: SmokeTest.java   Source Code and License 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 13
Project: openjdk-jdk10   File: SmokeTest.java   Source Code and License 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 14
Project: openjdk-jdk10   File: LightWeightHttpServer.java   Source Code and License 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 15
Project: openjdk-jdk10   File: HeadersTest1.java   Source Code and License 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 16
Project: openjdk9   File: Deadlock.java   Source Code and License 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 17
Project: openjdk9   File: LightWeightHttpServer.java   Source Code and License 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 18
Project: openjdk9   File: HeadersTest1.java   Source Code and License 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 19
Project: DigitalMediaServer   File: RemoteUtil.java   Source Code and License 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 20
Project: WatCA   File: WebServer.java   Source Code and License 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 21
Project: openbravo-pos   File: JettyHttpExchange.java   Source Code and License 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 22
Project: cosmic   File: ConsoleProxyCmdHandler.java   Source Code and License 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 23
Project: cosmic   File: ConsoleProxyAjaxHandler.java   Source Code and License 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 24
Project: jdk8u_jdk   File: Deadlock.java   Source Code and License 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: lookaside_java-1.8.0-openjdk   File: Deadlock.java   Source Code and License 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 26
Project: Disco   File: TaxServer.java   Source Code and License 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 27
Project: lab-materials   File: ServerHandler.java   Source Code and License 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 28
Project: lab-materials   File: ServerHandler.java   Source Code and License 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 29
Project: infobip-open-jdk-8   File: Deadlock.java   Source Code and License 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: jdk8u-dev-jdk   File: Deadlock.java   Source Code and License 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 31
Project: heron   File: NetworkUtilsTest.java   Source Code and License 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 32
Project: heron   File: NetworkUtilsTest.java   Source Code and License 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 33
Project: JFaceUtils   File: BaseHttpHandler.java   Source Code and License 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 34
Project: jdk7-jdk   File: Deadlock.java   Source Code and License 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 35
Project: transfer-accelerator   File: ServerStatus.java   Source Code and License 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 36
Project: fourinone   File: ParkInetServer.java   Source Code and License 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 37
Project: fourinone   File: ParkInetServer.java   Source Code and License 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 38
Project: openjdk-source-code-learn   File: Deadlock.java   Source Code and License 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: OLD-OpenJDK8   File: Deadlock.java   Source Code and License 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 40
Project: hsac-fitnesse-fixtures   File: HttpServer.java   Source Code and License 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;
}
 
Example 41
Project: JAVA_UNIT   File: Deadlock.java   Source Code and License 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 42
Project: openjdk-jdk7u-jdk   File: Deadlock.java   Source Code and License 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 43
Project: supoxy   File: SuPoxyServer.java   Source Code and License 6 votes vote down vote up
public void handle(HttpExchange t) throws IOException {

			StringWriter sw = new StringWriter();

			SuPoxyDataObject data = SunnyList.get(SunnyList.size()-1);

			sw.write(data.getJSONRaw());
			String response = sw.toString();

			Headers h = t.getResponseHeaders();
			h.set("Content-Type","application/json");

			t.sendResponseHeaders(200, response.length());
			OutputStream os = t.getResponseBody();
			os.write(response.getBytes());
			os.close();
		}
 
Example 44
Project: pinot   File: FileUploadDownloadClientTest.java   Source Code and License 6 votes vote down vote up
@Override
public void handle(HttpExchange httpExchange) throws IOException {
  Headers requestHeaders = httpExchange.getRequestHeaders();
  String uploadTypeStr = requestHeaders.getFirst(FileUploadDownloadClient.CustomHeaders.UPLOAD_TYPE);
  FileUploadType uploadType = FileUploadType.valueOf(uploadTypeStr);

  String downloadUri = null;
  if (uploadType == FileUploadType.JSON) {
    InputStream bodyStream = httpExchange.getRequestBody();
    try {
      JSONObject jsonObject = new JSONObject(IOUtils.toString(bodyStream, "UTF-8"));
      downloadUri = (String) jsonObject.get(CommonConstants.Segment.Offline.DOWNLOAD_URL);
    } catch (JSONException e) {
      throw new RuntimeException(e);
    }
    Assert.assertEquals(downloadUri, TEST_URI);
  } else if (uploadType == FileUploadType.URI) {
    downloadUri = requestHeaders.getFirst(FileUploadDownloadClient.CustomHeaders.DOWNLOAD_URI);
  } else {
    Assert.fail();
  }
  Assert.assertEquals(downloadUri, TEST_URI);
  sendResponse(httpExchange, HttpStatus.SC_OK, "OK");
}
 
Example 45
Project: cloudstack   File: ConsoleProxyCmdHandler.java   Source Code and License 6 votes vote down vote up
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();
    }
}
 
Example 46
Project: cloudstack   File: ConsoleProxyAjaxHandler.java   Source Code and License 6 votes vote down vote up
private void handleClientStart(HttpExchange t, ConsoleProxyClient viewer, String title, String guest) throws IOException {
    List<String> languages = t.getRequestHeaders().get("Accept-Language");
    String response = viewer.onAjaxClientStart(title, languages, guest);

    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());

    OutputStream os = t.getResponseBody();
    try {
        os.write(response.getBytes());
    } finally {
        os.close();
    }
}
 
Example 47
Project: OpenbravoPOS   File: JettyHttpExchange.java   Source Code and License 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 48
Project: openjdk-icedtea7   File: Deadlock.java   Source Code and License 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 49
Project: smscenter   File: HttpConnectionHandlerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testHandleWrongXml() throws IOException {
    HttpExchange exchange = mock(HttpExchange.class);
    when(exchange.getRemoteAddress()).thenReturn(new InetSocketAddress(80));
    byte[] bytes = "WRONG".getBytes(CHARSET);
    when(exchange.getRequestBody()).thenReturn(new ByteArrayInputStream(bytes));
    Headers headers = mock(Headers.class);
    when(exchange.getResponseHeaders()).thenReturn(headers);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    when(exchange.getResponseBody()).thenReturn(out);

    handler.handle(exchange);
    verify(exchange, times(1)).sendResponseHeaders(eq(200), eq(0L));
    String responseXml = new String(out.toByteArray(), CHARSET);
    HttpResponse response = (HttpResponse) xstream.fromXML(responseXml);
    assertNotNull(response);
    assertEquals(new Integer(HttpReceiverErrorCodes.ERR_INV_XML), response.getErrorCode());
}
 
Example 50
Project: smscenter   File: HttpConnectionHandlerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testHandleInvalidUser() throws IOException {
    HttpExchange exchange = mock(HttpExchange.class);
    when(exchange.getRemoteAddress()).thenReturn(new InetSocketAddress(80));
    String requestXml = createSendRequest();
    when(exchange.getRequestBody()).thenReturn(new ByteArrayInputStream(requestXml.getBytes(CHARSET)));
    Headers headers = mock(Headers.class);
    when(exchange.getResponseHeaders()).thenReturn(headers);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    when(exchange.getResponseBody()).thenReturn(out);

    handler.handle(exchange);
    verify(exchange, times(1)).sendResponseHeaders(eq(200), eq(0L));
    String responseXml = new String(out.toByteArray(), CHARSET);
    HttpResponse response = (HttpResponse) xstream.fromXML(responseXml);
    assertNotNull(response);
    assertEquals(new Integer(HttpReceiverErrorCodes.ERR_INV_PASWD), response.getErrorCode());
}
 
Example 51
Project: smscenter   File: HttpReceiverTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() {
    receiver = new HttpReceiver();
    receiver.setPort(80);
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            HttpExchange exchange = (HttpExchange) invocation.getArguments()[0];
            Headers headers = exchange.getResponseHeaders();
            headers.set("Content-Type", "text/html");
            exchange.sendResponseHeaders(200, 0);
            Writer writer = new OutputStreamWriter(exchange.getResponseBody(), "UTF-8");
            writer.write("<html><head><title>[400] Bad Request</title></head><body><h1>Bad Request</h1></body></html>");
            writer.close();
            exchange.close();
            return null;
        }
    }).when(connectionHandler).handle(any(HttpExchange.class));
    receiver.setHttpConnectionHandler(connectionHandler);
}
 
Example 52
Project: Fourinone   File: ParkInetServer.java   Source Code and License 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 53
Project: Fourinone   File: ParkInetServer.java   Source Code and License 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 54
Project: pentaho-kettle   File: JobEntryHTTP_PDI208_Test.java   Source Code and License 6 votes vote down vote up
private static void startHTTPServer() throws IOException {
  httpServer = HttpServer.create( new InetSocketAddress( JobEntryHTTP_PDI208_Test.HTTP_HOST, JobEntryHTTP_PDI208_Test.HTTP_PORT ), 10 );
  httpServer.createContext( "/uploadFile", new HttpHandler() {
    @Override
    public void handle( HttpExchange httpExchange ) throws IOException {
      Headers h = httpExchange.getResponseHeaders();
      h.add( "Content-Type", "application/octet-stream" );
      httpExchange.sendResponseHeaders( 200, 0 );
      InputStream is = httpExchange.getRequestBody();
      OutputStream os = httpExchange.getResponseBody();
      int inputChar = -1;
      while ( ( inputChar = is.read() ) >= 0 ) {
        os.write( inputChar );
      }
      is.close();
      os.flush();
      os.close();
      httpExchange.close();
    }
  } );
  httpServer.start();
}
 
Example 55
Project: health-and-care-developer-network   File: RequestHeadersHelper.java   Source Code and License 6 votes vote down vote up
@Nullable
@NonNls
public static Date validateZeroOrOneInstanceOfRfc2822Header(@NotNull final Headers requestHeaders, @NotNull @RequestHeader final String requestHeader) throws BadRequestException
{
	@NonNls @Nullable final String value = validateZeroOrOneInstanceOfRequestHeader(requestHeaders, requestHeader);
	if (value == null)
	{
		return null;
	}
	try
	{
		return fromRfc2822Form(value);
	}
	catch (ParseException e)
	{
		throw new BadRequestException(format(ENGLISH, "Could not parse RFC2822 date (%2$s) in Request header %1$s", requestHeader, value), e);
	}
}
 
Example 56
Project: health-and-care-developer-network   File: RequestHeadersHelper.java   Source Code and License 6 votes vote down vote up
@Nullable @NonNls
public static String validateZeroOrOneInstanceOfRequestHeader(@NotNull final Headers requestHeaders, @NotNull @RequestHeader final String requestHeader) throws BadRequestException
{
	@Nullable final List<String> strings = requestHeaders.get(requestHeader);
	if (strings == null)
	{
		return null;
	}
	final int size = strings.size();
	if (size == 1)
	{
		return strings.get(0);
	}
	if (size == 0)
	{
		return null;
	}
	throw new BadRequestException(format(ENGLISH, "More than one value for Request header %1$s", requestHeader));
}
 
Example 57
Project: health-and-care-developer-network   File: RequestHeadersHelper.java   Source Code and License 6 votes vote down vote up
public static boolean validateConnectionRequestHeader(@NotNull final Headers requestHeaders) throws BadRequestException
{
	@NonNls @Nullable final String value = validateZeroOrOneInstanceOfRequestHeader(requestHeaders, ConnectionHeaderName);
	if (value == null)
	{
		return false;
	}
	if (KeepAlive.equalsIgnoreCase(value))
	{
		return true;
	}
	if (Close.equalsIgnoreCase(value))
	{
		return false;
	}
	throw new BadRequestException(format(ENGLISH, "Unrecognised value %1$s for Connection header", value));
}
 
Example 58
Project: health-and-care-developer-network   File: ResponseHeadersHelper.java   Source Code and License 6 votes vote down vote up
@NotNull
public static Headers withoutEntityHeaders(@NotNull final HttpExchange httpExchange, @NotNull final String cacheControlHeaderValue)
{
	final Headers responseHeaders = httpExchange.getResponseHeaders();
	responseHeaders.set(ServerHeaderName, ServerHeaderValue);
	responseHeaders.set(DateHeaderName, rfc2822DateForNow());
	responseHeaders.set(ContentLanguageHeaderName, ContentLanguageHeaderValue);
	responseHeaders.set(ConnectionHeaderName, "close");
	final boolean isHttps = httpExchange instanceof HttpsExchange;
	if (isHttps)
	{
		responseHeaders.set(StrictTransportSecurityHeaderName, StrictTransportSecurityHeaderValueMaximum);
	}
	responseHeaders.set(XFrameOptionsHeaderName, "DENY");
	responseHeaders.set(XXssProtectionHeaderName, "1; mode=block");
	responseHeaders.set(XRimAutoMatchHeaderName, "none");
	responseHeaders.set(XRobotsTagHeaderName, "none");
	responseHeaders.set(AccessControlAllowOriginHeaderName, "*");
	responseHeaders.set(AccessControlAllowMethodsHeaderName, "POST, PUT, DELETE, GET, HEAD, OPTIONS");
	responseHeaders.set(AccessControlAllowHeadersHeaderName, "Authorization, Content-Type");
	responseHeaders.set(CacheControlHeaderName, cacheControlHeaderValue);
	responseHeaders.set(AcceptRangesHeaderName, "none");
	return responseHeaders;
}
 
Example 59
Project: autorest-streaming-example   File: Sun.java   Source Code and License 5 votes vote down vote up
private static boolean CORS(HttpExchange httpExchange) throws IOException {
    Headers headers = httpExchange.getResponseHeaders();
    headers.add("Access-Control-Allow-Headers", "Content-Type");
    headers.add("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE");
    headers.add("Access-Control-Allow-Origin", httpExchange.getRequestHeaders().getFirst("origin"));
    headers.add("Access-Control-Max-Age", "3600");

    if (!httpExchange.getRequestMethod().equals("OPTIONS")) return false;
    httpExchange.sendResponseHeaders(200, 0);
    write(httpExchange, "");
    return true;
}
 
Example 60
Project: V8LogScanner   File: RegExp.java   Source Code and License 5 votes vote down vote up
private void buildVRSREQUEST() {
    rgxNode.add(PropTypes.Process);
    rgxNode.add(PropTypes.Method);
    rgxNode.add(PropTypes.URI);
    rgxNode.add(PropTypes.Headers);
    rgxNode.add(PropTypes.Body);
    rgxNode.add(PropTypes.Context);

    Filter filter = getFilter(PropTypes.Event);
    filter.add("VRSREQUEST");
}