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

The following examples show how to use com.sun.net.httpserver.HttpExchange. These examples are extracted from open source projects. 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 Project: Quelea   Author: quelea-projection   File: RemoteControlServer.java    License: 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())) {
        if (pageContent == null || !USE_CACHE) {
            pageContent = readFile("server/defaultrcspage.htm");
            pageContent = langStrings(pageContent);
        }
        byte[] bytes = pageContent.getBytes(Charset.forName("UTF-8"));
        he.sendResponseHeaders(200, bytes.length);
        try (OutputStream os = he.getResponseBody()) {
            os.write(bytes);
        }
    } else {
        passwordPage(he);
    }
}
 
Example #2
Source Project: openjdk-8-source   Author: keerath   File: B4769350.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    switch(count) {
        case 0:
            AuthenticationHandler.proxyReply(exchange,
                    "Basic realm=\"proxy\"");
            break;
        case 1:
            t3cond1.countDown();
            AuthenticationHandler.errorReply(exchange,
                    "Basic realm=\"realm4\"");
            break;
        case 2:
            AuthenticationHandler.okReply(exchange);
            break;
        default:
            System.out.println ("Unexpected request");
    }
}
 
Example #3
Source Project: Fibry   Author: lucav76   File: TestRemoteActors.java    License: MIT License 6 votes vote down vote up
public void testWithReturnJackson() throws IOException, InterruptedException, ExecutionException {
    CountDownLatch latch = new CountDownLatch(1);
    int port = 9005;

    Stereotypes.def().embeddedHttpServer(port, (HttpExchange ex) -> {
        latch.countDown();
        System.out.println(ex.getRequestURI().getQuery());

        return "{\"number\":\"+47012345678\"}";
    });

    var user = new User("TestUser");
    var phone = new PhoneNumber("+47012345678");
    var actor = ActorSystem.anonymous().<User, PhoneNumber>newRemoteActorWithReturn("actor2", new HttpChannel("http://localhost:" + port + "/", HttpChannel.HttpMethod.GET, null, null, false), new JacksonSerDeser<>(PhoneNumber.class));
    var result = actor.sendMessageReturn(user);

    latch.await(1, TimeUnit.SECONDS);
    System.out.println(result.get());
    Assert.assertEquals(phone, result.get());
}
 
Example #4
Source Project: spring-analysis-note   Author: Vip-Augus   File: SimpleHessianServiceExporter.java    License: MIT License 6 votes vote down vote up
/**
 * Processes the incoming Hessian request and creates a Hessian response.
 */
@Override
public void handle(HttpExchange exchange) throws IOException {
	if (!"POST".equals(exchange.getRequestMethod())) {
		exchange.getResponseHeaders().set("Allow", "POST");
		exchange.sendResponseHeaders(405, -1);
		return;
	}

	ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
	try {
		invoke(exchange.getRequestBody(), output);
	}
	catch (Throwable ex) {
		exchange.sendResponseHeaders(500, -1);
		logger.error("Hessian skeleton invocation failed", ex);
		return;
	}

	exchange.getResponseHeaders().set("Content-Type", CONTENT_TYPE_HESSIAN);
	exchange.sendResponseHeaders(200, output.size());
	FileCopyUtils.copy(output.toByteArray(), exchange.getResponseBody());
}
 
Example #5
Source Project: incubator-heron   Author: apache   File: MetricsCacheManagerHttpServer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange httpExchange) throws IOException {
  // get the entire stuff
  byte[] payload = NetworkUtils.readHttpRequestBody(httpExchange);
  T req;
  try {
    req = parseRequest(payload);
  } catch (InvalidProtocolBufferException e) {
    LOG.log(Level.SEVERE,
        "Unable to decipher data specified in Request: " + httpExchange, e);
    httpExchange.sendResponseHeaders(400, -1); // throw exception
    return;
  }
  U res = generateResponse(req, metricsCache);
  NetworkUtils.sendHttpResponse(httpExchange, res.toByteArray());
  httpExchange.close();
}
 
Example #6
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: B4769350.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    try {
        switch(count) {
            case 0:
                AuthenticationHandler.errorReply(exchange,
                        "Basic realm=\"realm1\"");
                break;
            case 1:
                t1Cond1.await();
                AuthenticationHandler.okReply(exchange);
                break;
            default:
                System.out.println ("Unexpected request");
        }
    } catch (InterruptedException |
                     BrokenBarrierException e)
            {
                throw new RuntimeException(e);
            }
}
 
