Java Code Examples for com.sun.net.httpserver.HttpExchange#getResponseBody()

The following examples show how to use com.sun.net.httpserver.HttpExchange#getResponseBody() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InternalHttpServer.java    From zxpoly with GNU General Public License v3.0 7 votes vote down vote up
private void handleStreamData(final HttpExchange exchange) throws IOException {
  final Headers headers = exchange.getResponseHeaders();
  headers.add("Content-Type", this.mime);
  headers.add("Cache-Control", "no-cache, no-store");
  headers.add("Pragma", "no-cache");
  headers.add("Transfer-Encoding", "chunked");
  headers.add("Content-Transfer-Encoding", "binary");
  headers.add("Expires", "0");
  headers.add("Connection", "Keep-Alive");
  headers.add("Keep-Alive", "max");
  headers.add("Accept-Ranges", "none");

  exchange.sendResponseHeaders(200, 0);

  OutputStream os = exchange.getResponseBody();
  try {
    final TcpReader reader = this.tcpReaderRef.get();
    if (reader != null) {
      while (!stopped && !Thread.currentThread().isInterrupted()) {
        final byte[] data = reader.read();
        if (data != null) {
          os.write(data);
          os.flush();
        }
      }
    }
  } finally {
    os.close();
  }
}
 
Example 2
Source File: MobileLyricsServer.java    From Quelea with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void handle(HttpExchange he) throws IOException {
    String response = "";
    LivePanel lp = QueleaApp.get().getMainWindow().getMainPanel().getLivePanel();
    if (running && lp.getDisplayable() instanceof TextDisplayable) {
        if (he.getRequestURI().toString().contains("/songtranslations")) {
            response = listSongTranslations(he);
        } else {
            response = getSongTranslation(he);
        }
        if (getLyrics(false).equals("")) {
            response = "";
        }
    }
    he.getResponseHeaders().add("Cache-Control", "no-cache, no-store, must-revalidate");
    he.sendResponseHeaders(200, response.getBytes(Charset.forName("UTF-8")).length);
    OutputStream os = he.getResponseBody();
    os.write(response.getBytes(Charset.forName("UTF-8")));
    os.close();
}
 
Example 3
Source File: BasicAuthTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange he) throws IOException {
    String method = he.getRequestMethod();
    InputStream is = he.getRequestBody();
    if (method.equalsIgnoreCase("POST")) {
        String requestBody = new String(is.readAllBytes(), US_ASCII);
        if (!requestBody.equals(POST_BODY)) {
            he.sendResponseHeaders(500, -1);
            ok = false;
        } else {
            he.sendResponseHeaders(200, -1);
            ok = true;
        }
    } else { // GET
        he.sendResponseHeaders(200, RESPONSE.length());
        OutputStream os = he.getResponseBody();
        os.write(RESPONSE.getBytes(US_ASCII));
        os.close();
        ok = true;
    }
}
 
Example 4
Source File: ConsoleProxyAjaxHandler.java    From cosmic with Apache License 2.0 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");
    hds.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
    t.sendResponseHeaders(200, response.length());

    final OutputStream os = t.getResponseBody();
    try {
        os.write(response.getBytes());
    } finally {
        os.close();
    }
}
 
Example 5
Source File: RemoteControlServer.java    From Quelea with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void handle(HttpExchange he) throws IOException {
    if (RCHandler.isLoggedOn(he.getRemoteAddress().getAddress().toString())) {
        String pageContent = readFile("server/addpassagercspage.htm");
        pageContent = pageContent.replace("$1", LabelGrabber.INSTANCE.getLabel("rcs.submit"));
        pageContent = pageContent.replace("$2", LabelGrabber.INSTANCE.getLabel("bible.passage.selector.prompt"));
        byte[] bytes = pageContent.getBytes(Charset.forName("UTF-8"));
        he.getResponseHeaders().add("Cache-Control", "no-cache, no-store, must-revalidate");
        he.sendResponseHeaders(200, bytes.length);
        try (OutputStream os = he.getResponseBody()) {
            os.write(bytes);
        }
    } else {
        passwordPage(he);
    }
}
 
