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

The following examples show how to use org.eclipse.jetty.servlet.ServletContextHandler#setContextPath() . 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: 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 2
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 3
Source File: ExplorerAppTest.java    From Nicobar with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void init() throws Exception {
    System.setProperty("archaius.deployment.applicationId","scriptmanager-app");
    System.setProperty("archaius.deployment.environment","dev");

    server = new Server(TEST_LOCAL_PORT);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addEventListener(new KaryonGuiceContextListener());

    context.addFilter(GuiceFilter.class, "/*", 1);
    context.addServlet(DefaultServlet.class, "/");

    server.setHandler(context);

    server.start();
}
 
Example 4
Source File: Server.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected Server() throws Exception {
    org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(9000);

    // Register and map the dispatcher servlet
    final ServletHolder servletHolder = new ServletHolder(new CXFNonSpringJaxrsServlet());
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(servletHolder, "/*");

    servletHolder.setInitParameter("javax.ws.rs.Application",
        CatalogApplication.class.getName());

    server.setHandler(context);
    server.start();
    server.join();
}
 
Example 5
Source File: TransactionServer.java    From tcc-transaction with Apache License 2.0 6 votes vote down vote up
private TransactionServer() {
	this.server = new Server(port);

	try {
		ServletContextHandler handler = new ServletContextHandler();
		handler.setContextPath("/");
		handler.setSessionHandler(new SessionHandler());
		handler.addServlet(EnvServlet.class, "/api/env");
		handler.addServlet(PropertiesServlet.class, "/api/props");
           handler.addServlet(TaskServlet.class, "/api/tasks");
           handler.addServlet(StaticContentServlet.class, "/*");
           handler.addServlet(StartServlet.class, "/api/start");

           server.setHandler(handler);
	} catch (Exception e) {
		log.error("Exception in building AdminResourcesContainer ", e);
	}
}
 
Example 6
Source File: JettyUtil.java    From incubator-iotdb with Apache License 2.0 5 votes vote down vote up
public static ServletContextHandler createStaticHandler() {
  ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
  URL res = JettyUtil.class.getClassLoader().getResource("iotdb/ui/static");
  HttpServlet servlet = new DefaultServlet();
  ServletHolder holder = new ServletHolder(servlet);
  holder.setInitParameter("resourceBase", res.toString());
  contextHandler.setContextPath("/static");
  contextHandler.addServlet(holder, "/");
  return contextHandler;
}
 
Example 7
Source File: ServletTest.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Test
public void test()
        throws Exception
{
    int port = FreePortFinder.findFreePortOnLoopback();
    Server server = new Server( port );
    try {

        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath( "/" );
        context.addEventListener( new FooServletContextListener() );
        context.addServlet( FooServlet.class, "/*" );

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

        try( CloseableHttpClient client = HttpClientBuilder.create().build() )
        {
            String result = client.execute( new HttpGet( "http://127.0.0.1:" + port + "/" ),
                                            new BasicResponseHandler() );
            Assert.assertEquals( APP_NAME, result.trim() );
        }

    } finally {
        server.stop();
    }
}
 
Example 8
Source File: ClientJettyReaderWriterITest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void initClass() {
    server = new Server(8180);

    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(EmbeddedServlet.class, "/hello");
    server.setHandler(context);

    try {
        server.start();
    } catch (Exception e) {
        fail("Failed to start server: " + e);
    }
}
 
Example 9
Source File: WebSocketServerEcho.java    From quarks with Apache License 2.0 5 votes vote down vote up
public void start(URI endpointURI, boolean needClientAuth) {
    curEndpointURI = endpointURI;
    curNeedClientAuth = needClientAuth;

    System.out.println(svrName+" "+endpointURI + " needClientAuth="+needClientAuth);

    server = createServer(endpointURI, needClientAuth);
    connector = (ServerConnector)server.getConnectors()[0];

    // Setup the basic application "context" for this application at "/"
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    server.setHandler(context);
    
    try {
        // Initialize javax.websocket layer
        ServerContainer wscontainer = WebSocketServerContainerInitializer.configureContext(context);

        // Add WebSocket endpoint to javax.websocket layer
        wscontainer.addEndpoint(this.getClass());

        // System.setProperty("javax.net.debug", "ssl"); // or "all"; "help" for full list

        server.start();
        System.out.println(svrName+" started "+connector);
        // server.dump(System.err);            
    }
    catch (Exception e) {
        throw new RuntimeException("start", e);
    }
}
 
