Java Code Examples for com.sun.net.httpserver.HttpServer#create()

The following examples show how to use com.sun.net.httpserver.HttpServer#create() . 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: GridEmbeddedHttpServer.java    From ignite with Apache License 2.0 7 votes vote down vote up
/**
 * Internal method which creates and starts the server.
 *
 * @param httpsMode True if the server to be started is HTTPS, false otherwise.
 * @return Started server.
 */
private static GridEmbeddedHttpServer createAndStart(boolean httpsMode) throws Exception {
    HttpServer httpSrv;
    InetSocketAddress addrToBind = new InetSocketAddress(HOSTNAME_TO_BIND_SRV, getAvailablePort());

    if (httpsMode) {
        HttpsServer httpsSrv = HttpsServer.create(addrToBind, 0);

        httpsSrv.setHttpsConfigurator(new HttpsConfigurator(GridTestUtils.sslContext()));

        httpSrv = httpsSrv;
    }
    else
        httpSrv = HttpServer.create(addrToBind, 0);

    GridEmbeddedHttpServer embeddedHttpSrv = new GridEmbeddedHttpServer();

    embeddedHttpSrv.proto = httpsMode ? "https" : "http";
    embeddedHttpSrv.httpSrv = httpSrv;
    embeddedHttpSrv.httpSrv.start();

    return embeddedHttpSrv;
}
 
Example 2
Source File: PicqHttpServer.java    From PicqBotX with MIT License 6 votes vote down vote up
/**
 * 启动 Http 服务器
 */
public void start()
{
    try
    {
        // 使用 Java SE 6 内置的 HttpServer
        server = HttpServer.create(new InetSocketAddress(port), 0);

        // 添加监听器
        server.createContext("/", new PicqHttpHandler());

        // 启动
        server.start();
    }
    catch (IOException e)
    {
        throw new HttpServerException(logger, e);
    }
}
 
Example 3
Source File: AbstractWebSink.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
/**
 * Start a http server on supplied port that will serve the metrics, as json,
 * on the specified path.
 *
 * @param path
 * @param port
 */
protected void startHttpServer(String path, int port) {
  try {
    httpServer = HttpServer.create(new InetSocketAddress(port), 0);
    httpServer.createContext(path, httpExchange -> {
      byte[] response = generateResponse();
      httpExchange.sendResponseHeaders(HTTP_STATUS_OK, response.length);
      OutputStream os = httpExchange.getResponseBody();
      os.write(response);
      os.close();
      LOG.log(Level.INFO, "Received metrics request.");
    });
    LOG.info("Starting web sink server on port: " + port);
    httpServer.start();
  } catch (IOException e) {
    throw new RuntimeException("Failed to create Http server on port " + port, e);
  }
}
 
Example 4
Source File: HttpInteractor.java    From NCANode with MIT License 6 votes vote down vote up
@Override
public void interact() {
    String ip   = provider.config.get("http", "ip");
    int port = Integer.valueOf(provider.config.get("http", "port"));

    provider.out.write("Starting HTTP server on " + ip + ":" + port + "...");

    InetSocketAddress inetSocketAddress = new InetSocketAddress(ip, port);

    try {
        HttpServer http = HttpServer.create(inetSocketAddress, 0);
        http.createContext("/", new HttpApiHandler());
        http.start();
    } catch (IOException e) {
        e.printStackTrace();
    }


}
 
Example 5
Source File: Server.java    From nano with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    long start = System.currentTimeMillis();
    String rootFolder = args.length >= 1 ? args[0] : ".";
    int port = args.length >= 2 ? Integer.parseInt(args[1]) : 4242;
    Path root = Paths.get(rootFolder);
    HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
    List<Path> discovered = Contexts.discoverContexts(root);
    discovered.stream().forEach(p -> Contexts.create(server, p));
    server.start();
    System.out.println("nano started in: " + (System.currentTimeMillis() - start) + "ms at port: " + port);
}
 
Example 6
Source File: ServerTableSizeReaderTest.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private HttpServer startServer(int port, HttpHandler handler)
    throws IOException {
  final HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
  server.createContext(URI_PATH, handler);
  new Thread(new Runnable() {
    @Override
    public void run() {
      server.start();
    }
  }).start();
  return server;
}
 
Example 7
Source File: MultiAuthTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 8
Source File: bug4714674.java    From jdk8u-jdk 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 9
Source File: SimpleHttpServerJaxWsServiceExporter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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();
}
 