Example 6
Source File: RemoteControlServer.java    From Quelea with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    if (RCHandler.isLoggedOn(t.getRemoteAddress().getAddress().toString())) {
        byte[] byteArray = RCHandler.getPresentationSlides(t);
        t.getResponseHeaders().add("Cache-Control", "no-cache, no-store, must-revalidate");
        t.sendResponseHeaders(200, byteArray.length);
        try (OutputStream out = t.getResponseBody()) {
            out.write(byteArray);
        }
    } else {
        passwordPage(t);
    }
}
 
Example 7
Source File: B4769350.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static void okReply (HttpExchange exchange) throws IOException {
    exchange.getResponseHeaders().add("Connection", "close");
    String response = "Hello .";
    exchange.sendResponseHeaders(200, response.getBytes().length);
    OutputStream os = exchange.getResponseBody();
    os.write(response.getBytes());
    os.close();
    exchange.close();
}
 
Example 8
Source File: HttpsCreateSockTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    t.sendResponseHeaders(200, message.length());
    BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(t.getResponseBody(), "ISO8859-1"));
    writer.write(message, 0, message.length());
    writer.close();
    t.close();
}
 
Example 9
Source File: ConsoleProxyAjaxHandler.java    From cosmic with Apache License 2.0 5 votes vote down vote up
private void handleClientUpdate(final HttpExchange t, final ConsoleProxyClient viewer) throws IOException {
    final String response = viewer.onAjaxClientUpdate();

    final Headers hds = t.getResponseHeaders();
    hds.set("Content-Type", "text/javascript");
    hds.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
    t.sendResponseHeaders(200, response.length());

    final OutputStream os = t.getResponseBody();
    try {
        os.write(response.getBytes());
    } finally {
        os.close();
    }
}
 
Example 10
Source File: HttpStreams.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    try (InputStream is = t.getRequestBody()) {
        while (is.read() != -1);
    }
    t.sendResponseHeaders(respCode(), length());
    try (OutputStream os = t.getResponseBody()) {
        os.write(message());
    }
    t.close();
}
 
Example 11
Source File: TestClusterManager.java    From rubix with Apache License 2.0 5 votes vote down vote up
public void handle(HttpExchange exchange) throws IOException
{
  String nodes = "[{\"uri\":\"http://192.168.2.252:8083\",\"recentRequests\":119.0027780896941,\"recentFailures\":119.00267353393015,\"recentSuccesses\":1.0845754237194612E-4,\"lastRequestTime\":\"2016-01-14T13:26:29.948Z\",\"lastResponseTime\":\"2016-01-14T13:26:29.948Z\",\"recentFailureRatio\":0.999999121400646,\"age\":\"6.68h\",\"recentFailuresByType\":{\"java.util.concurrent.TimeoutException\":2.4567611856996272E-6,\"java.net.SocketTimeoutException\":119.00237271323728,\"java.net.SocketException\":2.98363931759331E-4}},{\"uri\":\"http://192.168.1.3:8082\",\"recentRequests\":119.00277802527565,\"recentFailures\":119.00282273097419,\"recentSuccesses\":0.0,\"lastRequestTime\":\"2016-01-14T13:26:29.701Z\",\"lastResponseTime\":\"2016-01-14T13:26:29.701Z\",\"recentFailureRatio\":1.0000003756693692,\"age\":\"21.81h\",\"recentFailuresByType\":{\"java.util.concurrent.TimeoutException\":0.0,\"java.net.SocketTimeoutException\":119.00258110193407,\"java.net.ConnectException\":0.0,\"java.net.SocketException\":2.416290401318479E-4,\"java.net.NoRouteToHostException\":1.3332509542453224E-21}}]\n";
  exchange.getResponseHeaders().add("Content-Type", "application/json");
  exchange.sendResponseHeaders(200, nodes.length());
  OutputStream os = exchange.getResponseBody();
  os.write(nodes.getBytes());
  os.close();
}
 
Example 12
Source File: LocalHttpGateway.java    From startup-os with Apache License 2.0 5 votes vote down vote up
public void handle(HttpExchange httpExchange) throws IOException {
  httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
  httpExchange
      .getResponseHeaders()
      .add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  final byte[] response = "OK".getBytes(UTF_8);
  httpExchange.sendResponseHeaders(HTTP_STATUS_CODE_OK, response.length);
  try (OutputStream stream = httpExchange.getResponseBody()) {
    stream.write(response);
  }
}
 
