com.sun.net.httpserver.HttpExchange Java Examples

The following examples show how to use com.sun.net.httpserver.HttpExchange. 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: FixedLengthInputStream.java    From openjdk-jdk8u-backup with 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 #2
Source File: AuthFilter.java    From freehealth-connector with 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 #3
Source File: B4769350.java    From openjdk-8-source with 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 #4
Source File: TestRemoteActors.java    From Fibry with 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 #5
Source File: AbstractHandler.java    From JavaTutorial with 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 #6
Source File: TestFaultSequenceExecutionForMalformedResponse.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: SimpleHessianServiceExporter.java    From spring-analysis-note with 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 #8
Source File: B4769350.java    From jdk8u-jdk with 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 #9
Source File: KillRequestHandler.java    From incubator-heron with 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 #10
Source File: MetricsCacheManagerHttpServer.java    From incubator-heron with 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 #11
Source File: B4769350.java    From openjdk-jdk8u with 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 #12
Source File: B4769350.java    From openjdk-8-source with 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 #13
Source File: ChunkedEncodingTest.java    From dragonwell8_jdk with 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 #14
Source File: B4769350.java    From dragonwell8_jdk with 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 #15
Source File: B4769350.java    From jdk8u60 with 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 #16
Source File: AttestationServer.java    From AttestationServer with 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 #17
Source File: Httpserver.java    From jstorm with 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 #18
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())) {
        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 #19
Source File: RCHandler.java    From Quelea with 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 #20
Source File: PushHandler.java    From alloc with 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 #21
Source File: RCHandler.java    From Quelea with 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 #22
Source File: ClassLoad.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
     boolean error = true;

     // Start a dummy server to return 404
     HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
     HttpHandler handler = new HttpHandler() {
         public void handle(HttpExchange t) throws IOException {
             InputStream is = t.getRequestBody();
             while (is.read() != -1);
             t.sendResponseHeaders (404, -1);
             t.close();
         }
     };
     server.createContext("/", handler);
     server.start();

     // Client request
     try {
         URL url = new URL("http://localhost:" + server.getAddress().getPort());
         String name = args.length >= 2 ? args[1] : "foo.bar.Baz";
         ClassLoader loader = new URLClassLoader(new URL[] { url });
         System.out.println(url);
         Class c = loader.loadClass(name);
         System.out.println("Loaded class \"" + c.getName() + "\".");
     } catch (ClassNotFoundException ex) {
         System.out.println(ex);
         error = false;
     } finally {
         server.stop(0);
     }
     if (error)
         throw new RuntimeException("No ClassNotFoundException generated");
}
 
Example #23
Source File: SimpleHttpWebServer.java    From vsphere-automation-sdk-java with MIT License 5 votes vote down vote up
/**
    * This method send response code and state value back to the client.
    *
    * @param httpExchange {@link HttpExchange}
    * @param response
    */
protected void writeResponse(HttpExchange httpExchange, String response) throws IOException {
       httpExchange.sendResponseHeaders(200, response.length());
       OutputStream os = httpExchange.getResponseBody();
       os.write(response.getBytes());
       os.close();
   }
 