Example #7
Source Project: dragonwell8_jdk   Author: alibaba   File: ChunkedEncodingTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    InputStream is = t.getRequestBody();
    while (is.read() != -1);
    is.close();

    t.sendResponseHeaders (200, 0);
    OutputStream os = t.getResponseBody();
    DigestOutputStream dos = new DigestOutputStream(os, serverDigest);

    int offset = 0;
    for (int i=0; i<52; i++) {
        dos.write(baMessage, offset, CHUNK_SIZE);
        offset += CHUNK_SIZE;
    }
    serverMac = serverDigest.digest();
    os.close();
    t.close();
}
 
Example #8
Source Project: Quelea   Author: quelea-projection   File: RCHandler.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static String addSongToSchedule(HttpExchange he) {
    String songIDString;
    long songID;
    if (he.getRequestURI().toString().contains("/add/")) {
        songIDString = he.getRequestURI().toString().split("/add/", 2)[1];
        songID = Long.parseLong(songIDString);
        SongDisplayable sd = SongManager.get().getIndex().getByID(songID);

        Utils.fxRunAndWait(() -> {
            QueleaApp.get().getMainWindow().getMainPanel().getSchedulePanel().getScheduleList().add(sd);
        });

        return LabelGrabber.INSTANCE.getLabel("rcs.add.success");
    }
    return LabelGrabber.INSTANCE.getLabel("rcs.add.failed");
}
 
Example #9
Source Project: openjdk-8-source   Author: keerath   File: B4769350.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    try {
        switch(count) {
            case 0:
                AuthenticationHandler.errorReply(exchange,
                        "Basic realm=\"realm1\"");
                break;
            case 1:
                t1Cond1.await();
                t1cond2latch.await();
                AuthenticationHandler.okReply(exchange);
                break;
            default:
                System.out.println ("Unexpected request");
        }
    } catch (InterruptedException |
                     BrokenBarrierException e)
            {
                throw new RuntimeException(e);
            }
}
 
Example #10
Source Project: alloc   Author: mpusher   File: PushHandler.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handle(HttpExchange httpExchange) throws IOException {
    String body = new String(readBody(httpExchange), Constants.UTF_8);
    Map<String, Object> params = Jsons.fromJson(body, Map.class);

    sendPush(params);

    byte[] data = "服务已经开始推送,请注意查收消息".getBytes(Constants.UTF_8);
    httpExchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
    httpExchange.sendResponseHeaders(200, data.length);//200, content-length
    OutputStream out = httpExchange.getResponseBody();
    out.write(data);
    out.close();
    httpExchange.close();
}
 
Example #11
Source Project: Quelea   Author: quelea-projection   File: RCHandler.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static String getSongTranslation(HttpExchange he) throws UnsupportedEncodingException {
    String language;
    StringBuilder ret = new StringBuilder();
    if (he.getRequestURI().toString().contains("/gettranslation/")) {
        String uri = URLDecoder.decode(he.getRequestURI().toString(), "UTF-8");
        language = uri.split("/gettranslation/", 2)[1];
        final MainPanel p = QueleaApp.get().getMainWindow().getMainPanel();
        int current = p.getSchedulePanel().getScheduleList().getItems().indexOf(p.getLivePanel().getDisplayable());
        SongDisplayable d = ((SongDisplayable) QueleaApp.get().getMainWindow().getMainPanel().getSchedulePanel().getScheduleList().getItems().get(current));
        for (String b : d.getTranslations().keySet()) {
            if (b.equals(language)) {
                ret.append(d.getTranslations().get(language));
            }
        }
    }
    return ret.toString();
}
 
Example #12
Source Project: jstorm   Author: alibaba   File: Httpserver.java    License: Apache License 2.0 6 votes vote down vote up
void handleJstat(HttpExchange t, Map<String, String> paramMap) throws IOException {
    String workerPort = paramMap.get(HttpserverUtils.HTTPSERVER_LOGVIEW_PARAM_WORKER_PORT);
    if (workerPort == null) {
        handlFailure(t, "worker port is not set!");
        return;
    }

    LOG.info("Begin to get jstat of " + workerPort);
    StringBuilder sb = new StringBuilder();
    List<Integer> pids = Worker.getOldPortPids(workerPort);
    for (Integer pid : pids) {
        sb.append("!!!!!!!!!!!!!!!!!!\r\n");
        sb.append("WorkerPort:" + workerPort + ", pid:" + pid);
        sb.append("\r\n!!!!!!!!!!!!!!!!!!\r\n");

        handleJstat(sb, pid);
    }

    byte[] data = sb.toString().getBytes();
    sendResponse(t, HttpURLConnection.HTTP_OK, data);
}
 
Example #13
Source Project: AttestationServer   Author: GrapheneOS   File: AttestationServer.java    License: MIT License 6 votes vote down vote up
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
    final Account account = verifySession(exchange, false, null);
    if (account == null) {
        return;
    }
    exchange.getResponseHeaders().set("Content-Type", "image/png");
    exchange.sendResponseHeaders(200, 0);
    try (final OutputStream output = exchange.getResponseBody()) {
        final String contents = "attestation.app " +
            account.userId + " " +
            BaseEncoding.base64().encode(account.subscribeKey) + " " +
            account.verifyInterval;
        createQrCode(contents.getBytes(), output);
    }
}
 
