类org.apache.http.impl.bootstrap.ServerBootstrap源码实例Demo

下面列出了怎么用org.apache.http.impl.bootstrap.ServerBootstrap的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: servicecomb-java-chassis   文件: DownloadSchema.java
public DownloadSchema() throws IOException {
  FileUtils.deleteQuietly(tempDir);
  FileUtils.forceMkdir(tempDir);

  // for download from net stream case
  server = ServerBootstrap
      .bootstrap()
      .setListenerPort(0)
      .registerHandler("/download/netInputStream", (req, resp, context) -> {
        String uri = req.getRequestLine().getUri();
        String query = URI.create(uri).getQuery();
        int idx = query.indexOf('=');
        String content = query.substring(idx + 1);
        content = URLDecoder.decode(content, StandardCharsets.UTF_8.name());
        resp.setEntity(new StringEntity(content, StandardCharsets.UTF_8.name()));
      }).create();
  server.start();
}
 
/**
 * Starts the HTTP server.
 *
 * @return the listening port.
 */
static int start () throws IOException
{

   server = ServerBootstrap.bootstrap ().registerHandler ("*",
         new HttpRequestHandler ()
         {

            @Override
            public void handle (HttpRequest request, HttpResponse response,
                  HttpContext context)
                  throws HttpException, IOException
            {

               response.setStatusCode (HttpStatus.SC_OK);
               response.setEntity (new StringEntity ("0123456789"));
            }
         })
         .create ();
   server.start ();

   return server.getLocalPort ();
}
 
源代码3 项目: brooklyn-server   文件: TestHttpServer.java
public TestHttpServer start() {
    checkNotStarted();

    HttpProcessor httpProcessor = new ImmutableHttpProcessor(requestInterceptors, responseInterceptors);
    int port = Networking.nextAvailablePort(basePort);
    ServerBootstrap bootstrap = ServerBootstrap.bootstrap()
        .setListenerPort(port)
        .setLocalAddress(getLocalAddress())
        .setHttpProcessor(httpProcessor);

    for (HandlerTuple tuple : handlers) {
        bootstrap.registerHandler(tuple.path, tuple.handler);
    }
    server = bootstrap.create();

    try {
        server.start();
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    }

    return this;
}
 
private void givenEcsMetadataService(String containerCredentialsUri, String accessKeyId, String secretAccessKey, String sessionToken) throws IOException {
    httpServer = ServerBootstrap.bootstrap()
            .registerHandler("*", (request, response, context) -> {
                System.out.println("REQUEST: " + request.getRequestLine());
                if (containerCredentialsUri.matches(request.getRequestLine().getUri())) {
                    response.setEntity(new StringEntity(gsonBuilder.create().toJson(ImmutableMap.of(
                            "AccessKeyId", accessKeyId,
                            "SecretAccessKey", secretAccessKey,
                            "Token", sessionToken
                    ))));
                } else {
                    response.setStatusCode(SC_NOT_FOUND);
                }
            })
            .create();
    httpServer.start();
}
 
@Test
public void httpsTestWithoutTLSServer() throws Exception {

	TestHttpHandler handler = new TestHttpHandler();

	server = ServerBootstrap.bootstrap()
			.setListenerPort(8081)
			.setServerInfo("Test/1.1")
			.registerHandler("*", handler)
			.create();

	server.start();

	String url = "https://localhost:8081/endpoint";

	Settings settings = Settings.builder()
			.put("opendistro_security.audit.config.webhook.url", url)
			.put("opendistro_security.audit.config.webhook.format", "slack")
			.put("path.home", ".")
               .put("opendistro_security.ssl.transport.truststore_filepath",
                       FileHelper.getAbsoluteFilePathFromClassPath("auditlog/truststore.jks"))
			.build();

	LoggingSink fallback =  new LoggingSink("test", Settings.EMPTY, null, null);;
	WebhookSink auditlog = new WebhookSink("name", settings, ConfigConstants.OPENDISTRO_SECURITY_AUDIT_CONFIG_DEFAULT, null, fallback);
	AuditMessage msg = MockAuditMessageFactory.validAuditMessage();
	auditlog.store(msg);
	Assert.assertTrue(handler.method == null);
	Assert.assertTrue(handler.body == null);
	Assert.assertTrue(handler.uri == null);
	// ... so message must be stored in fallback
	Assert.assertEquals(1, fallback.messages.size());
	Assert.assertEquals(msg, fallback.messages.get(0));
	server.shutdown(3l, TimeUnit.SECONDS);
}
 
