Java Code Examples for org.eclipse.jetty.servlet.ServletContextHandler#setResourceBase()

The following examples show how to use org.eclipse.jetty.servlet.ServletContextHandler#setResourceBase() . 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: BQInternalWebServerTestFactory.java    From bootique with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
Server provideServer(Environment env, ShutdownManager shutdownManager) {
    Server server = new Server();

    ServerConnector connector = new ServerConnector(server);
    connector.setPort(12025);
    server.addConnector(connector);

    ServletContextHandler handler = new ServletContextHandler();
    handler.setContextPath("/");

    DefaultServlet servlet = new DefaultServlet();

    ServletHolder holder = new ServletHolder(servlet);
    handler.addServlet(holder, "/*");
    handler.setResourceBase(env.getProperty("bq.internaljetty.base"));

    server.setHandler(handler);

    shutdownManager.addShutdownHook(() -> {
        server.stop();
    });

    return server;
}
 
Example 2
Source File: StatsServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final Server server = new Server(8686);

    final ServletHolder staticHolder = new ServletHolder(new DefaultServlet());
    final ServletContextHandler staticContext = new ServletContextHandler();
    staticContext.setContextPath("/static");
    staticContext.addServlet(staticHolder, "/*");
    staticContext.setResourceBase(StatsServer.class.getResource("/web-ui").toURI().toString());

     // Register and map the dispatcher servlet
    final ServletHolder cxfServletHolder = new ServletHolder(new CXFServlet());
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addEventListener(new ContextLoaderListener());
    context.addServlet(cxfServletHolder, "/rest/*");
    context.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
    context.setInitParameter("contextConfigLocation", StatsConfig.class.getName());

    HandlerList handlers = new HandlerList();
    handlers.addHandler(staticContext);
    handlers.addHandler(context);

    server.setHandler(handlers);
    server.start();
    server.join();
}
 
Example 3
Source File: StatsServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final Server server = new Server(8686);

    final ServletHolder staticHolder = new ServletHolder(new DefaultServlet());
    final ServletContextHandler staticContext = new ServletContextHandler();
    staticContext.setContextPath("/static");
    staticContext.addServlet(staticHolder, "/*");
    staticContext.setResourceBase(StatsServer.class.getResource("/web-ui").toURI().toString());

     // Register and map the dispatcher servlet
    final CXFCdiServlet cxfServlet = new CXFCdiServlet();
    final ServletHolder cxfServletHolder = new ServletHolder(cxfServlet);
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addEventListener(new Listener());
    context.addEventListener(new BeanManagerResourceBindingListener());
    context.addServlet(cxfServletHolder, "/rest/*");

    HandlerList handlers = new HandlerList();
    handlers.addHandler(staticContext);
    handlers.addHandler(context);

    server.setHandler(handlers);
    server.start();
    server.join();
}
 
Example 4
Source File: HBaseSpanViewerServer.java    From incubator-retired-htrace with Apache License 2.0 6 votes vote down vote up
public int run(String[] args) throws Exception {
  URI uri = new URI("http://" + conf.get(HTRACE_VIEWER_HTTP_ADDRESS_KEY,
                                         HTRACE_VIEWER_HTTP_ADDRESS_DEFAULT));
  InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort());
  server = new Server(addr);
  ServletContextHandler root =
    new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
  server.setHandler(root);

  String resourceBase = server.getClass()
                              .getClassLoader()
                              .getResource("webapps/htrace")
                              .toExternalForm();
  root.setResourceBase(resourceBase);
  root.setWelcomeFiles(new String[]{"index.html"});
  root.addServlet(new ServletHolder(new DefaultServlet()),
                  "/");
  root.addServlet(new ServletHolder(new HBaseSpanViewerTracesServlet(conf)),
                  "/gettraces");
  root.addServlet(new ServletHolder(new HBaseSpanViewerSpansServlet(conf)),
                  "/getspans/*");

  server.start();
  server.join();
  return 0;
}
 