Example #14
Source Project: jdk8u60   Author: chenghanpeng   File: B4769350.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    switch(count) {
        case 0:
            AuthenticationHandler.errorReply(exchange,
                    "Basic realm=\"realm2\"");
            try {
                t1Cond2.await();
            } catch (InterruptedException |
                     BrokenBarrierException e)
            {
                throw new RuntimeException(e);
            }
            t1cond2latch.countDown();
            break;
        case 1:
            AuthenticationHandler.okReply(exchange);
            break;
        default:
            System.out.println ("Unexpected request");
    }
}
 
Example #15
Source Project: dragonwell8_jdk   Author: alibaba   File: B4769350.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    try {
        switch(count) {
            case 0:
                AuthenticationHandler.errorReply(exchange,
                        "Basic realm=\"realm2\"");
                break;
            case 1:
                t1Cond1.await();
                AuthenticationHandler.okReply(exchange);
                break;
            default:
                System.out.println ("Unexpected request");
        }
    } catch (InterruptedException | BrokenBarrierException e) {
        throw new RuntimeException(e);
    }
}
 
Example #16
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: FixedLengthInputStream.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    InputStream is = t.getRequestBody();
    byte[] ba = new byte[BUFFER_SIZE];
    int read;
    long count = 0L;
    while((read = is.read(ba)) != -1) {
        count += read;
    }
    is.close();

    check(count == expected, "Expected: " + expected + ", received "
            + count);

    debug("Received " + count + " bytes");

    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example #17
Source Project: incubator-heron   Author: apache   File: KillRequestHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {

  // read the http request payload
  byte[] requestBody = NetworkUtils.readHttpRequestBody(exchange);

  // prepare the kill topology request
  Scheduler.KillTopologyRequest killTopologyRequest =
      Scheduler.KillTopologyRequest.newBuilder()
          .mergeFrom(requestBody)
          .build();

  if (!scheduler.onKill(killTopologyRequest)) {
    throw new RuntimeException("Failed to process killTopologyRequest");
  } else {
    throw new TerminateSchedulerException(
        "Kill request handled successfully - terminating scheduler");
  }
}
 
Example #18
Source Project: jdk8u-jdk   Author: lambdalab-mirror   File: B4769350.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    switch(count) {
        case 0:
            AuthenticationHandler.proxyReply(exchange,
                    "Basic realm=\"proxy\"");
            break;
        case 1:
            t3cond1.countDown();
            AuthenticationHandler.errorReply(exchange,
                    "Basic realm=\"realm4\"");
            break;
        case 2:
            AuthenticationHandler.okReply(exchange);
            break;
        default:
            System.out.println ("Unexpected request");
    }
}
 
Example #19
Source Project: JavaTutorial   Author: aofeng   File: AbstractHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 处理请求头。
 */
public void handleHeader(HttpExchange httpEx) {
    InetSocketAddress remoteAddress = httpEx.getRemoteAddress();
    _logger.info("收到来自"+remoteAddress.getAddress().getHostAddress()+":"+remoteAddress.getPort()+"的请求");
    
    URI rUri = httpEx.getRequestURI();
    _logger.info("请求地址:"+rUri.toString());
    
    String method = httpEx.getRequestMethod();
    _logger.info("请求方法:"+method);
    
    Headers headers = httpEx.getRequestHeaders();
    Set<Entry<String, List<String>>> headerSet = headers.entrySet();
    _logger.info("请求头:");
    for (Entry<String, List<String>> header : headerSet) {
        _logger.info(header.getKey()+":"+header.getValue());
    }
}
 
Example #20
Source Project: freehealth-connector   Author: taktik   File: AuthFilter.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public void doFilter(HttpExchange t, Chain chain) throws IOException {
   if (this.authenticator != null) {
      Result r = this.authenticator.authenticate(t);
      if (r instanceof Success) {
         Success s = (Success)r;
         ExchangeImpl e = ExchangeImpl.get(t);
         e.setPrincipal(s.getPrincipal());
         chain.doFilter(t);
      } else if (r instanceof Retry) {
         Retry ry = (Retry)r;
         this.consumeInput(t);
         t.sendResponseHeaders(ry.getResponseCode(), -1L);
      } else if (r instanceof Failure) {
         Failure f = (Failure)r;
         this.consumeInput(t);
         t.sendResponseHeaders(f.getResponseCode(), -1L);
      }
   } else {
      chain.doFilter(t);
   }

}
 