@Test
   public void httpsTestPemContentEndpoint() throws Exception {

       TestHttpHandler handler = new TestHttpHandler();

       server = ServerBootstrap.bootstrap()
               .setListenerPort(8086)
               .setServerInfo("Test/1.1")
               .setSslContext(createSSLContext())
               .registerHandler("*", handler)
               .create();

       server.start();
       AuditMessage msg = MockAuditMessageFactory.validAuditMessage();
       LoggingSink fallback =  new LoggingSink("test", Settings.EMPTY, null, null);

       String url = "https://localhost:8086/endpoint";

       // test  with filecontent
       handler.reset();
       Settings settings = Settings.builder()
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.url", url)
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.format", "jSoN")
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.ssl.pemtrustedcas_content", FileHelper.loadFile("auditlog/root-ca.pem"))
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.ssl.verify", true)
               .put("path.home", ".")
               .build();

       AuditLogSink auditlog = new WebhookSink("name", settings, "opendistro_security.audit.endpoints.endpoint1.config", null, fallback);
       auditlog.store(msg);
       Assert.assertTrue(handler.method.equals("POST"));
       Assert.assertTrue(handler.body != null);
       Assert.assertTrue(handler.body.contains("{"));
       assertStringContainsAllKeysAndValues(handler.body);



       server.shutdown(3l, TimeUnit.SECONDS);
}
 
@BeforeEach
public void setUp() throws IOException {
    validationHandler = new HTTPTestValidationHandler(10);
    byte[] ipAddr = new byte[]{127, 0, 0, 1};
    InetAddress localhost = InetAddress.getByAddress(ipAddr);
    localServer = ServerBootstrap.bootstrap()
            .setLocalAddress(localhost)
            .setListenerPort(HTTP_PORT)
            .registerHandler("/ckc", validationHandler)
            .create();

    localServer.start();
}
 
源代码8 项目: syndesis   文件: HttpConnectorVerifierTest.java
@Before
public void setUp() throws Exception {
    localServer = ServerBootstrap.bootstrap()
        .setHttpProcessor(getHttpProcessor())
        .registerHandler("/", new BasicValidationHandler("GET", null, null, null))
        .registerHandler("/withPath", new BasicValidationHandler("GET", null, null, null))
        .registerHandler("/with/nested/path", new BasicValidationHandler("GET", null, null, null))
        .create();

    localServer.start();
}
 
源代码9 项目: Photato   文件: Photato.java
private static HttpServer getDefaultServer(Path folderRoot) {
    return ServerBootstrap.bootstrap()
            .setListenerPort(PhotatoConfig.serverPort)
            .setServerInfo(serverName)
            .setSocketConfig(getSocketConfig())
            .setExceptionLogger(new StdErrorExceptionLogger())
            .registerHandler("*", new LoadingHandler(folderRoot))
            .create();
}
 
源代码10 项目: curly   文件: TestWebServer.java
private TestWebServer(int port) throws IOException, InterruptedException {
    this.port=port;
    ServerBootstrap bootstrap = ServerBootstrap.bootstrap();
    bootstrap.setListenerPort(port);
    bootstrap.setServerInfo("Test/1.1");
    bootstrap.setSocketConfig(SocketConfig.DEFAULT);
    bootstrap.registerHandler("*", this::handleHttpRequest);
    server = bootstrap.create();
    server.start();
}
 
源代码11 项目: james-project   文件: SerialiseToHTTPTest.java
@BeforeAll
static void setupServer() throws MessagingException, IOException {
    mapper = new UriHttpRequestHandlerMapper();

    SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(50000).build();
    server = ServerBootstrap.bootstrap().setListenerPort(0).setSocketConfig(socketConfig)
            .setExceptionLogger(ExceptionLogger.NO_OP).setHandlerMapper(mapper).create();

    server.start();

}
 
