Java Code Examples for com.sun.net.httpserver.HttpServer#createContext()
The following examples show how to use
com.sun.net.httpserver.HttpServer#createContext() .
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: HtmlToPdfTest.java From htmltopdf-java with MIT License | 6 votes |
@Test public void itConvertsMarkupFromUrlToPdf() throws IOException { String html = "<html><head><title>Test page</title></head><body><p>This is just a simple test.</p></html>"; HttpServer httpServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); httpServer.createContext("/test", httpExchange -> { httpExchange.sendResponseHeaders(200, html.length()); try (OutputStream os = httpExchange.getResponseBody()) { os.write(html.getBytes(StandardCharsets.UTF_8)); } }); httpServer.start(); String url = String.format("http://127.0.0.1:%d/test", httpServer.getAddress().getPort()); boolean success = HtmlToPdf.create() .object(HtmlToPdfObject.forUrl(url)) .convert("/dev/null"); assertTrue(success); }
Example 2
Source File: FixedLengthInputStream.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
/** * 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; }
Example 3
Source File: ContentTypeTestCase.java From product-ei with Apache License 2.0 | 6 votes |
@Test(groups = {"wso2.esb"}, description = "Test different content types", dataProvider = "contentTypeProvider") public void testReturnContentType(String dataProviderContentType) throws Exception { contentType = dataProviderContentType; HttpServer server = HttpServer.create(new InetSocketAddress(PORT), 0); server.createContext("/gettest", new MyHandler()); server.setExecutor(null); // creates a default executor server.start(); DefaultHttpClient httpclient = new DefaultHttpClient(); String url = "http://localhost:8480/serviceTest/test"; HttpGet httpGet = new HttpGet(url); HttpResponse response = null; try { response = httpclient.execute(httpGet); } catch (IOException e) { log.error("Error Occurred while sending http get request. " , e); } log.info(response.getEntity().getContentType()); log.info(response.getStatusLine().getStatusCode()); assertEquals(response.getFirstHeader("Content-Type").getValue(), contentType, "Expected content type doesn't match"); assertEquals(response.getStatusLine().getStatusCode(), HTTP_STATUS_OK, "response code doesn't match"); server.stop(5); }
Example 4
Source File: Mapper_MappingFile_URL_Test.java From rmlmapper-java with MIT License | 6 votes |
@Test public void testValid() throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); server.createContext("/mappingFile", new ValidMappingFileHandler()); server.createContext("/inputFile", new ValidInputFileHandler()); server.setExecutor(null); // creates a default executor server.start(); Main.main("-m http://localhost:8080/mappingFile -o ./generated_output.nq".split(" ")); compareFiles( "./generated_output.nq", "MAPPINGFILE_URL_TEST_valid/target_output.nq", false ); server.stop(0); File outputFile = Utils.getFile("./generated_output.nq"); assertTrue(outputFile.delete()); }
Example 5
Source File: ExpectUtilsHttpTest.java From expect4j with Apache License 2.0 | 5 votes |
public void setUp() throws Exception { HttpServer httpServer = HttpServer.create(new InetSocketAddress(address, 0), 0); httpServer.createContext("/", new TestHandler()); httpServer.setExecutor(null); httpServer.start(); port = httpServer.getAddress().getPort(); }
Example 6
Source File: InfiniteLoop.java From openjdk-8-source 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 7
Source File: ChunkedEncodingTest.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
/** * 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 8
Source File: HttpNegotiateServer.java From TencentKona-8 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 9
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 10
Source File: HttpStreams.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
HttpServer startHttpServer() throws IOException { HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0); httpServer.createContext("/chunked/", new ChunkedHandler()); httpServer.createContext("/fixed/", new FixedHandler()); httpServer.createContext("/error/", new ErrorHandler()); httpServer.createContext("/chunkedError/", new ChunkedErrorHandler()); httpServer.start(); return httpServer; }
Example 11
Source File: HttpService.java From binlake with Apache License 2.0 | 5 votes |
/** * http service for outer * * @param port * @param lsm * @param client * @throws IOException */ public HttpService(int port, ConcurrentHashMap<String, ILeaderSelector> lsm, IZkClient client) throws IOException { LogUtils.debug.debug("http service start"); HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); server.createContext("/alive", new AliveHandler(lsm, client)); server.createContext("/delay", new MonitorHandler(lsm, client)); server.createContext("/kill", new KillHandler(lsm, client)); server.createContext("/refresh", new RefreshHandler(lsm, client)); server.createContext("/add/selector", new AddSelectorHandler(lsm, client)); server.start(); }
Example 12
Source File: MissingTrailingSpace.java From openjdk-jdk8u 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: HTTPTestServer.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
public static HTTPTestServer createServerAndRedirect( HttpProtocolType protocol, HttpAuthType targetAuthType, HttpTestAuthenticator auth, HttpSchemeType schemeType, HttpHandler targetDelegate, int code300) throws IOException { Objects.requireNonNull(targetAuthType); Objects.requireNonNull(auth); // The connection between client and proxy can only // be a plain connection: SSL connection to proxy // is not supported by our client connection. HttpProtocolType targetProtocol = targetAuthType == HttpAuthType.PROXY ? HttpProtocolType.HTTP : protocol; HTTPTestServer redirectTarget = (targetAuthType == HttpAuthType.PROXY) ? createProxy(protocol, targetAuthType, auth, schemeType, targetDelegate, "/") : createServer(targetProtocol, targetAuthType, auth, schemeType, targetDelegate, "/"); HttpServer impl = createHttpServer(protocol); final HTTPTestServer redirectingServer = new HTTPTestServer(impl, redirectTarget, null); InetSocketAddress redirectAddr = redirectTarget.getAddress(); URL locationURL = url(targetProtocol, redirectAddr, "/"); final HttpHandler hh = redirectingServer.create300Handler(locationURL, HttpAuthType.SERVER, code300); impl.createContext("/", hh); impl.start(); return redirectingServer; }
Example 14
Source File: BasicLongCredentials.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); try { Handler handler = new Handler(); HttpContext ctx = server.createContext("/test", handler); BasicAuthenticator a = new BasicAuthenticator(REALM) { public boolean checkCredentials (String username, String pw) { return USERNAME.equals(username) && PASSWORD.equals(pw); } }; ctx.setAuthenticator(a); server.start(); Authenticator.setDefault(new MyAuthenticator()); URL url = new URL("http://localhost:"+server.getAddress().getPort()+"/test/"); HttpURLConnection urlc = (HttpURLConnection)url.openConnection(); InputStream is = urlc.getInputStream(); int c = 0; while (is.read()!= -1) { c ++; } if (c != 0) { throw new RuntimeException("Test failed c = " + c); } if (error) { throw new RuntimeException("Test failed: error"); } System.out.println ("OK"); } finally { server.stop(0); } }
Example 15
Source File: ConfigMapApp.java From smallrye-config with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { Config config = ConfigProvider.getConfig(); HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); server.createContext("/configMap", exchange -> { boolean responseSent = false; final Iterable<ConfigSource> configSources = config.getConfigSources(); for (ConfigSource configSource : configSources) { if (configSource.getName().startsWith("FileSystemConfig")) { final Map<String, String> properties = configSource.getProperties(); final byte[] bytes = properties.toString().getBytes(); exchange.sendResponseHeaders(200, properties.toString().length()); exchange.getResponseBody().write(bytes); exchange.getResponseBody().flush(); exchange.getResponseBody().close(); responseSent = true; break; } } if (!responseSent) { exchange.sendResponseHeaders(404, 0); exchange.getResponseBody().write(new byte[0]); exchange.getResponseBody().flush(); exchange.getResponseBody().close(); } }); server.start(); }
Example 16
Source File: PilosaClientIT.java From java-pilosa with BSD 3-Clause "New" or "Revised" License | 5 votes |
private HttpServer runNonexistentCoordinatorHttpServer() { final int port = 15999; try { HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); server.createContext("/status", new NonexistentCoordinatorHandler()); server.setExecutor(null); server.start(); return server; } catch (IOException ex) { fail(ex.getMessage()); } return null; }
Example 17
Source File: PilosaClientIT.java From java-pilosa with BSD 3-Clause "New" or "Revised" License | 5 votes |
private HttpServer runNoCoordinatorHttpServer() { final int port = 15999; try { HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); server.createContext("/status", new NoCoordinatorHandler()); server.setExecutor(null); server.start(); return server; } catch (IOException ex) { fail(ex.getMessage()); } return null; }
Example 18
Source File: HttpOnly.java From openjdk-jdk8u with GNU General Public License v2.0 | 4 votes |
HttpServer startHttpServer() throws IOException { HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0); httpServer.createContext(URI_PATH, new SimpleHandler()); httpServer.start(); return httpServer; }
Example 19
Source File: NoCache.java From openjdk-jdk8u with GNU General Public License v2.0 | 4 votes |
static HttpServer startHttpServer() throws IOException { HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0); httpServer.createContext("/NoCache/", new SimpleHandler()); httpServer.start(); return httpServer; }
Example 20
Source File: NoCache.java From hottub with GNU General Public License v2.0 | 4 votes |
static HttpServer startHttpServer() throws IOException { HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0); httpServer.createContext("/NoCache/", new SimpleHandler()); httpServer.start(); return httpServer; }