Example #21
@Override
public void handle(HttpExchange httpExchange) throws IOException {
    Headers headers = httpExchange.getResponseHeaders();
    headers.add("Content-Type", "text/xml");

    //response payload
    String response = "<a></b>";

    httpExchange.sendResponseHeaders(200, response.length());
    OutputStream responseStream = httpExchange.getResponseBody();
    try {
        responseStream.write(response.getBytes(Charset.defaultCharset()));
    } finally {
        responseStream.close();
    }
}
 
Example #22
Source Project: micro-integrator   Author: wso2   File: HTTPResponseCodeTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public void handle(HttpExchange httpExchange) throws IOException {
    Headers headers = httpExchange.getResponseHeaders();
    headers.add("Content-Type", "text/xml");
    String response = "This is Response status code test case";
    httpExchange.sendResponseHeaders(responseCode, response.length());
    OutputStream os = httpExchange.getResponseBody();
    os.write(response.getBytes());
    os.close();
}
 
Example #23
Source Project: jdk8u_jdk   Author: JetBrains   File: B4769350.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    if (count == 1) {
        t2condlatch.countDown();
    }
    AuthenticationHandler.errorReply(exchange,
            "Basic realm=\"realm3\"");

}
 
Example #24
Source Project: java-technology-stack   Author: codeEngraver   File: SimpleHttpInvokerServiceExporter.java    License: MIT License 5 votes vote down vote up
/**
 * Reads a remote invocation from the request, executes it,
 * and writes the remote invocation result to the response.
 * @see #readRemoteInvocation(HttpExchange)
 * @see #invokeAndCreateResult(RemoteInvocation, Object)
 * @see #writeRemoteInvocationResult(HttpExchange, RemoteInvocationResult)
 */
@Override
public void handle(HttpExchange exchange) throws IOException {
	try {
		RemoteInvocation invocation = readRemoteInvocation(exchange);
		RemoteInvocationResult result = invokeAndCreateResult(invocation, getProxy());
		writeRemoteInvocationResult(exchange, result);
		exchange.close();
	}
	catch (ClassNotFoundException ex) {
		exchange.sendResponseHeaders(500, -1);
		logger.error("Class not found during deserialization", ex);
	}
}
 
Example #25
Source Project: cloudstack   Author: apache   File: ConsoleProxyAjaxHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void handleClientKickoff(HttpExchange t, ConsoleProxyClient viewer) throws IOException {
    String response = viewer.onAjaxClientKickoff();
    t.sendResponseHeaders(200, response.length());
    OutputStream os = t.getResponseBody();
    try {
        os.write(response.getBytes());
    } finally {
        os.close();
    }
}
 
Example #26
Source Project: Quelea   Author: quelea-projection   File: RemoteControlServer.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void handle(HttpExchange he) throws IOException {
    if (RCHandler.isLoggedOn(he.getRemoteAddress().getAddress().toString())) {
        final String response;
        response = RCHandler.songDisplay(he);
        he.getResponseHeaders().add("Cache-Control", "no-cache, no-store, must-revalidate");
        he.sendResponseHeaders(200, response.getBytes(Charset.forName("UTF-8")).length);
        try (OutputStream os = he.getResponseBody()) {
            os.write(response.getBytes(Charset.forName("UTF-8")));
        }
    } else {
        passwordPage(he);
    }
}
 
Example #27
Source Project: java-pilosa   Author: pilosa   File: PilosaClientIT.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void handle(HttpExchange r) throws IOException {
    String response = "{\"state\":\"NORMAL\",\"nodes\":[{\"isCoordinator\":true, \"id\":\"0f5c2ffc-1244-47d0-a83d-f5a25abba9bc\",\"uri\":{\"scheme\":\"http\",\"host\":\"nonexistent\",\"port\":4444}}],\"localID\":\"0f5c2ffc-1244-47d0-a83d-f5a25abba9bc\"}";
    r.sendResponseHeaders(200, response.getBytes().length);
    try (OutputStream os = r.getResponseBody()) {
        os.write(response.getBytes());
    }
    r.close();
}
 
Example #28
Source Project: jdk8u-dev-jdk   Author: frohoff   File: B4769350.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    switch(count) {
        case 0:
            AuthenticationHandler.errorReply(exchange,
                    "Basic realm=\"realm3\"");
            break;
        case 1:
            AuthenticationHandler.okReply(exchange);
            break;
        default:
            System.out.println ("Unexpected request");
    }
}
 
Example #29
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: B4769350.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void errorReply(HttpExchange exchange, String reply)
        throws IOException
{
    exchange.getResponseHeaders().add("Connection", "close");
    exchange.getResponseHeaders().add("WWW-Authenticate", reply);
    exchange.sendResponseHeaders(401, 0);
    exchange.close();
}
 
Example #30
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: HttpsSocketFacTest.java    License: 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();
}