Example 10
Source File: HttpNegotiateServer.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 11
Source File: ClassLoad.java    From openjdk-8-source 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 12
Source File: Deadlock.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 {
    Handler handler = new Handler();
    InetSocketAddress addr = new InetSocketAddress (0);
    HttpServer server = HttpServer.create(addr, 0);
    HttpContext ctx = server.createContext("/test", handler);
    BasicAuthenticator a = new BasicAuthenticator("[email protected]") {
        @Override
        public boolean checkCredentials (String username, String pw) {
            return "fred".equals(username) && pw.charAt(0) == 'x';
        }
    };

    ctx.setAuthenticator(a);
    ExecutorService executor = Executors.newCachedThreadPool();
    server.setExecutor(executor);
    server.start ();
    java.net.Authenticator.setDefault(new MyAuthenticator());

    System.out.print("Deadlock: " );
    for (int i=0; i<2; i++) {
        Runner t = new Runner(server, i);
        t.start();
        t.join();
    }
    server.stop(2);
    executor.shutdown();
    if (error) {
        throw new RuntimeException("test failed error");
    }

    if (count != 2) {
        throw new RuntimeException("test failed count = " + count);
    }
    System.out.println("OK");

}
 
Example 13
Source File: MockMetadataStoreDirectoryServer.java    From helix with Apache License 2.0 5 votes vote down vote up
public void startServer() throws IOException {
  _server = HttpServer.create(new InetSocketAddress(_hostname, _mockServerPort), 0);
  generateContexts();
  _server.setExecutor(_executor);
  _server.start();
  LOG.info(
      "Started MockMetadataStoreDirectoryServer at " + _hostname + ":" + _mockServerPort + "!");
}
 
Example 14
Source File: Test.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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 15
Source File: UnmodifiableMaps.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
HttpServer startHttpServer() throws IOException {
    HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0);
    httpServer.createContext("/foo", new SimpleHandler());
    httpServer.start();
    return httpServer;
}
 
Example 16
Source File: B6299712.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void startHttpServer() throws IOException {
    server = HttpServer.create(new InetSocketAddress(0), 0);
    server.createContext("/", new DefaultHandler());
    server.createContext("/redirect", new RedirectHandler());
    server.start();
}
 
Example 17
Source File: HttpOnly.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
HttpServer startHttpServer() throws IOException {
    HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0);
    httpServer.createContext(URI_PATH, new SimpleHandler());
    httpServer.start();
    return httpServer;
}
 
Example 18
Source File: Basic.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
JarHttpServer(String docsDir) throws IOException {
    this.docsDir = docsDir;

    httpServer = HttpServer.create(new InetSocketAddress(0), 0);
    httpServer.createContext("/", this);
}
 
Example 19
Source File: B6401598.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) {
        try {
                server = HttpServer.create(new InetSocketAddress(0), 400);
                server.createContext("/server/", new MyHandler());
                exec = Executors.newFixedThreadPool(3);
                server.setExecutor(exec);
                port = server.getAddress().getPort();
                server.start();

                short counter;

                for (counter = 0; counter < 1000; counter++) {
                        HttpURLConnection connection = getHttpURLConnection(new URL("http://127.0.0.1:"+port+"/server/"), 10000);

                        OutputStream os = connection.getOutputStream();

                        DataOutputStream dos = new DataOutputStream(os);

                        dos.writeShort(counter);

                        dos.flush();
                        dos.close();

                        counter++;

                        InputStream is = connection.getInputStream();

                        DataInputStream dis = new DataInputStream(is);

                        short ret = dis.readShort();

                        dis.close();
                }
                System.out.println ("Stopping");
                server.stop (1);
                exec.shutdown();
        } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                server.stop (1);
                exec.shutdown();
        }
}
 
Example 20
Source File: KissVideoStreamServer.java    From megabasterd with GNU General Public License v3.0 3 votes vote down vote up
public void start(int port, String context) throws IOException {

        _main_panel.getView().updateKissStreamServerStatus(LabelTranslatorSingleton.getInstance().translate("Streaming server: ON (port ") + STREAMER_PORT + ")");

        HttpServer httpserver = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), port), 0);

        httpserver.createContext(context, this);

        httpserver.setExecutor(THREAD_POOL);

        httpserver.start();
    }