源代码12 项目: james-project   文件: HeadersToHTTPTest.java
@BeforeAll
static void setupServer() throws Exception {
    mapper = new UriHttpRequestHandlerMapper();

    SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(50000).build();
    server = ServerBootstrap.bootstrap().setListenerPort(0).setSocketConfig(socketConfig)
            .setExceptionLogger(ExceptionLogger.NO_OP).setHandlerMapper(mapper).create();

    server.start();
}
 
@Test
public void testTlsConfigurationNoFallback() throws Exception {

	TestHttpHandler handler = new TestHttpHandler();

	server = ServerBootstrap.bootstrap().setListenerPort(8083).setServerInfo("Test/1.1").setSslContext(createSSLContext()).registerHandler("*", handler).create();

	server.start();

	Builder builder = Settings.builder().loadFromPath(FileHelper.getAbsoluteFilePathFromClassPath("auditlog/endpoints/sink/configuration_tls.yml"));
	builder.put("path.home", "/");

	// replace some values with absolute paths for unit tests
	builder.put("opendistro_security.audit.config.webhook.ssl.pemtrustedcas_filepath", FileHelper.getAbsoluteFilePathFromClassPath("auditlog/root-ca.pem"));
	builder.put("opendistro_security.audit.endpoints.endpoint1.config.webhook.ssl.pemtrustedcas_filepath", FileHelper.getAbsoluteFilePathFromClassPath("auditlog/root-ca.pem"));
	builder.put("opendistro_security.audit.endpoints.endpoint2.config.webhook.ssl.pemtrustedcas_content", FileHelper.loadFile("auditlog/root-ca.pem"));

	SinkProvider provider = new SinkProvider(builder.build(), null, null, null);
	WebhookSink defaultSink = (WebhookSink) provider.defaultSink;
	Assert.assertEquals(true, defaultSink.verifySSL);

	AuditMessage msg = MockAuditMessageFactory.validAuditMessage();
	provider.allSinks.get("endpoint1").store(msg);

	Assert.assertTrue(handler.method.equals("POST"));
       Assert.assertTrue(handler.body != null);
       Assert.assertTrue(handler.body.contains("{"));
       assertStringContainsAllKeysAndValues(handler.body);

	handler.reset();

	provider.allSinks.get("endpoint2").store(msg);

	Assert.assertTrue(handler.method.equals("POST"));
       Assert.assertTrue(handler.body != null);
       Assert.assertTrue(handler.body.contains("{"));
       assertStringContainsAllKeysAndValues(handler.body);

	handler.reset();

	provider.defaultSink.store(msg);

	Assert.assertTrue(handler.method.equals("POST"));
       Assert.assertTrue(handler.body != null);
       Assert.assertTrue(handler.body.contains("{"));
       assertStringContainsAllKeysAndValues(handler.body);

       server.stop();
}
 
