com.sun.net.httpserver.HttpServer Java Examples
The following examples show how to use
com.sun.net.httpserver.HttpServer.
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: XMLFieldConfigHelperTest.java From datawave with Apache License 2.0 | 6 votes |
private HttpServer createFileServer(String path, int port) throws Exception { final String resp = readFile(path); HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); server.setExecutor(null); server.createContext("/", e -> { e.sendResponseHeaders(200, 0); e.getResponseHeaders().set("Content-Type", "text/xml"); OutputStream responseBody = e.getResponseBody(); responseBody.write(resp.getBytes()); responseBody.close(); }); return server; }
Example #2
Source File: TestClusterManager.java From rubix with Apache License 2.0 | 6 votes |
@Test /* * Tests that in a cluster with failed node, failed node is not returned */ public void testFailedNodeCluster() throws IOException { HttpServer server = createServer("/v1/node", new MultipleWorkers(), "/v1/node/failed", new OneFailedNode()); log.info("STARTED SERVER"); ClusterManager clusterManager = getPrestoClusterManager(); List<String> nodes = clusterManager.getNodes(); log.info("Got nodes: " + nodes); assertTrue(nodes.size() == 1, "Should only have two nodes"); assertTrue(nodes.get(0).equals("192.168.2.252"), "Wrong nodes data"); server.stop(0); }
Example #3
Source File: LocalServerReceiver.java From google-oauth-java-client with Apache License 2.0 | 6 votes |
@Override public String getRedirectUri() throws IOException { server = HttpServer.create(new InetSocketAddress(port != -1 ? port : findOpenPort()), 0); HttpContext context = server.createContext(callbackPath, new CallbackHandler()); server.setExecutor(null); try { server.start(); port = server.getAddress().getPort(); } catch (Exception e) { Throwables.propagateIfPossible(e); throw new IOException(e); } return "http://" + this.getHost() + ":" + port + callbackPath; }
Example #4
Source File: ContextInstanceDataAutoConfigurationTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@Test void placeHolder_noExplicitConfiguration_missingInstanceDataResolverForNotAwsEnvironment() throws Exception { // Arrange HttpServer httpServer = MetaDataServer.setupHttpServer(); HttpContext instanceIdHttpContext = httpServer.createContext( "/latest/meta-data/instance-id", new MetaDataServer.HttpResponseWriterHandler(null)); this.context = new AnnotationConfigApplicationContext(); this.context.register(ContextInstanceDataAutoConfiguration.class); // Act this.context.refresh(); // Assert assertThat(this.context .containsBean("AmazonEc2InstanceDataPropertySourcePostProcessor")) .isFalse(); httpServer.removeContext(instanceIdHttpContext); }
Example #5
Source File: NoCache.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws IOException { ResponseCache.setDefault(new ThrowingCache()); HttpServer server = startHttpServer(); try { URL url = new URL("http://" + InetAddress.getLocalHost().getHostAddress() + ":" + server.getAddress().getPort() + "/NoCache/"); URLConnection uc = url.openConnection(); uc.setUseCaches(false); uc.getInputStream().close(); } finally { server.stop(0); // clear the system-wide cache handler, samevm/agentvm mode ResponseCache.setDefault(null); } }
Example #6
Source File: TestHelper.java From ant-ivy with Apache License 2.0 | 6 votes |
/** * Creates a HTTP server, backed by a local file system, which can be used as a repository to * serve Ivy module descriptors and artifacts. * NOTE: This is supposed to be used only in test cases and only a limited functionality is * added in the handler(s) backing the server * * @param serverAddress The address to which the server will be bound * @param webAppContext The context root of the application which will be handling * the requests to the server * @param localFilesystemRepoRoot The path to the root directory containing the module * descriptors and artifacts * @return AutoCloseable * @throws IOException if something goes wrong */ public static AutoCloseable createHttpServerBackedRepository(final InetSocketAddress serverAddress, final String webAppContext, final Path localFilesystemRepoRoot) throws IOException { final LocalFileRepoOverHttp handler = new LocalFileRepoOverHttp(webAppContext, localFilesystemRepoRoot); final HttpServer server = HttpServer.create(serverAddress, -1); // setup the handler server.createContext(webAppContext, handler); // start the server server.start(); return new AutoCloseable() { @Override public void close() throws Exception { final int delaySeconds = 0; server.stop(delaySeconds); } }; }
Example #7
Source File: NoCache.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws IOException { ResponseCache.setDefault(new ThrowingCache()); HttpServer server = startHttpServer(); try { URL url = new URL("http://" + InetAddress.getLocalHost().getHostAddress() + ":" + server.getAddress().getPort() + "/NoCache/"); URLConnection uc = url.openConnection(); uc.setUseCaches(false); uc.getInputStream().close(); } finally { server.stop(0); // clear the system-wide cache handler, samevm/agentvm mode ResponseCache.setDefault(null); } }
Example #8
Source File: Main.java From java-docs-samples with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws IOException { // Create an instance of HttpServer bound to port defined by the // PORT environment variable when present, otherwise on 8080. int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8080")); HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); // Set root URI path. server.createContext("/", (var t) -> { byte[] response = "Hello World from Google App Engine Java 11.".getBytes(); t.sendResponseHeaders(200, response.length); try (OutputStream os = t.getResponseBody()) { os.write(response); } }); // Start the server. server.start(); }
Example #9
Source File: FunctionServer.java From jerverless with MIT License | 6 votes |
public FunctionServer(AppConfig appConfig) { try { this.appConfig = appConfig; middlewareProcessor = new MiddlewareProcessor(this.appConfig); serverInstance = HttpServer.create(new InetSocketAddress(this.appConfig.getPort()), 0); serverInstance.setExecutor(Executors.newCachedThreadPool()); // unlimited thread pool! warn TODO : replace with fixed consoleInstance = ServerConsole.getInstance(this); inputMapperProcessor = InputMapperProcessor.getInstance(this); outputMapperProcessor = OutputMapperProcessor.getInstance(this); for (Route route : appConfig.getRoutes()) { serverInstance.createContext(route.getEndpoint(), new FunctionHandler(middlewareProcessor, route)); } } catch (IOException ex) { Logger.getLogger(FunctionServer.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(FunctionServer.class.getName()).log(Level.SEVERE, "jerverless can't bind in to given port"); System.exit(1); } }
Example #10
Source File: ExposedHostTest.java From testcontainers-java with MIT License | 6 votes |
@BeforeClass public static void setUpClass() throws Exception { server = HttpServer.create(new InetSocketAddress(0), 0); server.createContext("/", exchange -> { byte[] content = "Hello World!".getBytes(); exchange.sendResponseHeaders(200, content.length); try (OutputStream responseBody = exchange.getResponseBody()) { responseBody.write(content); responseBody.flush(); } }); server.start(); Testcontainers.exposeHostPorts(server.getAddress().getPort()); Testcontainers.exposeHostPorts(ImmutableMap.of(server.getAddress().getPort(), 80)); Testcontainers.exposeHostPorts(ImmutableMap.of(server.getAddress().getPort(), 81)); }
Example #11
Source File: bug4714674.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
/** * 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 #12
Source File: MissingTrailingSpace.java From hottub with GNU General Public License v2.0 | 5 votes |
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 #13
Source File: InfiniteLoop.java From hottub with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress(0), 0); server.createContext("/test/InfiniteLoop", new RespHandler()); server.start(); try { InetSocketAddress address = server.getAddress(); URL url = new URL("http://localhost:" + address.getPort() + "/test/InfiniteLoop"); final Phaser phaser = new Phaser(2); for (int i=0; i<10; i++) { HttpURLConnection uc = (HttpURLConnection)url.openConnection(); final InputStream is = uc.getInputStream(); final Thread thread = new Thread() { public void run() { try { phaser.arriveAndAwaitAdvance(); while (is.read() != -1) Thread.sleep(50); } catch (Exception x) { x.printStackTrace(); } }}; thread.start(); phaser.arriveAndAwaitAdvance(); is.close(); System.out.println("returned from close"); thread.join(); } } finally { server.stop(0); } }
Example #14
Source File: SimpleHttpServer.java From Halyard with Apache License 2.0 | 5 votes |
/** * Instantiate a new HTTP server. Use port number 0 (zero) to let the system select a new port number. * * @param port number of port * @param context context path * @param handler handler for handling HTTP requests */ public SimpleHttpServer(int port, String context, HttpHandler handler) throws IOException { // Maximum number of incoming TCP connections is set to system default value int backlog = 0; // Create HTTP server httpServer = HttpServer.create(new InetSocketAddress(port), backlog); // Create HTTP context with a given handler httpServer.createContext(context, handler); // Create an executor httpServer.setExecutor(Executors.newFixedThreadPool(4 * Runtime.getRuntime().availableProcessors())); }
Example #15
Source File: HttpStreams.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
void test() throws Exception { HttpServer server = null; try { server = startHttpServer(); String baseUrl = "http://localhost:" + server.getAddress().getPort() + "/"; client(baseUrl + "chunked/"); client(baseUrl + "fixed/"); client(baseUrl + "error/"); client(baseUrl + "chunkedError/"); // Test with a response cache ResponseCache ch = ResponseCache.getDefault(); ResponseCache.setDefault(new TrivialCacheHandler()); try { client(baseUrl + "chunked/"); client(baseUrl + "fixed/"); client(baseUrl + "error/"); client(baseUrl + "chunkedError/"); } finally { ResponseCache.setDefault(ch); } } finally { if (server != null) server.stop(0); } System.out.println("passed: " + pass + ", failed: " + fail); if (fail > 0) throw new RuntimeException("some tests failed check output"); }
Example #16
Source File: InfiniteLoop.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress(0), 0); server.createContext("/test/InfiniteLoop", new RespHandler()); server.start(); try { InetSocketAddress address = server.getAddress(); URL url = new URL("http://localhost:" + address.getPort() + "/test/InfiniteLoop"); final Phaser phaser = new Phaser(2); for (int i=0; i<10; i++) { HttpURLConnection uc = (HttpURLConnection)url.openConnection(); final InputStream is = uc.getInputStream(); final Thread thread = new Thread() { public void run() { try { phaser.arriveAndAwaitAdvance(); while (is.read() != -1) Thread.sleep(50); } catch (Exception x) { x.printStackTrace(); } }}; thread.start(); phaser.arriveAndAwaitAdvance(); is.close(); System.out.println("returned from close"); thread.join(); } } finally { server.stop(0); } }
Example #17
Source File: ServerImpl.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
ServerImpl(HttpServer wrapper, String protocol, InetSocketAddress addr, int backlog) throws IOException { this.protocol = protocol; this.wrapper = wrapper; this.logger = Logger.getLogger("com.sun.net.httpserver"); ServerConfig.checkLegacyProperties(this.logger); this.https = protocol.equalsIgnoreCase("https"); this.address = addr; this.contexts = new ContextList(); this.schan = ServerSocketChannel.open(); if (addr != null) { ServerSocket socket = this.schan.socket(); socket.bind(addr, backlog); this.bound = true; } this.selector = Selector.open(); this.schan.configureBlocking(false); this.listenerKey = this.schan.register(this.selector, 16); this.dispatcher = new ServerImpl.Dispatcher(); this.idleConnections = Collections.synchronizedSet(new HashSet()); this.allConnections = Collections.synchronizedSet(new HashSet()); this.reqConnections = Collections.synchronizedSet(new HashSet()); this.rspConnections = Collections.synchronizedSet(new HashSet()); this.time = System.currentTimeMillis(); this.timer = new Timer("server-timer", true); this.timer.schedule(new ServerImpl.ServerTimerTask(), (long)CLOCK_TICK, (long)CLOCK_TICK); if (timer1Enabled) { this.timer1 = new Timer("server-timer1", true); this.timer1.schedule(new ServerImpl.ServerTimerTask1(), TIMER_MILLIS, TIMER_MILLIS); this.logger.config("HttpServer timer1 enabled period in ms: " + TIMER_MILLIS); this.logger.config("MAX_REQ_TIME: " + MAX_REQ_TIME); this.logger.config("MAX_RSP_TIME: " + MAX_RSP_TIME); } this.events = new LinkedList(); this.logger.config("HttpServer created " + protocol + " " + addr); }
Example #18
Source File: HttpNegotiateServer.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
/** * Creates and starts an HTTP or proxy server that requires * Negotiate authentication. * @param scheme "Negotiate" or "Kerberos" * @param principal the krb5 service principal the server runs with * @return the server */ public static HttpServer httpd(String scheme, boolean proxy, String principal, String ktab) throws Exception { MyHttpHandler h = new MyHttpHandler(); HttpServer server = HttpServer.create(new InetSocketAddress(0), 0); HttpContext hc = server.createContext("/", h); hc.setAuthenticator(new MyServerAuthenticator( proxy, scheme, principal, ktab)); server.start(); return server; }
Example #19
Source File: Test.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
private static String deployWebservice() throws IOException { // Manually create HttpServer here using ephemeral address for port // so as to not end up with attempt to bind to an in-use port httpServer = HttpServer.create(new InetSocketAddress(0), 0); httpServer.start(); endpoint = Endpoint.create(new ServiceImpl()); endpoint.publish(httpServer.createContext("/wservice")); String wsdlAddress = "http://localhost:" + httpServer.getAddress().getPort() + "/wservice?wsdl"; log("address = " + wsdlAddress); return wsdlAddress; }
Example #20
Source File: HttpClientFactoryImplTest.java From component-runtime with Apache License 2.0 | 5 votes |
@Test void requestWithJSON() throws IOException { final HttpServer server = HttpServer.create(new InetSocketAddress(0), 0); server.createContext("/").setHandler(httpExchange -> { final Headers headers = httpExchange.getResponseHeaders(); headers.set("content-type", "application/json;charset=UTF-8"); final byte[] bytes; try (final BufferedReader in = new BufferedReader(new InputStreamReader(httpExchange.getRequestBody(), StandardCharsets.UTF_8))) { bytes = in.lines().collect(joining("\n")).getBytes(StandardCharsets.UTF_8); } httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, bytes.length); httpExchange.getResponseBody().write(bytes); httpExchange.close(); }); try { server.start(); final ResponseJson client = newDefaultFactory().create(ResponseJson.class, null); client.base("http://localhost:" + server.getAddress().getPort() + "/api"); final Response<Sample> result = client.main("application/json", new Sample(singletonList(new Foo("testJSON")))); assertEquals(1, result.body().getFoos().size()); assertEquals("testJSON", result.body().getFoos().iterator().next().getName()); assertEquals(HttpURLConnection.HTTP_OK, result.status()); assertEquals("30", result.headers().get("content-length").iterator().next()); } finally { server.stop(0); } }
Example #21
Source File: B4769350.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
public void startServer() { InetSocketAddress addr = new InetSocketAddress(0); try { server = HttpServer.create(addr, 0); } catch (IOException ioe) { throw new RuntimeException("Server could not be created"); } executor = Executors.newFixedThreadPool(10); server.setExecutor(executor); server.createContext("/test/realm1/t1a", new AuthenticationHandlerT1a() ); server.createContext("/test/realm2/t1b", new AuthenticationHandlerT1b()); server.createContext("/test/realm1/t1c", new AuthenticationHandlerT1c()); server.createContext("/test/realm2/t1d", new AuthenticationHandlerT1d()); server.createContext("/test/realm3/t2a", new AuthenticationHandlerT2a()); server.createContext("/test/realm3/t2b", new AuthenticationHandlerT2b()); server.createContext("/test/realm4/t3a", new AuthenticationHandlerT3a()); server.createContext("/test/realm4/t3b", new AuthenticationHandlerT3bc()); server.createContext("/test/realm4/t3c", new AuthenticationHandlerT3bc()); t1Cond1 = new CyclicBarrier(3); server.start(); }
Example #22
Source File: L2ACPServer.java From L2ACP-api with GNU General Public License v2.0 | 5 votes |
public L2ACPServer() { HttpServer server; try { server = HttpServer.create(new InetSocketAddress(8000), 0); server.createContext("/api", new RequestHandler()); server.setExecutor(null); // creates a default executor server.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ThreadPool.scheduleAtFixedRate(new DatamineTask(), 120000, 600000); }
Example #23
Source File: Test.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
private static String deployWebservice() throws IOException { // Manually create HttpServer here using ephemeral address for port // so as to not end up with attempt to bind to an in-use port httpServer = HttpServer.create(new InetSocketAddress(0), 0); httpServer.start(); endpoint = Endpoint.create(new ServiceImpl()); endpoint.publish(httpServer.createContext("/wservice")); String wsdlAddress = "http://localhost:" + httpServer.getAddress().getPort() + "/wservice?wsdl"; log("address = " + wsdlAddress); return wsdlAddress; }
Example #24
Source File: HttpOnly.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
void test(String[] args) throws Exception { HttpServer server = startHttpServer(); CookieHandler previousHandler = CookieHandler.getDefault(); try { InetSocketAddress address = server.getAddress(); URI uri = new URI("http://" + InetAddress.getLocalHost().getHostAddress() + ":" + address.getPort() + URI_PATH); populateCookieStore(uri); doClient(uri); } finally { CookieHandler.setDefault(previousHandler); server.stop(0); } }
Example #25
Source File: bug4714674.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
/** * 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 #26
Source File: APIErrors.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
static HttpServer createServer() throws Exception { HttpServer s = HttpServer.create(new InetSocketAddress(0), 0); if (s instanceof HttpsServer) throw new RuntimeException ("should not be httpsserver"); String root = System.getProperty("test.src") + "/docs"; s.createContext("/files", new FileServerHandler(root)); s.setExecutor(serverExecutor); s.start(); return s; }
Example #27
Source File: App.java From templates with MIT License | 5 votes |
public static void main(String[] args) throws Exception { int port = 8082; IHandler handler = new com.openfaas.function.Handler(); HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); InvokeHandler invokeHandler = new InvokeHandler(handler); server.createContext("/", invokeHandler); server.setExecutor(null); // creates a default executor server.start(); }
Example #28
Source File: MockTaxiiService.java From metron with Apache License 2.0 | 5 votes |
public static void start(int port) throws IOException { // Create an HTTP server listening at port 8282 URI uri = UriBuilder.fromUri("http://localhost/").port(port).build(); server = HttpServer.create(new InetSocketAddress(uri.getPort()), 0); HttpHandler handler = RuntimeDelegate.getInstance().createEndpoint(new ApplicationConfig(), HttpHandler.class); server.createContext(uri.getPath(), handler); discoveryMsg = discoveryMsg.replaceAll("PORT", "" + uri.getPort()); server.start(); }
Example #29
Source File: WebApp.java From hbase-tools with Apache License 2.0 | 5 votes |
private WebApp(Args args, TableStat tableStat) throws IOException { server = HttpServer.create(new InetSocketAddress(port(args)), 0); server.createContext("/", new RootHandler(args)); server.createContext("/stat", new StatHandler(tableStat.getFormatter())); server.createContext("/jquery", new JQueryHandler()); server.createContext("/keyInput", new KeyInputHandler(tableStat)); server.setExecutor(null); }
Example #30
Source File: HttpNegotiateServer.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
/** * Creates and starts an HTTP or proxy server that requires * Negotiate authentication. * @param scheme "Negotiate" or "Kerberos" * @param principal the krb5 service principal the server runs with * @return the server */ public static HttpServer httpd(String scheme, boolean proxy, String principal, String ktab) throws Exception { MyHttpHandler h = new MyHttpHandler(); HttpServer server = HttpServer.create(new InetSocketAddress(0), 0); HttpContext hc = server.createContext("/", h); hc.setAuthenticator(new MyServerAuthenticator( proxy, scheme, principal, ktab)); server.start(); return server; }