Example 5
Source File: EmbeddedJerseyModule.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Inject
public EmbeddedServer(SimulatedCloudGateway gateway) {
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    jettyServer = new Server(8099);
    jettyServer.setHandler(context);

    // Static content

    DefaultServlet staticContentServlet = new DefaultServlet();
    ServletHolder holder = new ServletHolder(staticContentServlet);
    holder.setInitOrder(1);
    context.addServlet(holder, "/static/*");
    context.setResourceBase(resolveStaticContentLocation());

    // Jersey

    DefaultResourceConfig config = new DefaultResourceConfig();
    config.getClasses().add(JsonMessageReaderWriter.class);
    config.getClasses().add(TitusExceptionMapper.class);
    config.getSingletons().add(new SimulatedAgentsServiceResource(gateway));

    ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(config));
    jerseyServlet.setInitOrder(0);
    context.addServlet(jerseyServlet, "/cloud/*");
}
 
Example 6
Source File: ScanWebServer.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
public ScanWebServer(final int port)
{
    // Configure Jetty to use java.util.logging, and don't announce that it's doing that
    System.setProperty("org.eclipse.jetty.util.log.announce", "false");
    System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.JavaUtilLog");

    server = new Server(port);

    final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);

    // Our servlets
    context.addServlet(ServerServlet.class, "/server/*");
    context.addServlet(ScansServlet.class, "/scans/*");
    context.addServlet(ScanServlet.class, "/scan/*");
    context.addServlet(SimulateServlet.class, "/simulate/*");

    // Serve static files from webroot to "/"
    context.setContextPath("/");
    context.setResourceBase(ScanServerInstance.class.getResource("/webroot").toExternalForm());
    context.addServlet(DefaultServlet.class, "/");

    server.setHandler(context);
}
 
Example 7
Source File: EngineWebServer.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
public EngineWebServer(final int port)
{
    // Configure Jetty to use java.util.logging, and don't announce that it's doing that
    System.setProperty("org.eclipse.jetty.util.log.announce", "false");
    System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.JavaUtilLog");

    server = new Server(port);

    final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);

    // Our servlets
    context.addServlet(MainServlet.class, "/main/*");
    context.addServlet(DisconnectedServlet.class, "/disconnected/*");
    context.addServlet(GroupsServlet.class, "/groups/*");
    context.addServlet(GroupServlet.class, "/group/*");
    context.addServlet(ChannelServlet.class, "/channel/*");
    context.addServlet(RestartServlet.class, "/restart/*");
    context.addServlet(StopServlet.class, "/stop/*");

    // Serve static files from webroot to "/"
    context.setContextPath("/");
    context.setResourceBase(EngineWebServer.class.getResource("/webroot").toExternalForm());
    context.addServlet(DefaultServlet.class, "/");

    server.setHandler(context);
}
 
Example 8
Source File: Bootstrap.java    From qmq with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    DynamicConfig config = DynamicConfigLoader.load("broker.properties");
    ServerWrapper wrapper = new ServerWrapper(config);
    Runtime.getRuntime().addShutdownHook(new Thread(wrapper::destroy));
    wrapper.start(true);

    if (wrapper.isSlave()) {
        final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        context.setResourceBase(System.getProperty("java.io.tmpdir"));
        final QueryMessageServlet servlet = new QueryMessageServlet(config, wrapper.getStorage());

        ServletHolder servletHolder = new ServletHolder(servlet);
        servletHolder.setAsyncSupported(true);
        context.addServlet(servletHolder, "/api/broker/message");

        final int port = config.getInt("slave.server.http.port", 8080);
        final Server server = new Server(port);
        server.setHandler(context);
        server.start();
        server.join();
    }
}
 
Example 9
Source File: Bootstrap.java    From qmq with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.setResourceBase(System.getProperty("java.io.tmpdir"));
    DynamicConfig config = DynamicConfigLoader.load("metaserver.properties");
    final ServerWrapper wrapper = new ServerWrapper(config);
    wrapper.start(context.getServletContext());

    context.addServlet(MetaServerAddressSupplierServlet.class, "/meta/address");
    context.addServlet(MetaManagementServlet.class, "/management");
    context.addServlet(SubjectConsumerServlet.class, "/subject/consumers");
    context.addServlet(OnOfflineServlet.class, "/onoffline");
    context.addServlet(SlaveServerAddressSupplierServlet.class, "/slave/meta");

    // TODO(keli.wang): allow set port use env
    int port = config.getInt("meta.server.discover.port", 8080);
    final Server server = new Server(port);
    server.setHandler(context);
    server.start();
    server.join();
}
 
