com.sun.net.httpserver.HttpHandler Java Examples

The following examples show how to use com.sun.net.httpserver.HttpHandler. 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: TestKubeService.java    From singer with Apache License 2.0 7 votes vote down vote up
public void registerBadJsonResponse() {
    server.createContext("/pods", new HttpHandler() {

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            try {
                String response = new String(
                        Files.readAllBytes(new File("src/test/resources/pods-badresponse.json").toPath()), "utf-8");
                exchange.getResponseHeaders().add("Content-Type", "text/html");
                exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length());
                IOUtils.write(response, exchange.getResponseBody());
                exchange.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw e;
            }
        }
    });
}
 
Example #2
Source File: MockServer.java    From r2cloud with Apache License 2.0 6 votes vote down vote up
public void mockResponse(String url, String data) {
	server.createContext(url, new HttpHandler() {

		@Override
		public void handle(HttpExchange exchange) throws IOException {
			if (data == null) {
				exchange.sendResponseHeaders(404, 0);
				return;
			}
			exchange.sendResponseHeaders(200, data.length());
			OutputStream os = exchange.getResponseBody();
			os.write(data.getBytes(StandardCharsets.UTF_8));
			os.close();
		}
	});
}
 
Example #3
Source File: HttpContextImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
HttpContextImpl(String protocol, String path, HttpHandler cb, ServerImpl server) {
   if (path != null && protocol != null && path.length() >= 1 && path.charAt(0) == '/') {
      this.protocol = protocol.toLowerCase();
      this.path = path;
      if (!this.protocol.equals("http") && !this.protocol.equals("https")) {
         throw new IllegalArgumentException("Illegal value for protocol");
      } else {
         this.handler = cb;
         this.server = server;
         this.authfilter = new AuthFilter((Authenticator)null);
         this.sfilters.add(this.authfilter);
      }
   } else {
      throw new IllegalArgumentException("Illegal value for path or protocol");
   }
}
 
Example #4
Source File: HTTPTestServer.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static HTTPTestServer createServer(HttpProtocolType protocol,
                                    HttpAuthType authType,
                                    HttpTestAuthenticator auth,
                                    HttpSchemeType schemeType,
                                    HttpHandler delegate,
                                    String path)
        throws IOException {
    Objects.requireNonNull(authType);
    Objects.requireNonNull(auth);

    HttpServer impl = createHttpServer(protocol);
    final HTTPTestServer server = new HTTPTestServer(impl, null, delegate);
    final HttpHandler hh = server.createHandler(schemeType, auth, authType);
    HttpContext ctxt = impl.createContext(path, hh);
    server.configureAuthentication(ctxt, schemeType, auth, authType);
    impl.start();
    return server;
}
 
Example #5
Source File: RtlSdrDataServer.java    From r2cloud with Apache License 2.0 6 votes vote down vote up
public void start() throws IOException {
	server = HttpServer.create(new InetSocketAddress("localhost", 8002), 0);
	server.start();
	server.createContext("/", new HttpHandler() {

		@Override
		public void handle(HttpExchange exchange) throws IOException {
			if (filename == null) {
				return;
			}
			exchange.getResponseHeaders().add("Content-Type", "application/octet-stream");
			try (GZIPInputStream is = new GZIPInputStream(RtlSdrDataServer.class.getResourceAsStream(filename))) {
				exchange.sendResponseHeaders(200, 0);
				try (OutputStream os = exchange.getResponseBody();) {
					Util.copy(is, os);
				}
			}
		}
	});
}
 
