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

The following examples show how to use com.sun.net.httpserver.HttpServer#setExecutor() . 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: ConsoleProxy.java    From cloudstack with Apache License 2.0 7 votes vote down vote up
private static void startupHttpMain() {
    try {
        ConsoleProxyServerFactory factory = getHttpServerFactory();
        if (factory == null) {
            s_logger.error("Unable to load HTTP server factory");
            System.exit(1);
        }

        HttpServer server = factory.createHttpServerInstance(httpListenPort);
        server.createContext("/getscreen", new ConsoleProxyThumbnailHandler());
        server.createContext("/resource/", new ConsoleProxyResourceHandler());
        server.createContext("/ajax", new ConsoleProxyAjaxHandler());
        server.createContext("/ajaximg", new ConsoleProxyAjaxImageHandler());
        server.setExecutor(new ThreadExecutor()); // creates a default executor
        server.start();

        ConsoleProxyNoVNCServer noVNCServer = getNoVNCServer();
        noVNCServer.start();

    } catch (Exception e) {
        s_logger.error(e.getMessage(), e);
        System.exit(1);
    }
}
 
Example 2
Source File: XMLFieldConfigHelperTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
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 3
Source File: HTTPServer.java    From learnjavabug with MIT License 6 votes vote down vote up
public static void run(String[] args) {
  int port = PORT;
  String context = "/";
  String clazz = "Calc.class";
  if (args != null && args.length > 0) {
    port = Integer.parseInt(args[0]);
    context = args[1];
    clazz = args[2];
  }
  HttpServerProvider provider = HttpServerProvider.provider();
  HttpServer httpserver = null;
  try {
    httpserver = provider.createHttpServer(new InetSocketAddress(port), 100);
  } catch (IOException e) {
    e.printStackTrace();
  }
  //监听端口8080,

  httpserver.createContext(context, new RestGetHandler(clazz));
  httpserver.setExecutor(null);
  httpserver.start();
  System.out.println("server started");
}
 
Example 4
Source File: WebServerWithDelegatedCredentials.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Main function which runs the actual sample.
 * @param authFile the auth file backing the web server
 * @return true if sample runs successfully
 * @throws Exception exceptions running the server
 */
public static boolean runSample(File authFile) throws Exception {
    final String redirectUrl = "http://localhost:8000";
    final ExecutorService executor = Executors.newCachedThreadPool();

    try {
        DelegatedTokenCredentials credentials = DelegatedTokenCredentials.fromFile(authFile, redirectUrl);

        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
        HttpContext context = server.createContext("/", new MyHandler());
        context.getAttributes().put("credentials", credentials);
        server.setExecutor(Executors.newCachedThreadPool()); // creates a default executor
        server.start();

        // Use a browser to login within a minute
        Thread.sleep(60000);
        return true;
    } finally {
        executor.shutdown();
    }
}
 
Example 5
Source File: RestApiCallDemoClient.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 6
Source File: Mapper_MappingFile_URL_Test.java    From rmlmapper-java with MIT License 6 votes vote down vote up
@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 7
Source File: Server.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // parse arguments
    String settings = args.length > 0 ? args[0] : "";
    int port = args.length > 1 ? Integer.parseInt(args[1]) : 8080;
    if (settings.contains("debug"))
        System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "DEBUG");
    // create server
    HttpServer server = HttpServer.create(new InetSocketAddress(port), 1024 * 8);
    server.setExecutor(Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()));
    // add context handlers
    server.createContext("/plaintext", createPlaintextHandler());
    server.createContext("/json", createJSONHandler());
    if (settings.contains("postgres")) {
        DataSource ds = createPostgresDataSource();
        server.createContext("/fortunes", createFortunesHandler(ds));
    }
    // start server
    server.start();
}
 
Example 8
Source File: VulnerableHTTPServer.java    From JavaDeserH2HC with MIT License 5 votes vote down vote up
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();
}
 