Example 10
Source File: TestServer.java    From chipster with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	Server jettyInstance = new Server();
	ServerConnector connector = new ServerConnector(jettyInstance);
	connector.setPort(9080);
	SslContextFactory sslContext = new SslContextFactory("keystore.ks");
	sslContext.setKeyStorePassword("microarray");
	ServerConnector sslConnector = new ServerConnector(jettyInstance);
	sslConnector.setPort(9443);
	jettyInstance.setConnectors(new Connector[]{ connector, sslConnector });

	ServletContextHandler root = new ServletContextHandler(jettyInstance, "/", false, false);
	root.setResourceBase("/tmp/test-root");
	root.addServlet(new ServletHolder(new UploadServlet()), "/*");
	jettyInstance.start();
}
 
Example 11
Source File: Bootstrap.java    From qmq with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.setResourceBase(System.getProperty("java.io.tmpdir"));
    DynamicConfig config = DynamicConfigLoader.load("gateway.properties");

    context.addServlet(PullServlet.class, "/pull/*");
    context.addServlet(SendServlet.class, "/send/*");

    int port = config.getInt("gateway.port", 8080);
    final Server server = new Server(port);
    server.setHandler(context);
    server.start();
    server.join();
}
 
Example 12
Source File: AbstractDownloadTest.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Before
public void startServer()
    throws Exception
{

    System.setProperty( "redback.admin.creation.file", "target/auto-admin-creation.properties" );

    server = new Server();
    serverConnector = new ServerConnector( server, new HttpConnectionFactory() );
    server.addConnector( serverConnector );

    ServletHolder servletHolder = new ServletHolder( new CXFServlet() );
    ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SESSIONS );
    context.setResourceBase( SystemUtils.JAVA_IO_TMPDIR );
    context.setSessionHandler( new SessionHandler() );
    context.addServlet( servletHolder, "/" + getRestServicesPath() + "/*" );
    context.setInitParameter( "contextConfigLocation", getSpringConfigLocation() );
    context.addEventListener( new ContextLoaderListener() );

    ServletHolder servletHolderRepo = new ServletHolder( new RepositoryServlet() );
    context.addServlet( servletHolderRepo, "/repository/*" );

    server.setHandler( context );
    server.start();
    port = serverConnector.getLocalPort();
    log.info( "start server on port {}", this.port );

    User user = new User();
    user.setEmail( "[email protected]" );
    user.setFullName( "the root user" );
    user.setUsername( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME );
    user.setPassword( FakeCreateAdminService.ADMIN_TEST_PWD );

    getUserService( null ).createAdminUser( user );


}
 
Example 13
Source File: YanagishimaServer.java    From yanagishima with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Properties properties = loadProperties(args, new OptionParser());
    YanagishimaConfig config = new YanagishimaConfig(properties);

    Injector injector = createInjector(properties);

    createTables(injector.getInstance(TinyORM.class), config.getDatabaseType());

    Server server = new Server(config.getServerPort());
    server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", -1);

    ServletContextHandler servletContextHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    servletContextHandler.addFilter(new FilterHolder(new YanagishimaFilter(config.corsEnabled(), config.getAuditHttpHeaderName())), "/*", EnumSet.of(DispatcherType.REQUEST));
    servletContextHandler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    servletContextHandler.addServlet(DefaultServlet.class, "/");
    servletContextHandler.setResourceBase(properties.getProperty("web.resource.dir", "web"));

    LOGGER.info("Yanagishima Server started...");
    server.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            LOGGER.info("Shutting down Yanagishima Server...");
            try {
                server.stop();
                server.destroy();
            } catch (Exception e) {
                LOGGER.error("Error while shutting down Yanagishima Server", e);
            }
        }
    });
    LOGGER.info("Yanagishima Server running port " + config.getServerPort());
}
 
Example 14
Source File: DownloadRemoteIndexTaskTest.java    From archiva with Apache License 2.0 5 votes vote down vote up
protected void createContext( Server server, Path repositoryDirectory )
    throws IOException
{
    ServletContextHandler context = new ServletContextHandler();
    context.setResourceBase( repositoryDirectory.toAbsolutePath().toString() );
    context.setContextPath( "/" );
    ServletHolder sh = new ServletHolder( DefaultServlet.class );
    context.addServlet( sh, "/" );
    server.setHandler( context );

}
 
