Java Code Examples for org.eclipse.jetty.server.handler.ResourceHandler#setBaseResource()

The following examples show how to use org.eclipse.jetty.server.handler.ResourceHandler#setBaseResource() . 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: ForbiddenWordUtilsTest.java    From es with Apache License 2.0 6 votes vote down vote up
@Ignore
@Test
public void testFetch() throws Exception {
    String input = "12test32";
    Assert.assertFalse(ForbiddenWordUtils.containsForbiddenWord(input));

    ForbiddenWordUtils.setForbiddenWordFetchURL("http://localhost:10090/forbidden-test.txt");
    ForbiddenWordUtils.setReloadInterval(500);
    ForbiddenWordUtils.initRemoteFetch();

    Server server = new Server(10090);
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setBaseResource(Resource.newClassPathResource("."));
    server.setHandler(resourceHandler);
    server.start();

    Thread.sleep(1500);

    Assert.assertTrue(ForbiddenWordUtils.containsForbiddenWord(input));

    server.stop();
}
 
Example 2
Source File: TestServer.java    From healenium-web with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeAll(ExtensionContext context) {
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setBaseResource(Resource.newClassPathResource(folder));
    resourceHandler.setWelcomeFiles(new String[]{"index.html"});
    resourceHandler.setDirectoriesListed(true);
    server = new Server(port);
    HandlerList handlers = new HandlerList(resourceHandler, new DefaultHandler());
    server.setHandler(handlers);
    try {
        server.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 3
Source File: JettyServer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private ContextHandler createDocsWebApp(final String contextPath) {
    try {
        final ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setDirectoriesListed(false);

        // load the docs directory
        final File docsDir = Paths.get("docs").toRealPath().toFile();
        final Resource docsResource = Resource.newResource(docsDir);

        // load the component documentation working directory
        final String componentDocsDirPath = props.getProperty(NiFiProperties.COMPONENT_DOCS_DIRECTORY, "work/docs/components");
        final File workingDocsDirectory = Paths.get(componentDocsDirPath).toRealPath().getParent().toFile();
        final Resource workingDocsResource = Resource.newResource(workingDocsDirectory);

        // load the rest documentation
        final File webApiDocsDir = new File(webApiContext.getTempDirectory(), "webapp/docs");
        if (!webApiDocsDir.exists()) {
            final boolean made = webApiDocsDir.mkdirs();
            if (!made) {
                throw new RuntimeException(webApiDocsDir.getAbsolutePath() + " could not be created");
            }
        }
        final Resource webApiDocsResource = Resource.newResource(webApiDocsDir);

        // create resources for both docs locations
        final ResourceCollection resources = new ResourceCollection(docsResource, workingDocsResource, webApiDocsResource);
        resourceHandler.setBaseResource(resources);

        // create the context handler
        final ContextHandler handler = new ContextHandler(contextPath);
        handler.setHandler(resourceHandler);

        logger.info("Loading documents web app with context path set to " + contextPath);
        return handler;
    } catch (Exception ex) {
        throw new IllegalStateException("Resource directory paths are malformed: " + ex.getMessage());
    }
}
 
Example 4
Source File: WebService.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public void addStaticResources(String basePath, String resourcePath) {
    ContextHandler capHandler = new ContextHandler();
    capHandler.setContextPath(basePath);
    ResourceHandler resHandler = new ResourceHandler();
    resHandler.setBaseResource(Resource.newClassPathResource(resourcePath));
    resHandler.setEtags(true);
    resHandler.setCacheControl(WebService.HANDLER_CACHE_CONTROL);
    capHandler.setHandler(resHandler);
    handlers.add(capHandler);
}
 
Example 5
Source File: TestSupport.java    From p3-batchrefine with Apache License 2.0 5 votes vote down vote up
private int startTransformServer() throws Exception {
    URL transforms = EngineTest.class.getClassLoader().getResource(
            "transforms");
    if (transforms == null) {
        Assert.fail();
    }

    int port = findFreePort();

    Server fileServer = new Server(port);

    ResourceHandler handler = new ResourceHandler();
    MimeTypes mimeTypes = handler.getMimeTypes();
    mimeTypes.addMimeMapping("json", "application/json; charset=UTF-8");

    handler.setDirectoriesListed(true);
    handler.setBaseResource(JarResource.newResource(transforms));

    HandlerList handlers = new HandlerList();
    handlers.addHandler(handler);
    handlers.addHandler(new DefaultHandler());

    fileServer.setHandler(handlers);
    fileServer.start();

    return port;
}
 
Example 6
Source File: OwlOntologyProducerFailFastTest.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
  server.setStopAtShutdown(true);
  ResourceHandler handler = new ResourceHandler();
  handler.setBaseResource(Resource.newClassPathResource("/ontologies/bad/"));
  server.setHandler(handler);
  server.start();
}
 
Example 7
Source File: OwlOntologyProducerTest.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
  server.setStopAtShutdown(true);
  ResourceHandler handler = new ResourceHandler();
  handler.setBaseResource(Resource.newClassPathResource("/ontologies/import/"));
  server.setHandler(handler);
  server.start();
}
 