@Test
  public void httpsTest() throws Exception {

      TestHttpHandler handler = new TestHttpHandler();

      server = ServerBootstrap.bootstrap()
              .setListenerPort(8090)
              .setServerInfo("Test/1.1")
              .setSslContext(createSSLContext())
              .registerHandler("*", handler)
              .create();

      server.start();
      AuditMessage msg = MockAuditMessageFactory.validAuditMessage();

      String url = "https://localhost:8090/endpoint";

      // try with ssl verification on, no trust ca, must fail
      Settings settings = Settings.builder()
              .put("opendistro_security.audit.config.webhook.url", url)
              .put("opendistro_security.audit.config.webhook.format", "slack")
              .put("path.home", ".")
              .put("opendistro_security.audit.config.webhook.ssl.verify", true)
              .build();

LoggingSink fallback =  new LoggingSink("test", Settings.EMPTY, null, null);
WebhookSink auditlog = new WebhookSink("name", settings, ConfigConstants.OPENDISTRO_SECURITY_AUDIT_CONFIG_DEFAULT, null, fallback);
      auditlog.store(msg);
      Assert.assertNull(handler.method);
      Assert.assertNull(handler.body);
      Assert.assertNull(handler.body);
// message must be stored in fallback
Assert.assertEquals(1, fallback.messages.size());
Assert.assertEquals(msg, fallback.messages.get(0));

      // disable ssl verification, no ca, call must succeed
      handler.reset();
      settings = Settings.builder()
              .put("opendistro_security.audit.config.webhook.url", url)
              .put("opendistro_security.audit.config.webhook.format", "jSoN")
              .put("opendistro_security.audit.config.webhook.ssl.verify", false)
              .put("path.home", ".")
              .build();
      auditlog = new WebhookSink("name", settings, ConfigConstants.OPENDISTRO_SECURITY_AUDIT_CONFIG_DEFAULT, null, fallback);
      auditlog.store(msg);
      Assert.assertTrue(handler.method.equals("POST"));
      Assert.assertTrue(handler.body != null);
      Assert.assertTrue(handler.body.contains("{"));
      assertStringContainsAllKeysAndValues(handler.body);

      // enable ssl verification, provide correct trust ca, call must succeed
      handler.reset();
      settings = Settings.builder()
              .put("opendistro_security.audit.config.webhook.url", url)
              .put("opendistro_security.audit.config.webhook.format", "jSoN")
              .put("opendistro_security.ssl.transport.truststore_filepath", FileHelper.getAbsoluteFilePathFromClassPath("auditlog/truststore.jks"))
              .put("opendistro_security.audit.config.webhook.ssl.verify", true)
              .put("path.home", ".")
              .build();
      auditlog = new WebhookSink("name", settings, ConfigConstants.OPENDISTRO_SECURITY_AUDIT_CONFIG_DEFAULT, null, fallback);
      auditlog.store(msg);
      Assert.assertTrue(handler.method.equals("POST"));
      Assert.assertTrue(handler.body != null);
      Assert.assertTrue(handler.body.contains("{"));
      assertStringContainsAllKeysAndValues(handler.body);

      // enable ssl verification, provide wrong trust ca, call must succeed
      handler.reset();
      settings = Settings.builder()
              .put("opendistro_security.audit.config.webhook.url", url)
              .put("opendistro_security.audit.config.webhook.format", "jSoN")
              .put("opendistro_security.ssl.transport.truststore_filepath", FileHelper.getAbsoluteFilePathFromClassPath("auditlog/truststore_fail.jks"))
              .put("opendistro_security.audit.config.webhook.ssl.verify", true)
              .put("path.home", ".")
              .build();
      auditlog = new WebhookSink("name", settings, ConfigConstants.OPENDISTRO_SECURITY_AUDIT_CONFIG_DEFAULT, null, fallback);
      auditlog.store(msg);
      Assert.assertNull(handler.method);
      Assert.assertNull(handler.body);
      Assert.assertNull(handler.body);

      server.shutdown(3l, TimeUnit.SECONDS);
  }
 