Example 15
Source File: HttpServer.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Add default apps.
 * @param appDir The application directory
 */
protected void addDefaultApps(ContextHandlerCollection parent,
    final String appDir, Configuration conf) {
  // set up the context for "/logs/" if "hadoop.log.dir" property is defined.
  String logDir = this.logDir;
  if (logDir == null) {
    logDir = System.getProperty("hadoop.log.dir");
  }
  if (logDir != null) {
    ServletContextHandler logContext = new ServletContextHandler(parent, "/logs");
    logContext.addServlet(AdminAuthorizedServlet.class, "/*");
    logContext.setResourceBase(logDir);

    if (conf.getBoolean(
        ServerConfigurationKeys.HBASE_JETTY_LOGS_SERVE_ALIASES,
        ServerConfigurationKeys.DEFAULT_HBASE_JETTY_LOGS_SERVE_ALIASES)) {
      Map<String, String> params = logContext.getInitParams();
      params.put(
          "org.mortbay.jetty.servlet.Default.aliases", "true");
    }
    logContext.setDisplayName("logs");
    setContextAttributes(logContext, conf);
    defaultContexts.put(logContext, true);
  }
  // set up the context for "/static/*"
  ServletContextHandler staticContext = new ServletContextHandler(parent, "/static");
  staticContext.setResourceBase(appDir + "/static");
  staticContext.addServlet(DefaultServlet.class, "/*");
  staticContext.setDisplayName("static");
  setContextAttributes(staticContext, conf);
  defaultContexts.put(staticContext, true);
}
 
Example 16
Source File: HttpServer.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Add default servlets.
 */
protected void addDefaultServlets(
    ContextHandlerCollection contexts, Configuration conf) throws IOException {
  // set up default servlets
  addPrivilegedServlet("stacks", "/stacks", StackServlet.class);
  addPrivilegedServlet("logLevel", "/logLevel", LogLevel.Servlet.class);
  // Hadoop3 has moved completely to metrics2, and  dropped support for Metrics v1's
  // MetricsServlet (see HADOOP-12504).  We'll using reflection to load if against hadoop2.
  // Remove when we drop support for hbase on hadoop2.x.
  try {
    Class<?> clz = Class.forName("org.apache.hadoop.metrics.MetricsServlet");
    addPrivilegedServlet("metrics", "/metrics", clz.asSubclass(HttpServlet.class));
  } catch (Exception e) {
    // do nothing
  }
  addPrivilegedServlet("jmx", "/jmx", JMXJsonServlet.class);
  // While we don't expect users to have sensitive information in their configuration, they
  // might. Give them an option to not expose the service configuration to all users.
  if (conf.getBoolean(HTTP_PRIVILEGED_CONF_KEY, HTTP_PRIVILEGED_CONF_DEFAULT)) {
    addPrivilegedServlet("conf", "/conf", ConfServlet.class);
  } else {
    addUnprivilegedServlet("conf", "/conf", ConfServlet.class);
  }
  final String asyncProfilerHome = ProfileServlet.getAsyncProfilerHome();
  if (asyncProfilerHome != null && !asyncProfilerHome.trim().isEmpty()) {
    addPrivilegedServlet("prof", "/prof", ProfileServlet.class);
    Path tmpDir = Paths.get(ProfileServlet.OUTPUT_DIR);
    if (Files.notExists(tmpDir)) {
      Files.createDirectories(tmpDir);
    }
    ServletContextHandler genCtx = new ServletContextHandler(contexts, "/prof-output");
    genCtx.addServlet(ProfileOutputServlet.class, "/*");
    genCtx.setResourceBase(tmpDir.toAbsolutePath().toString());
    genCtx.setDisplayName("prof-output");
  } else {
    addUnprivilegedServlet("prof", "/prof", ProfileServlet.DisabledServlet.class);
    LOG.info("ASYNC_PROFILER_HOME environment variable and async.profiler.home system property " +
      "not specified. Disabling /prof endpoint.");
  }
}
 