Example #6
Source File: ActionHttp_PDI208_Test.java    From hop with Apache License 2.0 6 votes vote down vote up
private static void startHttpServer() throws IOException {
  httpServer = HttpServer.create( new InetSocketAddress( ActionHttp_PDI208_Test.HTTP_HOST, ActionHttp_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 #7
Source File: HashemAddHandlerBuiltin.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@TruffleBoundary
public String doAddHandler(HashemWebServer server, HashemBebin source, HashemContext context, IndirectCallNode callNode) {
    server.getValue().createContext("/", new HttpHandler() {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            try {
                DynamicObject answer = (DynamicObject) callNode.call(source.getCallTarget());
                int rCode = ((Long) answer.get("status", 200)).intValue();
                String body = (String) answer.get("body", "");
                byte[] response = body.getBytes();
                exchange.sendResponseHeaders(rCode, response.length);
                exchange.getResponseBody().write(response);
                exchange.getResponseBody().close();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    });
    return "";
}
 
Example #8
Source File: MetricsHttpServer.java    From dts with Apache License 2.0 6 votes vote down vote up
public MetricsHttpServer(InetSocketAddress addr, CollectorRegistry registry, boolean daemon) throws IOException {
    server = HttpServer.create();
    server.bind(addr, 3);
    HttpHandler mHandler = new HTTPMetricHandler(registry);
    server.createContext("/prometheus", mHandler);
    server.createContext("/health", new HealthHandler());
    server.createContext("/info", new InfoHandler());
    executorService = Executors.newFixedThreadPool(5, DaemonThreadFactory.defaultThreadFactory(daemon));
    server.setExecutor(executorService);
    start(daemon);
}
 
Example #9
Source File: OreKitDataClientTest.java    From r2cloud with Apache License 2.0 6 votes vote down vote up
@Test(expected = IOException.class)
public void testInvalidContent() throws Exception {
	server.createContext("/file.zip", new HttpHandler() {

		@Override
		public void handle(HttpExchange exchange) throws IOException {
			byte[] errorBody = UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8);
			exchange.getResponseHeaders().add("Content-Type", "text/plain");
			exchange.sendResponseHeaders(200, errorBody.length);
			OutputStream os = exchange.getResponseBody();
			os.write(errorBody);
			os.close();
		}
	});
	OreKitDataClient client = new OreKitDataClient(urls(validZipFile));
	client.downloadAndSaveTo(dataFolder);
}
 
Example #10
Source File: TestKubeService.java    From singer with Apache License 2.0 6 votes vote down vote up
public void registerGoodResponse() {
    server.createContext("/pods", new HttpHandler() {

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            try {
                String response = new String(
                        Files.readAllBytes(new File("src/test/resources/pods-goodresponse.json").toPath()),
                        "utf-8");
                exchange.getResponseHeaders().add("Content-Type", "text/html");
                exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length());
                IOUtils.write(response, exchange.getResponseBody());
                exchange.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw e;
            }
        }
    });
}
 
Example #11
Source File: HttpContextImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
HttpContextImpl(String protocol, String path, HttpHandler cb, ServerImpl server) {
   if (path != null && protocol != null && path.length() >= 1 && path.charAt(0) == '/') {
      this.protocol = protocol.toLowerCase();
      this.path = path;
      if (!this.protocol.equals("http") && !this.protocol.equals("https")) {
         throw new IllegalArgumentException("Illegal value for protocol");
      } else {
         this.handler = cb;
         this.server = server;
         this.authfilter = new AuthFilter((Authenticator)null);
         this.sfilters.add(this.authfilter);
      }
   } else {
      throw new IllegalArgumentException("Illegal value for path or protocol");
   }
}
 
Example #12
Source File: OreKitDataClientTest.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
private void setupZipFile(String path, String data) {
	server.createContext("/file.zip", new HttpHandler() {

		@Override
		public void handle(HttpExchange exchange) throws IOException {
			byte[] zip = createZip(path, data);
			exchange.getResponseHeaders().add("Content-Type", "application/zip");
			exchange.sendResponseHeaders(200, zip.length);
			OutputStream os = exchange.getResponseBody();
			os.write(zip);
			os.close();
		}
	});
}
 
Example #13
Source File: ClassLoad.java    From openjdk-jdk8u-backup 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 #14
Source File: Daemon.java    From validator with Apache License 2.0 5 votes vote down vote up
private HttpHandler createRootHandler(Configuration config) {
    HttpHandler rootHandler;
    final DefaultCheck check = new DefaultCheck(config);
    final CheckHandler checkHandler = new CheckHandler(check, config.getContentRepository().getProcessor());
    if (guiEnabled) {
        GuiHandler gui = new GuiHandler();
        rootHandler = new RoutingHandler(checkHandler, gui);
    } else {
        rootHandler = checkHandler;
    }
    return rootHandler;
}
 
Example #15
Source File: WebserviceController.java    From james with Apache License 2.0 5 votes vote down vote up
private Map<String, HttpHandler> createHandlers(InformationPointService informationPointService,
                                                ClassScanner classScanner,
                                                ScriptEngine scriptEngine,
                                                EventPublisher eventPublisher,
                                                QueueBacked jamesObjectiveQueue,
                                                QueueBacked newClassesQueue,
                                                QueueBacked newInformationPointQueue,
                                                QueueBacked removeInformationPointQueue) {
    HashMap<String, HttpHandler> handlers = new HashMap<>();
    handlers.put("/v1/information-point", new InformationPointHandler(informationPointService));
    handlers.put("/v1/queue", new QueueHandler(scriptEngine, eventPublisher, jamesObjectiveQueue, newClassesQueue, newInformationPointQueue, removeInformationPointQueue));
    handlers.put("/v1/class-scanner/", new ClassScannerHandler(classScanner));
    return handlers;
}
 
Example #16
Source File: ChunkedEncodingTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Http Server
 */
static HttpServer startHttpServer() throws IOException {
    HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0);
    HttpHandler httpHandler = new SimpleHandler();
    httpServer.createContext("/chunked/", httpHandler);
    httpServer.start();
    return httpServer;
}
 