@Test
   public void httpsTestPemEndpoint() throws Exception {

       TestHttpHandler handler = new TestHttpHandler();

       server = ServerBootstrap.bootstrap()
               .setListenerPort(8091)
               .setServerInfo("Test/1.1")
               .setSslContext(createSSLContext())
               .registerHandler("*", handler)
               .create();

       server.start();
       AuditMessage msg = MockAuditMessageFactory.validAuditMessage();
       LoggingSink fallback =  new LoggingSink("test", Settings.EMPTY, null, null);

       String url = "https://localhost:8091/endpoint";

       // test default with filepath
       handler.reset();
       Settings settings = Settings.builder()
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.url", url)
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.format", "jSoN")
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.ssl.pemtrustedcas_filepath", FileHelper.getAbsoluteFilePathFromClassPath("auditlog/root-ca.pem"))
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.ssl.verify", true)
               .put("path.home", ".")
               .build();
       AuditLogSink auditlog = new WebhookSink("name", settings, "opendistro_security.audit.endpoints.endpoint1.config", null, fallback);
       auditlog.store(msg);
       Assert.assertTrue(handler.method.equals("POST"));
       Assert.assertTrue(handler.body != null);
       Assert.assertTrue(handler.body.contains("{"));
       assertStringContainsAllKeysAndValues(handler.body);

       // test default with missing filepath and fallback to correct Security settings
       handler.reset();
       settings = Settings.builder()
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.url", url)
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.format", "jSoN")
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.ssl.verify", true)
               .put("opendistro_security.ssl.transport.truststore_filepath", FileHelper.getAbsoluteFilePathFromClassPath("auditlog/truststore.jks"))
               .put("path.home", ".")
               .build();
       auditlog = new WebhookSink("name", settings, "opendistro_security.audit.endpoints.endpoint1.config", null, fallback);
       auditlog.store(msg);
       Assert.assertTrue(handler.method.equals("POST"));
       Assert.assertTrue(handler.body != null);
       Assert.assertTrue(handler.body.contains("{"));
       assertStringContainsAllKeysAndValues(handler.body);

       // test default with wrong filepath and fallback to wrong Security settings
       handler.reset();
       settings = Settings.builder()
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.url", url)
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.format", "jSoN")
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.ssl.verify", true)
               .put("opendistro_security.ssl.transport.truststore_filepath", FileHelper.getAbsoluteFilePathFromClassPath("auditlog/truststore_fail.jks"))
               .put("path.home", ".")
               .build();
       auditlog = new WebhookSink("name", settings, "opendistro_security.audit.endpoints.endpoint1.config", null, fallback);
       auditlog.store(msg);
       Assert.assertNull(handler.method);
       Assert.assertNull(handler.body);
       Assert.assertNull(handler.body);

       // test default with wrong/no filepath and no fallback to Security settings, must fail
       handler.reset();
       settings = Settings.builder()
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.url", url)
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.format", "jSoN")
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.ssl.verify", true)
               .put("path.home", ".")
               .build();
       auditlog = new WebhookSink("name", settings, "opendistro_security.audit.endpoints.endpoint1.config", null, fallback);
       auditlog.store(msg);
       Assert.assertNull(handler.method);
       Assert.assertNull(handler.body);
       Assert.assertNull(handler.body);

       // test default with existing but wrong PEM, no fallback
       handler.reset();
       settings = Settings.builder()
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.url", url)
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.format", "jSoN")
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.ssl.verify", true)
               .put("opendistro_security.audit.endpoints.endpoint1.config.webhook.ssl.pemtrustedcas_filepath", FileHelper.getAbsoluteFilePathFromClassPath("auditlog/spock.crt.pem"))
               .put("path.home", ".")
               .build();
       auditlog = new WebhookSink("name", settings, "opendistro_security.audit.endpoints.endpoint1.config", null, fallback);
       auditlog.store(msg);
       Assert.assertNull(handler.method);
       Assert.assertNull(handler.body);
       Assert.assertNull(handler.body);

       server.shutdown(3l, TimeUnit.SECONDS);
}
 