Example 17
Source File: MockConsoleFactory.java    From knox with Apache License 2.0 5 votes vote down vote up
public static Handler create() {
  ServletHolder consoleHolder = new ServletHolder( "console", MockServlet.class );
  consoleHolder.setInitParameter( "contentType", "text/html" );
  consoleHolder.setInitParameter( "content", "<html>Console UI goes here.</html>" );

  ServletContextHandler consoleContext = new ServletContextHandler( ServletContextHandler.SESSIONS );
  consoleContext.setContextPath( "/console" );
  consoleContext.setResourceBase( "target/classes" );
  consoleContext.addServlet( consoleHolder, "/*" );

  return consoleContext;
}
 
Example 18
Source File: InterAccountSNSPermissionTest.java    From spring-integration-aws with MIT License 5 votes vote down vote up
private ServletContextHandler getServletContextHandler() throws Exception {

		context = new XmlWebApplicationContext();
		context.setConfigLocation("src/main/webapp/WEB-INF/InterAccountSNSPermissionFlow.xml");
		context.registerShutdownHook();

		ServletContextHandler contextHandler = new ServletContextHandler();
		contextHandler.setErrorHandler(null);
		contextHandler.setResourceBase(".");
		ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(
				context));
		contextHandler.addServlet(servletHolder, "/*");

		return contextHandler;
	}
 
Example 19
Source File: Bootstrap.java    From qmq with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DynamicConfig config = DynamicConfigLoader.load("backup.properties");
    DynamicConfig deadConfig = DynamicConfigLoader.load("dead_backup.properties");
    ServerWrapper wrapper = new ServerWrapper(config, deadConfig);
    Runtime.getRuntime().addShutdownHook(new Thread(wrapper::destroy));
    wrapper.start();

    final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.setResourceBase(System.getProperty("java.io.tmpdir"));

    final MessageService messageService = wrapper.getMessageService();

    DeadMessageApiServlet deadMessageApiServlet = new DeadMessageApiServlet(messageService);
    addServlet(context, deadMessageApiServlet, "/api/message/dead");

    MessageApiServlet messageApiServlet = new MessageApiServlet(messageService);
    addServlet(context, messageApiServlet, "/api/message");

    MessageDetailsServlet messageDetailsServlet = new MessageDetailsServlet(messageService);
    addServlet(context, messageDetailsServlet, "/api/message/detail");

    MessageRecordsServlet messageRecordsServlet = new MessageRecordsServlet(messageService);
    addServlet(context, messageRecordsServlet, "/api/message/records");

    int port = config.getInt("backup.server.http.port", 8080);
    final Server server = new Server(port);
    server.setHandler(context);
    server.start();
    server.join();
}
 
Example 20
Source File: Server.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected Server() throws Exception {
    org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(9000);

    // Configuring all static web resource
    final ServletHolder staticHolder = new ServletHolder(new DefaultServlet());
    // Register and map the dispatcher servlet
    final ServletHolder servletHolder = new ServletHolder(new CXFNonSpringJaxrsServlet());
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(staticHolder, "/static/*");
    context.addServlet(servletHolder, "/*");
    context.setResourceBase(getClass().getResource("/browser").toURI().toString());

    servletHolder.setInitParameter("redirects-list",
        "/ /index.html /js/fileinput.min.js /css/fileinput.min.css");
    servletHolder.setInitParameter("redirect-servlet-name", staticHolder.getName());
    servletHolder.setInitParameter("redirect-attributes", "javax.servlet.include.request_uri");
    servletHolder.setInitParameter("jaxrs.serviceClasses", Catalog.class.getName());
    servletHolder.setInitParameter("jaxrs.properties", StringUtils.join(
        new String[] {
            "search.query.parameter.name=$filter",
            SearchUtils.DATE_FORMAT_PROPERTY + "=yyyy/MM/dd"
        }, " ")
    );
    servletHolder.setInitParameter("jaxrs.providers", StringUtils.join(
        new String[] {
            MultipartProvider.class.getName(),
            SearchContextProvider.class.getName(),
            JsrJsonpProvider.class.getName(),
            CrossOriginResourceSharingFilter.class.getName()
        }, ",")
    );

    server.setHandler(context);
    server.start();
    server.join();
}