Example 8
Source File: BatchOwlLoaderIT.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setup() throws Exception {
  server.setStopAtShutdown(true);
  ResourceHandler handler = new ResourceHandler();
  handler.setBaseResource(Resource.newClassPathResource("/ontologies/import/"));
  server.setHandler(handler);
  server.start();
}
 
Example 9
Source File: GerritRestClientTest.java    From gerrit-rest-java-client with Apache License 2.0 5 votes vote down vote up
public String startJetty(Class<? extends HttpServlet> loginServletClass) throws Exception {
    Server server = new Server(0);

    ResourceHandler resourceHandler = new ResourceHandler();
    MimeTypes mimeTypes = new MimeTypes();
    mimeTypes.addMimeMapping("json", "application/json");
    resourceHandler.setMimeTypes(mimeTypes);
    URL url = this.getClass().getResource(".");
    resourceHandler.setBaseResource(new FileResource(url));
    resourceHandler.setWelcomeFiles(new String[] {"changes.json", "projects.json", "account.json"});

    ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.addServlet(loginServletClass, "/login/");

    ServletContextHandler basicAuthContextHandler = new ServletContextHandler(ServletContextHandler.SECURITY);
    basicAuthContextHandler.setSecurityHandler(basicAuth("foo", "bar", "Gerrit Auth"));
    basicAuthContextHandler.setContextPath("/a");

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {
        servletContextHandler,
        resourceHandler,
        basicAuthContextHandler
    });
    server.setHandler(handlers);

    server.start();

    Connector connector = server.getConnectors()[0];
    String host = "localhost";
    int port = connector.getLocalPort();
    return String.format("http://%s:%s", host, port);
}
 
Example 10
Source File: AtlasAPIV2ServerEmulator.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void createServer() throws Exception {
    server = new Server();
    final ContextHandlerCollection handlerCollection = new ContextHandlerCollection();

    final ServletContextHandler staticContext = new ServletContextHandler();
    staticContext.setContextPath("/");

    final ServletContextHandler atlasApiV2Context = new ServletContextHandler();
    atlasApiV2Context.setContextPath("/api/atlas/v2/");

    handlerCollection.setHandlers(new Handler[]{staticContext, atlasApiV2Context});

    server.setHandler(handlerCollection);

    final ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setBaseResource(Resource.newClassPathResource("public", false, false));
    staticContext.setHandler(resourceHandler);

    final ServletHandler servletHandler = new ServletHandler();
    atlasApiV2Context.insertHandler(servletHandler);

    httpConnector = new ServerConnector(server);
    httpConnector.setPort(21000);

    server.setConnectors(new Connector[]{httpConnector});

    servletHandler.addServletWithMapping(TypeDefsServlet.class, "/types/typedefs/");
    servletHandler.addServletWithMapping(EntityBulkServlet.class, "/entity/bulk/");
    servletHandler.addServletWithMapping(EntityGuidServlet.class, "/entity/guid/*");
    servletHandler.addServletWithMapping(SearchByUniqueAttributeServlet.class, "/entity/uniqueAttribute/type/*");
    servletHandler.addServletWithMapping(SearchBasicServlet.class, "/search/basic/");
    servletHandler.addServletWithMapping(LineageServlet.class, "/debug/lineage/");

    notificationServerEmulator = new AtlasNotificationServerEmulator();
}
 