Example 10
Source File: HttpServer.java    From heroic with Apache License 2.0 5 votes vote down vote up
private HandlerCollection setupHandler() throws Exception {
    final ResourceConfig resourceConfig = setupResourceConfig();
    final ServletContainer servlet = new ServletContainer(resourceConfig);

    final ServletHolder jerseyServlet = new ServletHolder(servlet);
    // Initialize and register Jersey ServletContainer

    jerseyServlet.setInitOrder(1);

    // statically provide injector to jersey application.
    final ServletContextHandler context =
        new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    context.setContextPath("/");

    GzipHandler gzip = new GzipHandler();
    gzip.setIncludedMethods("POST");
    gzip.setMinGzipSize(860);
    gzip.setIncludedMimeTypes("application/json");
    context.setGzipHandler(gzip);

    context.addServlet(jerseyServlet, "/*");
    context.addFilter(new FilterHolder(new ShutdownFilter(stopping, mapper)), "/*", null);
    context.setErrorHandler(new JettyJSONErrorHandler(mapper));

    final RequestLogHandler requestLogHandler = new RequestLogHandler();

    requestLogHandler.setRequestLog(new Slf4jRequestLog());

    final RewriteHandler rewrite = new RewriteHandler();
    makeRewriteRules(rewrite);

    final HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[]{rewrite, context, requestLogHandler});

    return handlers;
}
 
Example 11
Source File: ExampleServerTest.java    From rack-servlet with Apache License 2.0 5 votes vote down vote up
public ExampleServer(Module... modules) {
  ServletContextHandler handler = new ServletContextHandler();
  handler.setContextPath("/");
  handler.addEventListener(new GuiceInjectorServletContextListener(modules));
  handler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
  handler.addServlet(DefaultServlet.class, "/");

  server = new Server(0);
  server.setHandler(handler);
}
 
Example 12
Source File: JettyUtil.java    From incubator-iotdb with Apache License 2.0 5 votes vote down vote up
public static ServletContextHandler createServletHandler(String path, HttpServlet servlet) {
  ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
  ServletHolder holder = new ServletHolder(servlet);
  contextHandler.setContextPath(path);
  contextHandler.addServlet(holder, "/");
  return contextHandler;
}
 
Example 13
Source File: JettyServer.java    From jsonrpc4j with MIT License 5 votes vote down vote up
public void startup() throws Exception {
	port = 10000 + new Random().nextInt(30000);
	jetty = new Server(port);
	ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
	context.setContextPath("/");
	jetty.setHandler(context);
	ServletHolder servlet = context.addServlet(JsonRpcTestServlet.class, "/" + SERVLET);
	servlet.setInitParameter("class", service.getCanonicalName());
	jetty.start();
}
 
Example 14
Source File: ExplorerServer.java    From Explorer with Apache License 2.0 5 votes vote down vote up
private static ServletContextHandler setupRestApiContextHandler() {
    final ServletHolder cxfServletHolder = new ServletHolder(new CXFNonSpringJaxrsServlet());
    cxfServletHolder.setInitParameter("javax.ws.rs.Application", ExplorerServer.class.getName());
    cxfServletHolder.setName("rest");
    cxfServletHolder.setForcedPath("rest");

    final ServletContextHandler cxfContext = new ServletContextHandler();
    cxfContext.setSessionHandler(new SessionHandler());
    cxfContext.setContextPath("/api");
    cxfContext.addServlet(cxfServletHolder, "/*");
    cxfContext.addFilter(new FilterHolder(CorsFilter.class), "/*",
            EnumSet.allOf(DispatcherType.class));
    return cxfContext;
}
 