Example 13
Source File: LocalFileRepoOverHttp.java    From ant-ivy with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(final HttpExchange httpExchange) throws IOException {
    final URI requestURI = httpExchange.getRequestURI();
    Message.info("Handling " + httpExchange.getRequestMethod() + " request " + requestURI);
    final URI artifactURI;
    try {
        artifactURI = new URI(webContextRoot).relativize(requestURI);
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    final Path localFilePath = localFileRepoRoot.resolve(artifactURI.toString());
    if (httpExchange.getRequestMethod().equals("HEAD")) {
        final boolean available = this.isPresent(localFilePath);
        if (!available) {
            httpExchange.sendResponseHeaders(404, -1);
        } else {
            httpExchange.sendResponseHeaders(200, -1);
        }
        return;
    }
    if (!httpExchange.getRequestMethod().equals("GET")) {
        throw new IOException("Cannot handle " + httpExchange.getRequestMethod() + " HTTP method");
    }
    final OutputStream responseStream = httpExchange.getResponseBody();
    @SuppressWarnings("unused")
    final int numBytes = this.serve(httpExchange, localFilePath, responseStream);
    responseStream.close();
}
 
Example 14
Source File: EHHttpHandler.java    From easy-httpserver with Apache License 2.0 5 votes vote down vote up
/**
 * 响应请求,返回静态资源
 * @param httpExchange
 * @param code
 * @param bytes
 * @throws IOException
 */
private void responseStaticToClient(HttpExchange httpExchange, Integer code, byte[] bytes)
		throws IOException {
	httpExchange.sendResponseHeaders(code, bytes.length);
	OutputStream out = httpExchange.getResponseBody();
	out.write(bytes);
	out.flush();
	httpExchange.close();
}
 
Example 15
Source File: InfiniteLoop.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    InputStream is  = t.getRequestBody();
    byte[] ba = new byte[8192];
    while(is.read(ba) != -1);

    t.sendResponseHeaders(200, RESP_LENGTH);
    try (OutputStream os = t.getResponseBody()) {
        os.write(new byte[RESP_LENGTH]);
    }
    t.close();
}
 
Example 16
Source File: WebApp.java    From hbase-tools with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    if (html == null) {
        html = Util.getResource("webapp/js/jquery-2.1.4.min.js");
    }
    t.sendResponseHeaders(200, html.getBytes(Constant.CHARSET).length);
    OutputStream os = t.getResponseBody();
    os.write(html.getBytes(Constant.CHARSET));
    os.close();
}
 
Example 17
Source File: TestClusterManager.java    From rubix with Apache License 2.0 5 votes vote down vote up
public void handle(HttpExchange exchange) throws IOException
{
  String nodes = "[{\"uri\":\"http://192.168.1.3:8082\",\"recentRequests\":119.00277802527565,\"recentFailures\":119.00282273097419,\"recentSuccesses\":0.0,\"lastRequestTime\":\"2016-01-14T13:26:29.701Z\",\"lastResponseTime\":\"2016-01-14T13:26:29.701Z\",\"recentFailureRatio\":1.0000003756693692,\"age\":\"21.81h\",\"recentFailuresByType\":{\"java.util.concurrent.TimeoutException\":0.0,\"java.net.SocketTimeoutException\":119.00258110193407,\"java.net.ConnectException\":0.0,\"java.net.SocketException\":2.416290401318479E-4,\"java.net.NoRouteToHostException\":1.3332509542453224E-21}}]\n";
  exchange.getResponseHeaders().add("Content-Type", "application/json");
  exchange.sendResponseHeaders(200, nodes.length());
  OutputStream os = exchange.getResponseBody();
  os.write(nodes.getBytes());
  os.close();
}
 
Example 18
Source File: WebApp.java    From hbase-tools with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    if (html == null) {
        html = Util.getResource("webapp/js/jquery-2.1.4.min.js");
    }
    t.sendResponseHeaders(200, html.getBytes(Constant.CHARSET).length);
    OutputStream os = t.getResponseBody();
    os.write(html.getBytes(Constant.CHARSET));
    os.close();
}
 