Example 11
Source File: Main.java    From selenium with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  Flags flags = new Flags();
  JCommander.newBuilder().addObject(flags).build().parse(args);

  Server server = new Server();
  ServerConnector connector = new ServerConnector(server);
  connector.setPort(flags.port);
  server.setConnectors(new Connector[] {connector });

  HandlerList handlers = new HandlerList();

  ContextHandler context = new ContextHandler();
  context.setContextPath("/tests");
  ResourceHandler testHandler = new ResourceHandler();
  testHandler.setBaseResource(Resource.newClassPathResource("/tests"));
  testHandler.setDirectoriesListed(true);
  context.setHandler(testHandler);
  handlers.addHandler(context);

  ContextHandler coreContext = new ContextHandler();
  coreContext.setContextPath("/core");
  ResourceHandler coreHandler = new ResourceHandler();
  coreHandler.setBaseResource(Resource.newClassPathResource("/core"));
  coreContext.setHandler(coreHandler);
  handlers.addHandler(coreContext);

  ServletContextHandler driverContext = new ServletContextHandler();
  driverContext.setContextPath("/");
  driverContext.addServlet(WebDriverServlet.class, "/wd/hub/*");
  handlers.addHandler(driverContext);

  server.setHandler(handlers);
  server.start();
}
 
Example 12
Source File: SSLUtilsTest.java    From athenz with Apache License 2.0 4 votes vote down vote up
private static JettyServer createHttpsJettyServer(boolean clientAuth) throws IOException {
    Server server = new Server();
    HttpConfiguration https_config = new HttpConfiguration();
    https_config.setSecureScheme("https");
    int port;
    try (ServerSocket socket = new ServerSocket(0)) {
        port = socket.getLocalPort();
    }
    https_config.setSecurePort(port);
    https_config.setOutputBufferSize(32768);

    SslContextFactory sslContextFactory = new SslContextFactory();
    File keystoreFile = new File(DEFAULT_SERVER_KEY_STORE);
    if (!keystoreFile.exists()) {
        throw new FileNotFoundException();
    }

    String trustStorePath = DEFAULT_CA_TRUST_STORE;
    File trustStoreFile = new File(trustStorePath);
    if (!trustStoreFile.exists()) {
        throw new FileNotFoundException();
    }

    sslContextFactory.setEndpointIdentificationAlgorithm(null);

    sslContextFactory.setTrustStorePath(trustStorePath);
    sslContextFactory.setTrustStoreType(DEFAULT_SSL_STORE_TYPE);
    sslContextFactory.setTrustStorePassword(DEFAULT_CERT_PWD);

    sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
    sslContextFactory.setKeyStoreType(DEFAULT_SSL_STORE_TYPE);
    sslContextFactory.setKeyStorePassword(DEFAULT_CERT_PWD);

    sslContextFactory.setProtocol(DEFAULT_SSL_PROTOCOL);
    sslContextFactory.setNeedClientAuth(clientAuth);

    ServerConnector https = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(https_config));
    https.setPort(port);
    https.setIdleTimeout(500000);
    server.setConnectors(new Connector[] { https });
    HandlerList handlers = new HandlerList();
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setBaseResource(Resource.newResource("."));
    handlers.setHandlers(new Handler[]
            { resourceHandler, new DefaultHandler() });
    server.setHandler(handlers);
    return new JettyServer(server, port);
}
 