Example #17
Source File: HttpMockServer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * add mock
 *
 * @return
 */
public boolean addMockPath(String path, final String responseJson) {
    httpServer.createContext(path, new HttpHandler() {
        public void handle(HttpExchange exchange) throws IOException {
            byte[] response = responseJson.getBytes();
            exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
            exchange.getResponseBody().write(response);
            exchange.close();
        }
    });

    return true;

}
 
Example #18
Source File: SimpleHttpServer.java    From deployment-examples with MIT License 5 votes vote down vote up
/**
 * Instantiates a new simple http server.
 *
 * @param port the port
 * @param context the context
 * @param handler the handler
 */
public SimpleHttpServer(int port, String context, HttpHandler handler) {
    try {
        //Create HttpServer which is listening on the given port
        httpServer = HttpServer.create(new InetSocketAddress(port), 0);
        //Create a new context for the given context and handler
        httpServer.createContext(context, handler);
        //Create a default executor
        httpServer.setExecutor(null);
    } catch (IOException e) {
        e.printStackTrace();
    }

}
 
Example #19
Source File: MissingTrailingSpace.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    try {
        server.setExecutor(Executors.newFixedThreadPool(1));
        server.createContext(someContext, new HttpHandler() {
            @Override
            public void handle(HttpExchange msg) {
                try {
                    try {
                        msg.sendResponseHeaders(noMsgCode, -1);
                    } catch(IOException ioe) {
                        ioe.printStackTrace();
                    }
                } finally {
                    msg.close();
                }
            }
        });
        server.start();
        System.out.println("Server started at port "
                           + server.getAddress().getPort());

        runRawSocketHttpClient("localhost", server.getAddress().getPort());
    } finally {
        ((ExecutorService)server.getExecutor()).shutdown();
        server.stop(0);
    }
    System.out.println("Server finished.");
}
 
Example #20
Source File: HTTPServer.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Start a HTTP server serving Prometheus metrics from the given registry using the given {@link HttpServer}.
 * The {@code httpServer} is expected to already be bound to an address
 */
public HTTPServer(HttpServer httpServer, CollectorRegistry registry, boolean daemon) throws IOException {
    if (httpServer.getAddress() == null)
        throw new IllegalArgumentException("HttpServer hasn't been bound to an address");

    server = httpServer;
    HttpHandler mHandler = new HTTPMetricHandler(registry);
    server.createContext("/", mHandler);
    server.createContext("/metrics", mHandler);
    server.createContext("/-/healthy", mHandler);
    executorService = Executors.newFixedThreadPool(3, NamedDaemonThreadFactory.defaultThreadFactory(daemon));
    server.setExecutor(executorService);
    start(daemon);
}
 
Example #21
Source File: PrometheusRegistry.java    From sofa-lookout with Apache License 2.0 5 votes vote down vote up
public PrometheusRegistry(Clock clock, MetricConfig config) {
    super(clock, config);
    int serverPort = config.getInt(LOOKOUT_PROMETHEUS_EXPORTER_SERVER_PORT,
        DEFAULT_PROMETHEUS_EXPORTER_SERVER_PORT);
    String appName = config.getString(APP_NAME);
    if (StringUtils.isNotEmpty(appName)) {
        setCommonTag("app", appName);
    }
    exporterServer = new ExporterServer(serverPort);
    exporterServer.addMetricsQueryHandler(new HttpHandler() {
        @Override
        public void handle(HttpExchange httpExchange) throws IOException {
            String promText = "";
            try {
                promText = getMetricsSnapshot(PrometheusRegistry.this.iterator());
                byte[] respContents = promText.getBytes("UTF-8");
                httpExchange.sendResponseHeaders(200, respContents.length);
                httpExchange.getResponseHeaders().add("Content-Type",
                    "text/plain; charset=UTF-8");
                httpExchange.getResponseBody().write(respContents);
                httpExchange.close();
            } finally {
                logger.debug("{} scrapes prometheus metrics:\n{}", httpExchange
                    .getRemoteAddress().getAddress(), promText);
            }
        }
    });
    exporterServer.start();
    logger.info("lookout client exporter is started. server port:{}", serverPort);
}
 
Example #22
Source File: ExporterServer.java    From sofa-lookout with Apache License 2.0 5 votes vote down vote up
public void start() {
    httpServer.createContext("/", new HttpHandler() {
        @Override
        public void handle(HttpExchange httpExchange) throws IOException {
            byte[] respContents = ("<html><head><title>Lookout Client Exporter</title></head><body><h1>Lookout "
                                   + "Client Exporter</h1><p><a href=\"/metrics\">Metrics</a></p></body></html>")
                .getBytes("UTF-8");
            httpExchange.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8");
            httpExchange.sendResponseHeaders(200, respContents.length);
            httpExchange.getResponseBody().write(respContents);
            httpExchange.close();
        }
    });
    httpServer.start();
}
 