Example 19
Source File: HttpExchangeUtil.java    From idea-php-toolbox with MIT License 4 votes vote down vote up
public static void sendResponse(HttpExchange xchg, StringBuilder response) throws IOException {
    xchg.sendResponseHeaders(200, response.length());
    OutputStream os = xchg.getResponseBody();
    os.write(response.toString().getBytes());
    os.close();
}
 
Example 20
Source File: StoreHandler.java    From protect with MIT License 4 votes vote down vote up
@Override
public void authenticatedClientHandle(final HttpExchange exchange, final String username)
		throws IOException, UnauthorizedException, NotFoundException, BadRequestException,
		ResourceUnavailableException, ConflictException, InternalServerException {

	// Extract secret name from request
	final String queryString = exchange.getRequestURI().getQuery();
	final Map<String, List<String>> params = HttpRequestProcessor.parseQueryString(queryString);

	final String secretName = HttpRequestProcessor.getParameterValue(params, SECRET_NAME_FIELD);
	if (secretName == null) {
		throw new BadRequestException();
	}

	// Perform authentication
	accessEnforcement.enforceAccess(username, secretName, REQUEST_PERMISSION);

	// Ensure shareholder exists
	final ApvssShareholder shareholder = this.shareholders.get(secretName);
	if (shareholder == null) {
		throw new NotFoundException();
	}
	// Make sure secret is not disabled
	if (!shareholder.isEnabled()) {
		throw new ResourceUnavailableException();
	}
	// If DKG already started, it is too late, but we allow RSA keys to be updated
	if ((shareholder.getSharingType() != null)) {
		throw new ConflictException();
	}

	// Parse values from RSA storage operation
	final String nStr = HttpRequestProcessor.getParameterValue(params, MODULUS_VALUE);
	final BigInteger n = (nStr == null) ? null : new BigInteger(nStr);

	final String eStr = HttpRequestProcessor.getParameterValue(params, PUBLIC_EXPONENT_VALUE);
	final BigInteger e = (eStr == null) ? null : new BigInteger(eStr);

	final String vStr = HttpRequestProcessor.getParameterValue(params, VERIFICATION_BASE);
	final BigInteger v = (vStr == null) ? null : new BigInteger(vStr);

	final BigInteger[] verificationKeys = new BigInteger[shareholder.getN()];
	for (int i = 1; i <= shareholder.getN(); i++) {
		final String vStrI = HttpRequestProcessor.getParameterValue(params, VERIFICATION_KEYS + i);
		verificationKeys[i - 1] = (vStrI == null) ? null : new BigInteger(vStrI);
	}

	// Prepare to formulate response
	final int serverIndex = shareholder.getIndex();
	final String response;

	// Extract share from the request
	final List<String> shareValues = params.get(SHARE_VALUE);
	if ((shareValues == null) || (shareValues.size() != 1) || (shareValues.get(0) == null)) {
		// Unset the stored value
		shareholder.setStoredShareOfSecret(null);
		response = "s_" + serverIndex + " has been unset, DKG will use a random value for '" + secretName + "'.";
	} else {
		final BigInteger shareValue = new BigInteger(shareValues.get(0));
		if ((e != null) && (n != null) && (v != null)) {
			// Store RSA share, e and exponent n
			RSAPublicKeySpec spec = new RSAPublicKeySpec(n, e);
			KeyFactory keyFactory;
			try {
				keyFactory = KeyFactory.getInstance("RSA");

				final RsaSharing rsaSharing = new RsaSharing(shareholder.getN(), shareholder.getK(), (RSAPublicKey) keyFactory.generatePublic(spec), null, null, v, verificationKeys);
				shareholder.setRsaSecret(shareValue, rsaSharing);
				response = "RSA share have been stored.";
			}
			 catch ( NoSuchAlgorithmException | InvalidKeySpecException e1) {
				 throw new InternalServerException();
			 }
		} else {
			shareholder.setStoredShareOfSecret(shareValue);
			response = "s_" + serverIndex + " has been stored, DKG will use it for representing '" + secretName
					+ "' in the DKG.";
		}
	}

	// Create response
	final byte[] binaryResponse = response.getBytes(StandardCharsets.UTF_8);

	// Write headers
	exchange.sendResponseHeaders(HttpStatusCode.SUCCESS, binaryResponse.length);

	// Write response
	try (final OutputStream os = exchange.getResponseBody();) {
		os.write(binaryResponse);
	}
}