Example 13
Source File: SentryWebServer.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
public SentryWebServer(List<EventListener> listeners, int port, Configuration conf) {
  this.port = port;
  server = new Server(port);
  ServletContextHandler servletContextHandler = new ServletContextHandler();
  ServletHolder servletHolder = new ServletHolder(AdminServlet.class);
  servletContextHandler.addServlet(servletHolder, "/*");

  for(EventListener listener:listeners) {
    servletContextHandler.addEventListener(listener);
  }

  ServletHolder confServletHolder = new ServletHolder(ConfServlet.class);
  servletContextHandler.addServlet(confServletHolder, "/conf");
  servletContextHandler.getServletContext()
      .setAttribute(ConfServlet.CONF_CONTEXT_ATTRIBUTE, conf);

  ResourceHandler resourceHandler = new ResourceHandler();
  resourceHandler.setDirectoriesListed(true);
  URL url = this.getClass().getResource(RESOURCE_DIR);
  try {
    resourceHandler.setBaseResource(Resource.newResource(url.toString()));
  } catch (IOException e) {
    LOGGER.error("Got exception while setBaseResource for Sentry Service web UI", e);
  }
  resourceHandler.setWelcomeFiles(new String[]{WELCOME_PAGE});
  ContextHandler contextHandler= new ContextHandler();
  contextHandler.setHandler(resourceHandler);

  ContextHandlerCollection contextHandlerCollection = new ContextHandlerCollection();
  contextHandlerCollection.setHandlers(new Handler[]{contextHandler, servletContextHandler});

  String authMethod = conf.get(ServerConfig.SENTRY_WEB_SECURITY_TYPE);
  if (!ServerConfig.SENTRY_WEB_SECURITY_TYPE_NONE.equals(authMethod)) {
    /**
     * SentryAuthFilter is a subclass of AuthenticationFilter and
     * AuthenticationFilter tagged as private and unstable interface:
     * While there are not guarantees that this interface will not change,
     * it is fairly stable and used by other projects (ie - Oozie)
     */
    FilterHolder filterHolder = servletContextHandler.addFilter(SentryAuthFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    filterHolder.setInitParameters(loadWebAuthenticationConf(conf));
  }

  server.setHandler(contextHandlerCollection);
}
 
Example 14
Source File: VertxPluginRegistryTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * Build and start a fake local Maven Repository server based on Jetty
 *
 * @throws Exception
 */
@BeforeClass
public static void BuildLocalMavenRepo() throws Exception {
    //This function create a Localhost fake Maven Repository, hosting a single Test Plugin

    //Get Test plugin file
    File sourcePlugin = new File("src/test/resources/io/apiman/gateway/platforms/vertx3/engine/plugin-with-policyDefs.war");
    if (!sourcePlugin.exists()) {
        throw new Exception("Failed to find test plugin war at: " + sourcePlugin.getAbsolutePath());
    }

    //Create Local Maven Repository folder
    File repoFolder = Files.createTempDirectory("MockedMavenRepo").toFile();

    //Define Test plugin coordinates
    PluginCoordinates coordinates = PluginCoordinates.fromPolicySpec(testPluginCoordinates);

    //Build Test Plugin path in local Maven Repository folder
    File PluginFile = new File(repoFolder, PluginUtils.getMavenPath(coordinates));
    PluginFile.getParentFile().mkdirs();

    //Copy Test Plugin war into repository
    FileUtils.copyFile(sourcePlugin, PluginFile);

    //Create local Maven Repository Web Server
    mavenServer = new Server();
    ServerConnector connector = new ServerConnector(mavenServer);
    // auto-bind to available port
    connector.setPort(0);
    connector.setHost("0.0.0.0");
    mavenServer.addConnector(connector);

    //Add classic ressource handler
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[]{"index.html"});
    PathResource pathResource = new PathResource(repoFolder);
    resourceHandler.setBaseResource(pathResource);

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]{resourceHandler, new DefaultHandler()});
    mavenServer.setHandler(handlers);

    //Start local Maven Repository Server
    mavenServer.start();

    // Determine Base URI for Server
    String host = connector.getHost();
    if (host == null || host == "0.0.0.0") host = "127.0.0.1";
    int port = connector.getLocalPort();
    mavenServerUri = new URI(String.format("http://%s:%d/", host, port));
}