源代码16 项目: Photato   文件: Photato.java
public static void main(String[] args) throws Exception {
    //Set up this way so we can change default formatter for everyone
    System.setProperty("java.util.logging.SimpleFormatter.format", 
        "%1$tF %1$tT %4$s %2$s %5$s%6$s%n");

    LOGGER = Logger.getLogger( Photato.class.getName() );
    
    if (args.length < 1) {
        LOGGER.log( Level.SEVERE, "Usage: <picturesRootFolder> [cacheFolder] [configFolder]");
        System.exit(-1);
    }

    FileSystem fileSystem = FileSystems.getDefault();
    Path rootFolder = getRootFolder(fileSystem, args[0]);
    String cacheRootFolder = (args.length >= 2 ? args[1] : "cache");
    String thumbnailCacheFolder = cacheRootFolder + "/thumbnails";
    String fullscreenCacheFolder = cacheRootFolder + "/fullscreen";
    String metadataCacheLocation = cacheRootFolder + "/metadata.cache";
    String extractedPicturesCacheFolder = cacheRootFolder + "/extracted";
    String configFile = (args.length >= 3 ? args[2] : ".") + "/photato.ini";

    PhotatoConfig.init(configFile);

    LOGGER.log(Level.INFO, "Starting photato");
    LOGGER.log(Level.INFO, "-- Config file: {0}", configFile);
    LOGGER.log(Level.INFO, "-- Cache file: {0}", cacheRootFolder);
    LOGGER.log(Level.INFO, "-- Pictures file: {0}", rootFolder);
    
    HttpServer server = getDefaultServer(fileSystem.getPath("www"));
    server.start();

    if (!Files.exists(fileSystem.getPath(cacheRootFolder))) {
        LOGGER.log(Level.INFO, "Creating cache folder");
        Files.createDirectory(fileSystem.getPath(cacheRootFolder));
    }

    HttpClient httpClient = HttpClientBuilder.create().setUserAgent(serverName).build();

    ExifToolDownloader.run(httpClient, fileSystem, PhotatoConfig.forceFfmpegToolsDownload);
    FfmpegDownloader.run(httpClient, fileSystem, PhotatoConfig.forceExifToolsDownload);

    ThumbnailGenerator thumbnailGenerator = new ThumbnailGenerator(fileSystem, rootFolder, thumbnailCacheFolder, extractedPicturesCacheFolder, PhotatoConfig.thumbnailHeight, PhotatoConfig.thumbnailQuality);
    IGpsCoordinatesDescriptionGetter gpsCoordinatesDescriptionGetter = new OSMGpsCoordinatesDescriptionGetter(httpClient, PhotatoConfig.addressElementsCount);
    MetadataAggregator metadataGetter = new MetadataAggregator(fileSystem, metadataCacheLocation, gpsCoordinatesDescriptionGetter);
    FullScreenImageGetter fullScreenImageGetter = new FullScreenImageGetter(fileSystem, rootFolder, fullscreenCacheFolder, extractedPicturesCacheFolder, PhotatoConfig.fullScreenPictureQuality, PhotatoConfig.maxFullScreenPictureWitdh, PhotatoConfig.maxFullScreenPictureHeight);

    PhotatoFilesManager photatoFilesManager = new PhotatoFilesManager(rootFolder, fileSystem, metadataGetter, thumbnailGenerator, fullScreenImageGetter, PhotatoConfig.prefixModeOnly, PhotatoConfig.indexFolderName, PhotatoConfig.useParallelPicturesGeneration);

    // Closing tmp server
    server.shutdown(5, TimeUnit.SECONDS);

    while (true) {
        try {
            server = ServerBootstrap.bootstrap()
                    .setListenerPort(PhotatoConfig.serverPort)
                    .setServerInfo(serverName)
                    .setSocketConfig(getSocketConfig())
                    .setExceptionLogger(new StdErrorExceptionLogger())
                    .registerHandler(Routes.rawVideosRootUrl + "/*", new VideoHandler(rootFolder, Routes.rawVideosRootUrl))
                    .registerHandler(Routes.rawPicturesRootUrl + "/*", new ImageHandler(rootFolder, Routes.rawPicturesRootUrl))
                    .registerHandler(Routes.fullScreenPicturesRootUrl + "/*", new ImageHandler(fileSystem.getPath(fullscreenCacheFolder), Routes.fullScreenPicturesRootUrl))
                    .registerHandler(Routes.thumbnailRootUrl + "/*", new ImageHandler(fileSystem.getPath(thumbnailCacheFolder), Routes.thumbnailRootUrl))
                    .registerHandler(Routes.listItemsApiUrl, new FolderListHandler(Routes.listItemsApiUrl, photatoFilesManager))
                    .registerHandler("/img/*", new ImageHandler(fileSystem.getPath("www/img"), "/img"))
                    .registerHandler("/js/*", new JsHandler(fileSystem.getPath("www/js"), "/js"))
                    .registerHandler("/css/*", new CssHandler(fileSystem.getPath("www/css"), "/css"))
                    .registerHandler("*", new DefaultHandler(fileSystem.getPath("www")))
                    .create();
            server.start();

            LOGGER.log(Level.INFO, "Server started http://{0}:{1}", new Object[] {getLocalIp(), server.getLocalPort()});
            server.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        } catch (IOException | InterruptedException ex) {
            // In case of port already binded
            LOGGER.log( Level.SEVERE, "Could not start the server ...");
            Thread.sleep(1000);
        }
    }
}
 
 类所在包
 类方法
 同包方法