static void run(String host, String portString, CollectorRegistry registry) throws Exception { try { int port = Integer.parseInt(portString); InetSocketAddress address = host == null ? new InetSocketAddress(port) : new InetSocketAddress(host, port); HttpServer httpServer = HttpServer.create(address, 10); httpServer.createContext("/", httpExchange -> { if ("/metrics".equals(httpExchange.getRequestURI().getPath())) { respondMetrics(registry, httpExchange); } else { respondRedirect(httpExchange); } }); httpServer.start(); } catch (NumberFormatException e) { throw new RuntimeException("Failed to parse command line arguments: '" + portString + "' is not a valid port number."); } }
@BeforeClass public static void startHttpServer() throws Exception { String pathPrefixWithoutLeadingSlash; if (randomBoolean()) { pathPrefixWithoutLeadingSlash = "testPathPrefix/" + randomAsciiOfLengthBetween(1, 5); pathPrefix = "/" + pathPrefixWithoutLeadingSlash; } else { pathPrefix = pathPrefixWithoutLeadingSlash = ""; } int numHttpServers = randomIntBetween(2, 4); httpServers = new HttpServer[numHttpServers]; HttpHost[] httpHosts = new HttpHost[numHttpServers]; for (int i = 0; i < numHttpServers; i++) { HttpServer httpServer = createHttpServer(); httpServers[i] = httpServer; httpHosts[i] = new HttpHost(httpServer.getAddress().getHostString(), httpServer.getAddress().getPort()); } RestClientBuilder restClientBuilder = RestClient.builder(httpHosts); if (pathPrefix.length() > 0) { restClientBuilder.setPathPrefix((randomBoolean() ? "/" : "") + pathPrefixWithoutLeadingSlash); } restClient = restClientBuilder.build(); }
@Before public void stopRandomHost() { //verify that shutting down some hosts doesn't matter as long as one working host is left behind if (httpServers.length > 1 && randomBoolean()) { List<HttpServer> updatedHttpServers = new ArrayList<>(httpServers.length - 1); int nodeIndex = randomInt(httpServers.length - 1); for (int i = 0; i < httpServers.length; i++) { HttpServer httpServer = httpServers[i]; if (i == nodeIndex) { httpServer.stop(0); } else { updatedHttpServers.add(httpServer); } } httpServers = updatedHttpServers.toArray(new HttpServer[updatedHttpServers.size()]); } }
/** * Starts the http server for Graphflow web UI. */ @Override public void run() { try { HttpServer server = HttpServer.create(new InetSocketAddress(HTTP_HOST, HTTP_PORT), 0); // Create a route for input query server.createContext("/query", new PlanViewerHttpHandler()); // Create a default executor server.setExecutor(null); server.start(); File webViewer = new File(PLAN_VIEWER_HTML_PATH); logger.info("Please open the Graphflow UI (link below) in a browser:"); logger.info("file://" + webViewer.getAbsolutePath()); } catch (IOException exception) { logger.error("GraphflowUIHttpServer: failed to start"); } }
public static HTTPTestServer createProxy(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 = protocol == HttpProtocolType.HTTPS ? new HttpsProxyTunnel(impl, null, delegate) : 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; }
@Override public void afterPropertiesSet() throws IOException { InetSocketAddress address = (this.hostname != null ? new InetSocketAddress(this.hostname, this.port) : new InetSocketAddress(this.port)); this.server = HttpServer.create(address, this.backlog); if (this.executor != null) { this.server.setExecutor(this.executor); } if (this.contexts != null) { for (String key : this.contexts.keySet()) { HttpContext httpContext = this.server.createContext(key, this.contexts.get(key)); if (this.filters != null) { httpContext.getFilters().addAll(this.filters); } if (this.authenticator != null) { httpContext.setAuthenticator(this.authenticator); } } } if (this.logger.isInfoEnabled()) { this.logger.info("Starting HttpServer at address " + address); } this.server.start(); }
public static void main(String[] args) throws IOException, URISyntaxException, NoSuchAlgorithmException, InterruptedException { HttpServer server = createHttpsServer(); server.start(); try { test(server, HttpClient.Version.HTTP_1_1); test(server, HttpClient.Version.HTTP_2); } finally { server.stop(0); System.out.println("Server stopped"); } }
public static void main(String[] args) throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(8081), 0); server.setExecutor(Executors.newCachedThreadPool()); server.createContext("/meet", exchange -> { try { Thread.sleep(250); } catch (InterruptedException e) { } exchange.sendResponseHeaders(200, 0); exchange.getResponseBody().close(); }); server.start(); }
/** * Http Server */ HttpServer startHttpServer() throws IOException { if (debug) { Logger logger = Logger.getLogger("com.sun.net.httpserver"); Handler outHandler = new StreamHandler(System.out, new SimpleFormatter()); outHandler.setLevel(Level.FINEST); logger.setLevel(Level.FINEST); logger.addHandler(outHandler); } HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0); httpServer.createContext("/flis/", new MyHandler(POST_SIZE)); httpServer.start(); return httpServer; }
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); } }
public static void main(String[] args) throws Exception { HttpServer server = createServer(); int port = server.getAddress().getPort(); System.out.println("HTTP server port = " + port); httproot = "http://127.0.0.1:" + port + "/files/"; fileuri = httproot + "foo.txt"; HttpClient client = HttpClient.newHttpClient(); try { test1(); test2(); //test3(); } finally { server.stop(0); serverExecutor.shutdownNow(); for (HttpClient c : clients) ((ExecutorService)c.executor()).shutdownNow(); } }
/** * 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; }
public static void register(HttpServer server) { // Info server.createContext("/api", new InfoController()); // Version server.createContext("/api/version", new VersionController()); // Settings server.createContext("/api/settings", new SettingsController()); // Refresh server.createContext("/api/user/refresh", new UserRefreshController()); // Events server.createContext("/api/user/events", new UserEventsController()); // Bot server.createContext("/api/bot", new BotInfoController()); server.createContext("/api/bot/start", new StartController()); server.createContext("/api/bot/stop", new StopController()); // Plugins server.createContext("/api/plugins", new PluginController()); }
public static void test() { HttpServer server = null; try { serverDigest = MessageDigest.getInstance("MD5"); clientDigest = MessageDigest.getInstance("MD5"); server = startHttpServer(); int port = server.getAddress().getPort(); out.println ("Server listening on port: " + port); client("http://localhost:" + port + "/chunked/"); if (!MessageDigest.isEqual(clientMac, serverMac)) { throw new RuntimeException( "Data received is NOT equal to the data sent"); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (server != null) server.stop(0); } }
public static void main(String[] args) throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(HTTP_SERVER_PORT), 0); HttpContext secureContext = server.createContext(DEMO_REST_BASIC_AUTH, new RestDemoHandler()); secureContext.setAuthenticator(new BasicAuthenticator("demo-auth") { @Override public boolean checkCredentials(String user, String pwd) { return user.equals(USERNAME) && pwd.equals(PASSWORD); } }); server.createContext(DEMO_REST_NO_AUTH, new RestDemoHandler()); server.setExecutor(null); System.out.println("[*] Waiting for messages."); server.start(); }
public WebServerTestHelper() throws IOException, IllegalArgumentException { port = DEFAULT_PORT; String inPort = System.getProperty("wlt3.test.server.port"); if(inPort!=null && !inPort.isEmpty()) { try { inPort = inPort.trim(); port = Integer.parseInt(inPort); if((port<1) || (port>65535)) { throw new IllegalArgumentException("\""+inPort+"\" is not a valid TCP port for standalone web server listener! Valid TCP ports: 0-65535"); } } catch(Exception e) { throw new IllegalArgumentException("\""+inPort+"\" is not a valid TCP port for standalone web server listener!"); } } hs = HttpServer.create(new InetSocketAddress(port),0); sr = new SecureRandom(); accessList = new Hashtable<String,String>(); hs.start(); }
static void initServer() throws Exception { Logger logger = Logger.getLogger("com.sun.net.httpserver"); ConsoleHandler ch = new ConsoleHandler(); logger.setLevel(Level.SEVERE); ch.setLevel(Level.SEVERE); logger.addHandler(ch); String root = System.getProperty ("test.src")+ "/docs"; InetSocketAddress addr = new InetSocketAddress (0); s1 = HttpServer.create (addr, 0); if (s1 instanceof HttpsServer) { throw new RuntimeException ("should not be httpsserver"); } s2 = HttpsServer.create (addr, 0); HttpHandler h = new FileServerHandler(root); HttpContext c1 = s1.createContext("/files", h); HttpContext c2 = s2.createContext("/files", h); HttpContext c3 = s1.createContext("/echo", new EchoHandler()); redirectHandler = new RedirectHandler("/redirect"); redirectHandlerSecure = new RedirectHandler("/redirect"); HttpContext c4 = s1.createContext("/redirect", redirectHandler); HttpContext c41 = s2.createContext("/redirect", redirectHandlerSecure); HttpContext c5 = s2.createContext("/echo", new EchoHandler()); HttpContext c6 = s1.createContext("/keepalive", new KeepAliveHandler()); redirectErrorHandler = new RedirectErrorHandler("/redirecterror"); redirectErrorHandlerSecure = new RedirectErrorHandler("/redirecterror"); HttpContext c7 = s1.createContext("/redirecterror", redirectErrorHandler); HttpContext c71 = s2.createContext("/redirecterror", redirectErrorHandlerSecure); delayHandler = new DelayHandler(); HttpContext c8 = s1.createContext("/delay", delayHandler); HttpContext c81 = s2.createContext("/delay", delayHandler); executor = Executors.newCachedThreadPool(); s1.setExecutor(executor); s2.setExecutor(executor); ctx = new SimpleSSLContext().get(); sslparams = ctx.getSupportedSSLParameters(); s2.setHttpsConfigurator(new Configurator(ctx)); s1.start(); s2.start(); port = s1.getAddress().getPort(); System.out.println("HTTP server port = " + port); httpsport = s2.getAddress().getPort(); System.out.println("HTTPS server port = " + httpsport); httproot = "http://127.0.0.1:" + port + "/"; httpsroot = "https://127.0.0.1:" + httpsport + "/"; proxy = new ProxyServer(0, false); proxyPort = proxy.getPort(); System.out.println("Proxy port = " + proxyPort); }
@Override public void init(DaemonContext context) throws DaemonInitException, Exception { if (!config.init(context.getArguments())) throw new DaemonInitException("Invalid configuration."); ClassLoader loader = SPLDaemon.class.getClassLoader(); InputStream params = loader.getResourceAsStream(DEFAULT_PARAMS_FILE); if (params != null) { MAVLinkShadow.getInstance().loadParams(params); params.close(); } else { logger.warn("File 'default.params' with initial parameters values not found."); } MAVLinkMessageQueue mtMessageQueue = new MAVLinkMessageQueue(config.getQueueSize()); tcpServer = new MAVLinkTcpServer(config.getMAVLinkPort(), mtMessageQueue); MAVLinkMessageQueue moMessageQueue = new MAVLinkMessageQueue(config.getQueueSize()); MOMessageHandler moHandler = new MOMessageHandler(moMessageQueue); httpServer = HttpServer.create(new InetSocketAddress(config.getRockblockPort()), 0); httpServer.createContext(config.getHttpContext(), new RockBlockHttpHandler(moHandler, config.getRockBlockIMEI())); httpServer.setExecutor(null); // TODO: Broadcast MO messages to all the connected clients. RockBlockClient rockblock = new RockBlockClient(config.getRockBlockIMEI(), config.getRockBlockUsername(), config.getRockBlockPassword(), config.getRockBlockURL()); MTMessagePump mtMsgPump = new MTMessagePump(mtMessageQueue, rockblock); mtMsgPumpThread = new Thread(mtMsgPump, "mt-message-pump"); WSEndpoint.setMTQueue(mtMessageQueue); wsServer = new Server("localhost", config.getWSPort(), "/gcs", WSEndpoint.class); }
private static HttpServer createHttpServer() throws Exception { HttpServer httpServer = MockHttpServer.createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); httpServer.start(); //returns a different status code depending on the path for (int statusCode : getAllStatusCodes()) { httpServer.createContext(pathPrefix + "/" + statusCode, new ResponseHandler(statusCode)); } return httpServer; }
@AfterClass public static void stopHttpServers() throws IOException { restClient.close(); restClient = null; for (HttpServer httpServer : httpServers) { httpServer.stop(0); } httpServers = null; }
public static void initServer() throws IOException { Logger logger = Logger.getLogger("com.sun.net.httpserver"); ConsoleHandler ch = new ConsoleHandler(); logger.setLevel(Level.ALL); ch.setLevel(Level.ALL); logger.addHandler(ch); String root = System.getProperty("test.src") + "/docs"; InetSocketAddress addr = new InetSocketAddress(0); httpServer = HttpServer.create(addr, 0); if (httpServer instanceof HttpsServer) { throw new RuntimeException("should not be httpsserver"); } httpsServer = HttpsServer.create(addr, 0); HttpHandler h = new FileServerHandler(root); HttpContext c1 = httpServer.createContext("/files", h); HttpContext c2 = httpsServer.createContext("/files", h); HttpContext c3 = httpServer.createContext("/echo", new EchoHandler()); redirectHandler = new RedirectHandler("/redirect"); redirectHandlerSecure = new RedirectHandler("/redirect"); HttpContext c4 = httpServer.createContext("/redirect", redirectHandler); HttpContext c41 = httpsServer.createContext("/redirect", redirectHandlerSecure); HttpContext c5 = httpsServer.createContext("/echo", new EchoHandler()); HttpContext c6 = httpServer.createContext("/keepalive", new KeepAliveHandler()); redirectErrorHandler = new RedirectErrorHandler("/redirecterror"); redirectErrorHandlerSecure = new RedirectErrorHandler("/redirecterror"); HttpContext c7 = httpServer.createContext("/redirecterror", redirectErrorHandler); HttpContext c71 = httpsServer.createContext("/redirecterror", redirectErrorHandlerSecure); delayHandler = new DelayHandler(); HttpContext c8 = httpServer.createContext("/delay", delayHandler); HttpContext c81 = httpsServer.createContext("/delay", delayHandler); executor = Executors.newCachedThreadPool(); httpServer.setExecutor(executor); httpsServer.setExecutor(executor); ctx = new SimpleSSLContext().get(); httpsServer.setHttpsConfigurator(new HttpsConfigurator(ctx)); httpServer.start(); httpsServer.start(); port = httpServer.getAddress().getPort(); System.out.println("HTTP server port = " + port); httpsport = httpsServer.getAddress().getPort(); System.out.println("HTTPS server port = " + httpsport); httproot = "http://127.0.0.1:" + port + "/"; httpsroot = "https://127.0.0.1:" + httpsport + "/"; proxy = new ProxyServer(0, false); proxyPort = proxy.getPort(); System.out.println("Proxy port = " + proxyPort); }
static LocalHttpServer startServer() throws IOException { HttpServer httpServer = HttpServer.create( new InetSocketAddress(0), 0); LocalHttpServer localHttpServer = new LocalHttpServer(httpServer); localHttpServer.start(); return localHttpServer; }
static HttpServer createServer(ExecutorService e, BasicAuthenticator sa) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress(0), 10); Handler h = new Handler(); HttpContext serverContext = server.createContext("/test", h); serverContext.setAuthenticator(sa); server.setExecutor(e); server.start(); return server; }
public static void main(String[] args) throws IOException { banner(); int port = 8000; HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); server.createContext("/", new HTTPHandler()); server.setExecutor(null); // creates a default executor server.start(); System.out.println("\nJRE Version: "+System.getProperty("java.version")); System.out.println("[INFO]: Listening on port "+port); System.out.println(); }
public static void main(String[] args) throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); server.createContext("/", new LandingPageHandler()); server.createContext("/post", new PostHandler()); server.createContext("/json", new JSONHandler()); server.createContext("/favicon.ico", new IgnoreHandler()); server.setExecutor(Executors.newCachedThreadPool()); server.start(); System.out.println("Server started on port 8080" ); }
private void init() { try { server = HttpServer.create(new InetSocketAddress(8900), 0); server.createContext("/sparql", new GetSparqlResult(this)); } catch (Exception exception) { fail(exception.getMessage()); } }
private void createContext(HttpServer server, String path, HttpHandler handler, Authenticator auth) { final HttpContext context = server.createContext(path, handler); if( auth != null ) { context.setAuthenticator(auth); } context.getFilters().addAll(filters); }
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."); }
public GameStateIntegration(int port) { this.locale = new Locale("/lang/en-US.lang", "en-US"); // Make sure to load our locale try { this.server = HttpServer.create(new InetSocketAddress(port), 0); // Make our http server this.server.createContext("/", this); this.server.setExecutor(null); this.server.start(); Courier.getInstance().getLogger().info("Initiated GSI http server!"); } catch (IOException e) { e.printStackTrace(); } }
@Override public void afterPropertiesSet() throws Exception { if (this.server == null) { InetSocketAddress address = (this.hostname != null ? new InetSocketAddress(this.hostname, this.port) : new InetSocketAddress(this.port)); this.server = HttpServer.create(address, this.backlog); if (this.logger.isInfoEnabled()) { this.logger.info("Starting HttpServer at address " + address); } this.server.start(); this.localServer = true; } super.afterPropertiesSet(); }
public void start() throws IOException { this.server = HttpServer.create(new InetSocketAddress(this.port), 0); this.server.createContext("/", new DIALServer(this.piy, this.port)); this.server.setExecutor(null); this.server.start(); }
@Override public void run() { try { server = HttpServer.create(new InetSocketAddress(port), 5); server.createContext("/abc", serverListener); server.start(); } catch (IOException e) { logger.error("Error in creating test server.", e); } }
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); }
private JNLPServer(int port, String hostname) throws IOException { httpServer = HttpServer.create(new InetSocketAddress(port), 0); Properties ps = new Properties(); InputStream stream = getClass().getResourceAsStream( "/com/ramussoft/lib.conf"); ps.load(stream); stream.close(); httpServer.createContext("/", new ResourceServlet(hostname, new Date( Long.parseLong(ps.getProperty("LastModified"))))); httpServer.setExecutor(Executors.newCachedThreadPool()); }
@Test(expected = PilosaException.class) public void importFailNot200() throws IOException { HttpServer server = runImportFailsHttpServer(); try (PilosaClient client = PilosaClient.withAddress(":15999")) { StaticBitIterator iterator = new StaticBitIterator(); try { client.importFrame(this.index.frame("importframe"), iterator); } finally { if (server != null) { server.stop(0); } } } }
@Test(expected = PilosaException.class) public void queryFail404Test() throws IOException { HttpServer server = runContentSizeLyingHttpServer("/404"); try (PilosaClient client = PilosaClient.withAddress(":15999")) { try { client.query(this.frame.setBit(15, 10)); } finally { if (server != null) { server.stop(0); } } } }
private static HttpServer newHttpServer(HttpProtocolType protocol) throws IOException { switch (protocol) { case HTTP: return HttpServer.create(); case HTTPS: return HttpsServer.create(); default: throw new InternalError("Unsupported protocol " + protocol); } }