Example 15
Source File: ServletReporter.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
public void start() throws Exception {
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    jettyServer.setHandler(context);

    context.addEventListener(new HealthCheckServletContextListener(healthCheckRegistry));
    context.addEventListener(new MetricsServletContextListener(metricRegistry));
    context.addServlet(new ServletHolder(new AdminServlet()), "/*");

    jettyServer.start();
}
 
Example 16
Source File: MultiNodeManagerTestBase.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() throws Exception {
    staticCreateTestMetadata();
    System.clearProperty("kylin.server.cluster-servers");
    int port = CheckUtil.randomAvailablePort(40000, 50000);
    logger.info("Chosen port for CacheServiceTest is " + port);
    configA = KylinConfig.getInstanceFromEnv();
    configA.setProperty("kylin.server.cluster-servers", "localhost:" + port);
    configB = KylinConfig.createKylinConfig(configA);
    configB.setProperty("kylin.server.cluster-servers", "localhost:" + port);
    configB.setMetadataUrl("../examples/test_metadata");

    server = new Server(port);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    server.setHandler(context);

    final CacheService serviceA = new CacheService() {
        @Override
        public KylinConfig getConfig() {
            return configA;
        }
    };
    final CacheService serviceB = new CacheService() {
        @Override
        public KylinConfig getConfig() {
            return configB;
        }
    };

    context.addServlet(new ServletHolder(new BroadcasterReceiveServlet(new BroadcasterReceiveServlet.BroadcasterHandler() {
        @Override
        public void handle(String entity, String cacheKey, String event) {
            Broadcaster.Event wipeEvent = Broadcaster.Event.getEvent(event);
            final String log = "wipe cache type: " + entity + " event:" + wipeEvent + " name:" + cacheKey;
            logger.info(log);
            try {
                serviceA.notifyMetadataChange(entity, wipeEvent, cacheKey);
                serviceB.notifyMetadataChange(entity, wipeEvent, cacheKey);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    })), "/");
    server.start();
}
 
Example 17
Source File: JaxRsServerResource.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
@Override
protected void before() throws Throwable {
    Application application = new Application() {
        @Override
        public Set<Object> getSingletons() {
            Set<Object> result = new HashSet<>();
            result.addAll(providers);
            result.add(restService);
            return result;
        }
    };

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    filters.forEach(filter -> context.addFilter(
            new FilterHolder(filter),
            "/*",
            EnumSet.of(DispatcherType.REQUEST)
    ));
    context.addServlet(new ServletHolder(new ServletContainer(application)), "/*");

    this.port = UnusedSocketPortAllocator.global().allocate();
    server = new Server(port);
    server.setHandler(context);

    baseURI = "http://localhost:" + port;

    executor = Executors.newSingleThreadExecutor(r -> {
        Thread t = new Thread(r, "jettyServer");
        t.setDaemon(true);
        return t;
    });

    executor.execute(() -> {
        try {
            server.start();
            server.join();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    });

    // We cannot depend on Jetty running state, hence the active polling of the REST endpoint
    int responseCode = -1;
    do {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(baseURI + "/badEndpoint").openConnection();
            responseCode = connection.getResponseCode();
        } catch (IOException ignore) {
            Thread.sleep(10);
        }
    } while (responseCode != 404);
}
 
Example 18
Source File: ManagerApiMicroService.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * Configure the web application(s).
 * @param handlers
 * @throws Exception
 */
protected void addModulesToJetty(HandlerCollection handlers) throws Exception {
	/* *************
     * Manager API
     * ************* */
    ServletContextHandler apiManServer = new ServletContextHandler(ServletContextHandler.SESSIONS);
    addSecurityHandler(apiManServer);
    apiManServer.setContextPath("/apiman");
    apiManServer.addEventListener(new Listener());
    apiManServer.addEventListener(new BeanManagerResourceBindingListener());
    apiManServer.addEventListener(new ResteasyBootstrap());
    apiManServer.addFilter(LocaleFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    apiManServer.addFilter(ApimanCorsFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    apiManServer.addFilter(DisableCachingFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    addAuthFilter(apiManServer);
    apiManServer.addFilter(DefaultSecurityContextFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    apiManServer.addFilter(RootResourceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    apiManServer.addFilter(ManagerApiMicroServiceTxWatchdogFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    ServletHolder resteasyServlet = new ServletHolder(new HttpServletDispatcher());
    resteasyServlet.setInitParameter("javax.ws.rs.Application", ManagerApiMicroServiceApplication.class.getName());
    apiManServer.addServlet(resteasyServlet, "/*");

    apiManServer.setInitParameter("resteasy.injector.factory", "org.jboss.resteasy.cdi.CdiInjectorFactory");
    apiManServer.setInitParameter("resteasy.scan", "true");
    apiManServer.setInitParameter("resteasy.servlet.mapping.prefix", "");

    handlers.addHandler(apiManServer);

    /* ********** *
     * Manager UI *
     * ********** */
    ResourceHandler apimanUiServer = new ResourceHandler() {
        /**
         * @see org.eclipse.jetty.server.handler.ResourceHandler#getResource(java.lang.String)
         */
        @Override
        public Resource getResource(String path) {
            Resource resource = null;

            if (path == null || path.equals("/") || path.equals("/index.html")) {
                path = "/index.html";
            }
            if (path.startsWith("/apimanui/api-manager") || path.equals("/apimanui") || path.equals("/apimanui/")) {
                path = "/apimanui/index.html";
            }
            if (path.equals("/apimanui/apiman/config.js")) {
                resource = getConfigResource(path);
            }
            if (path.equals("/apimanui/apiman/translations.js")) {
                resource = getTranslationsResource(path);
            }

            if (resource == null) {
                URL url = getClass().getResource(path);
                if (url != null) {
                    resource = new ApimanResource(url);
                }
            }

            return resource;
        }
    };
    apimanUiServer.setResourceBase("/apimanui/");
    apimanUiServer.setWelcomeFiles(new String[] { "index.html" });
    handlers.addHandler(apimanUiServer);
}
 
Example 19
Source File: JettyWebSocketServer.java    From sequenceiq-samples with Apache License 2.0 4 votes vote down vote up
private void configureContextHandler(Server server) {
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.addServlet(new ServletHolder(new JettyWebSocketServlet(channelProcessor)), path);
    context.setContextPath("/");
    server.setHandler(context);
}
 
Example 20
Source File: WebDAVServer.java    From MtgDesktopCompanion with GNU General Public License v3.0 3 votes vote down vote up
@Override
public void start() throws IOException {
	server = new Server(getInt(SERVER_PORT));
	
	
	log = getString(LOGIN);
	pas = getString(PASS);
	
	
	ServletContextHandler ctx = new ServletContextHandler(ServletContextHandler.SESSIONS);
	ctx.setContextPath("/");
	
	ServletHandler handler = new ServletHandler();
	
	ctx.addServlet(new ServletHolder("default", new MiltonServlet()),"/");
	
	
	FilterHolder fh = handler.addFilterWithMapping(MiltonFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
				 fh.setInitParameter("resource.factory.class", WebDavMTGResourceFactory.class.getCanonicalName());
				 

	ctx.addFilter(fh, "/*", EnumSet.of(DispatcherType.REQUEST));
				 
	logger.trace(ctx.dump());

	ctx.setHandler(handler);
	server.setHandler(ctx);
	
	try {
		server.start();
		logger.info("Webdav start on port http://"+InetAddress.getLocalHost().getHostName() + ":"+getInt(SERVER_PORT));

	} catch (Exception e) {
		throw new IOException(e);
	}
}