Example #23
Source File: bug4714674.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create and start the HTTP server.
 */
public DeafServer() throws IOException {
    InetSocketAddress addr = new InetSocketAddress(0);
    server = HttpServer.create(addr, 0);
    HttpHandler handler = new DeafHandler();
    server.createContext("/", handler);
    server.setExecutor(Executors.newCachedThreadPool());
    server.start();
}
 
Example #24
Source File: MissingTrailingSpace.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    try {
        server.setExecutor(Executors.newFixedThreadPool(1));
        server.createContext(someContext, new HttpHandler() {
            @Override
            public void handle(HttpExchange msg) {
                try {
                    try {
                        msg.sendResponseHeaders(noMsgCode, -1);
                    } catch(IOException ioe) {
                        ioe.printStackTrace();
                    }
                } finally {
                    msg.close();
                }
            }
        });
        server.start();
        System.out.println("Server started at port "
                           + server.getAddress().getPort());

        runRawSocketHttpClient("localhost", server.getAddress().getPort());
    } finally {
        ((ExecutorService)server.getExecutor()).shutdown();
        server.stop(0);
    }
    System.out.println("Server finished.");
}
 
Example #25
Source File: ChunkedEncodingTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Http Server
 */
static HttpServer startHttpServer() throws IOException {
    HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0);
    HttpHandler httpHandler = new SimpleHandler();
    httpServer.createContext("/chunked/", httpHandler);
    httpServer.start();
    return httpServer;
}
 
Example #26
Source File: bug4714674.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create and start the HTTP server.
 */
public DeafServer() throws IOException {
    InetSocketAddress addr = new InetSocketAddress(0);
    server = HttpServer.create(addr, 0);
    HttpHandler handler = new DeafHandler();
    server.createContext("/", handler);
    server.setExecutor(Executors.newCachedThreadPool());
    server.start();
}
 
Example #27
Source File: HTTPTestServer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static HTTPTestServer create(HttpProtocolType protocol,
                                    HttpAuthType authType,
                                    HttpTestAuthenticator auth,
                                    HttpSchemeType schemeType,
                                    HttpHandler delegate)
        throws IOException {
    Objects.requireNonNull(authType);
    Objects.requireNonNull(auth);
    switch(authType) {
        // A server that performs Server Digest authentication.
        case SERVER: return createServer(protocol, authType, auth,
                                         schemeType, delegate, "/");
        // A server that pretends to be a Proxy and performs
        // Proxy Digest authentication. If protocol is HTTPS,
        // then this will create a HttpsProxyTunnel that will
        // handle the CONNECT request for tunneling.
        case PROXY: return createProxy(protocol, authType, auth,
                                       schemeType, delegate, "/");
        // A server that sends 307 redirect to a server that performs
        // Digest authentication.
        // Note: 301 doesn't work here because it transforms POST into GET.
        case SERVER307: return createServerAndRedirect(protocol,
                                                    HttpAuthType.SERVER,
                                                    auth, schemeType,
                                                    delegate, 307);
        // A server that sends 305 redirect to a proxy that performs
        // Digest authentication.
        case PROXY305:  return createServerAndRedirect(protocol,
                                                    HttpAuthType.PROXY,
                                                    auth, schemeType,
                                                    delegate, 305);
        default:
            throw new InternalError("Unknown server type: " + authType);
    }
}
 
Example #28
Source File: ServerImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public synchronized HttpContextImpl createContext(String path) {
   if (path == null) {
      throw new NullPointerException("null path parameter");
   } else {
      HttpContextImpl context = new HttpContextImpl(this.protocol, path, (HttpHandler)null, this);
      this.contexts.add(context);
      this.logger.config("context created: " + path);
      return context;
   }
}
 
Example #29
Source File: ServerImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public synchronized HttpContextImpl createContext(String path, HttpHandler handler) {
   if (handler != null && path != null) {
      HttpContextImpl context = new HttpContextImpl(this.protocol, path, handler, this);
      this.contexts.add(context);
      this.logger.config("context created: " + path);
      return context;
   } else {
      throw new NullPointerException("null handler, or path parameter");
   }
}
 
Example #30
Source File: HttpContextImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public void setHandler(HttpHandler h) {
   if (h == null) {
      throw new NullPointerException("Null handler parameter");
   } else if (this.handler != null) {
      throw new IllegalArgumentException("handler already set");
   } else {
      this.handler = h;
   }
}