Example #24
Source File: Basic.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    InputStream is = t.getRequestBody();
    Headers map = t.getRequestHeaders();
    Headers rmap = t.getResponseHeaders();
    URI uri = t.getRequestURI();

    debug("Server: received request for " + uri);
    String path = uri.getPath();
    if (path.endsWith("a.jar"))
        aDotJar++;
    else if (path.endsWith("b.jar"))
        bDotJar++;
    else if (path.endsWith("c.jar"))
        cDotJar++;
    else
        System.out.println("Unexpected resource request" + path);

    while (is.read() != -1);
    is.close();

    File file = new File(docsDir, path);
    if (!file.exists())
        throw new RuntimeException("Error: request for " + file);
    long clen = file.length();
    t.sendResponseHeaders (200, clen);
    OutputStream os = t.getResponseBody();
    FileInputStream fis = new FileInputStream(file);
    try {
        byte[] buf = new byte [16 * 1024];
        int len;
        while ((len=fis.read(buf)) != -1) {
            os.write (buf, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    fis.close();
    os.close();
}
 
Example #25
Source File: HttpStreams.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 {
    try (InputStream is = t.getRequestBody()) {
        while (is.read() != -1);
    }
    t.sendResponseHeaders(respCode(), length());
    try (OutputStream os = t.getResponseBody()) {
        os.write(message());
    }
    t.close();
}
 
Example #26
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 {
    String statString = formatter.toHtmlString();

    t.sendResponseHeaders(200, statString.getBytes(Constant.CHARSET).length);
    OutputStream os = t.getResponseBody();
    os.write(statString.getBytes(Constant.CHARSET));
    os.close();
}
 
Example #27
Source File: B4769350.java    From jdk8u_jdk with 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=\"realm1\"");
            break;
        case 1:
            AuthenticationHandler.okReply(exchange);
            break;
        default:
            System.out.println ("Unexpected request");
    }
}
 
Example #28
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 #29
Source File: RCHandler.java    From Quelea with GNU General Public License v3.0 5 votes vote down vote up
public static String setTheme(HttpExchange he) throws UnsupportedEncodingException {
    String themeName;
    if (he.getRequestURI().toString().contains("/settheme/")) {
        final MainPanel p = QueleaApp.get().getMainWindow().getMainPanel();
        String uri = URLDecoder.decode(he.getRequestURI().toString(), "UTF-8");
        themeName = uri.split("/settheme/", 2)[1];
        ScheduleThemeNode stn = QueleaApp.get().getMainWindow().getMainPanel().getSchedulePanel().getThemeNode();

        Utils.fxRunAndWait(() -> {
            int i = 0;
            for (ThemeDTO t : ThemeUtils.getThemes()) {
                i++;
                if (t.getThemeName().equals(themeName)) {
                    stn.selectSongTheme(t);
                    stn.selectBibleTheme(t);
                    break;
                } else if (i == ThemeUtils.getThemes().size()) {
                    stn.selectSongTheme(ThemeDTO.DEFAULT_THEME);
                    stn.selectBibleTheme(ThemeDTO.DEFAULT_THEME);
                }
            }
        });

        return "";
    }
    return "";
}
 
Example #30
Source File: AttestationServer.java    From AttestationServer with MIT License 5 votes vote down vote up
@Override
public void handlePost(final HttpExchange exchange) throws IOException, SQLiteException {
    final String requestToken;
    final String fingerprint;
    try (final JsonReader reader = Json.createReader(exchange.getRequestBody())) {
        final JsonObject object = reader.readObject();
        requestToken = object.getString("requestToken");
        fingerprint = object.getString("fingerprint");
    } catch (final ClassCastException | JsonException | NullPointerException e) {
        e.printStackTrace();
        exchange.sendResponseHeaders(400, -1);
        return;
    }

    final Account account = verifySession(exchange, false, requestToken.getBytes(StandardCharsets.UTF_8));
    if (account == null) {
        return;
    }

    final SQLiteConnection conn = new SQLiteConnection(AttestationProtocol.ATTESTATION_DATABASE);
    try {
        open(conn, false);

        final SQLiteStatement update = conn.prepare("UPDATE Devices SET " +
                "deletionTime = ? WHERE userId = ? AND hex(fingerprint) = ?");
        update.bind(1, System.currentTimeMillis());
        update.bind(2, account.userId);
        update.bind(3, fingerprint);
        update.step();
        update.dispose();

        if (conn.getChanges() == 0) {
            exchange.sendResponseHeaders(400, -1);
            return;
        }
    } finally {
        conn.dispose();
    }
    exchange.sendResponseHeaders(200, -1);
}