Example 9
Source File: PilosaClientIT.java    From java-pilosa with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private HttpServer runImportFailsHttpServer() {
    final int port = 15999;
    try {
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
        server.createContext("/internal/fragment/nodes", new FragmentNodesHandler());
        server.setExecutor(null);
        server.start();
        return server;
    } catch (IOException ex) {
        fail(ex.getMessage());
    }
    return null;
}
 
Example 10
Source File: PilosaClientIT.java    From java-pilosa with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 11
Source File: MissingTrailingSpace.java    From openjdk-jdk9 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 12
Source File: MissingTrailingSpace.java    From hottub 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 13
Source File: ConsoleProxy.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private static void startupHttpCmdPort() {
    try {
        s_logger.info("Listening for HTTP CMDs on port " + httpCmdListenPort);
        HttpServer cmdServer = HttpServer.create(new InetSocketAddress(httpCmdListenPort), 2);
        cmdServer.createContext("/cmd", new ConsoleProxyCmdHandler());
        cmdServer.setExecutor(new ThreadExecutor()); // creates a default executor
        cmdServer.start();
    } catch (Exception e) {
        s_logger.error(e.getMessage(), e);
        System.exit(1);
    }
}
 
Example 14
Source File: PilosaClientIT.java    From java-pilosa with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private HttpServer runContentSizeLyingHttpServer400(String path) {
    final int port = 15999;
    try {
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
        server.createContext(path, new ContentSizeLyingHandler(400));
        server.setExecutor(null);
        server.start();
        return server;
    } catch (IOException ex) {
        fail(ex.getMessage());
    }
    return null;
}
 
Example 15
Source File: APIErrors.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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 16
Source File: IOTest.java    From boon with Apache License 2.0 4 votes vote down vote up
@Test
public void testReadAllFromHttp() throws Exception {

    HttpServer server = HttpServer.create( new InetSocketAddress( 9777 ), 0 );
    server.createContext( "/test", new MyHandler() );
    server.setExecutor( null ); // creates a default executor
    server.start();

    Thread.sleep( 10 );

    String content = IO.read( "http://localhost:9777/test" );


    List<String> lines = IO.readLines( new StringReader( content ) );
    assertLines( lines );

}
 
Example 17
Source File: HTTPTest.java    From boon with Apache License 2.0 4 votes vote down vote up
@Test ( expected = RuntimeException.class )
public void testSad() throws Exception {

    HttpServer server = HttpServer.create( new InetSocketAddress( 9213 ), 0 );
    server.createContext( "/test", new MyHandler() );
    server.setExecutor( null ); // creates a default executor
    server.start();

    Thread.sleep( 10 );


    Map<String, String> headers = map( "foo", "bar", "fun", "sun" );

    String response = HTTP.postWithContentType( "http://localhost:9213/foo", headers, "text/plain", "hi mom" );

    System.out.println( response );

    assertTrue( response.contains( "hi mom" ) );
    assertTrue( response.contains( "Fun=[sun], Foo=[bar]" ) );

    Thread.sleep( 10 );

    server.stop( 0 );


}
 
Example 18
Source File: UrlServer.java    From Learn-Java-12-Programming with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(3333), 0);
    server.createContext("/something", new PostHandler());
    server.setExecutor(null);
    server.start();
}
 
Example 19
Source File: HTTPTest.java    From boon with Apache License 2.0 4 votes vote down vote up
@Test
public void testPostForm() throws Exception {

    HttpServer server = HttpServer.create( new InetSocketAddress( 9220 ), 0 );
    server.createContext( "/test", new MyHandler() );
    server.setExecutor( null ); // creates a default executor
    server.start();

    Thread.sleep( 10 );


    String response = HTTP.postForm( "http://localhost:9220/test",
            Collections.EMPTY_MAP,
            map( "hI", ( Object ) "hi-mom", "image", new byte[]{ 1, 2, 3 } )
    );

    boolean ok = true;
    ok |= response.startsWith( "hI=hi-mom&image=%01%02%03" ) ||
            die( "encoding did not work --" + response + "--" );

    Thread.sleep( 10 );

    server.stop( 0 );


}