private static Handler resourceHandler() { ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setBaseResource(Resource.newClassPathResource("/web", false, false)); resourceHandler.setWelcomeFiles(new String[] {"index.html"}); resourceHandler.setMinMemoryMappedContentLength(-1); return resourceHandler; }
public static void main(String[] args) throws Exception { // Create the Server object and a corresponding ServerConnector and then set the port for the // connector. In // this example the server will listen on port 8090. If you set this to port 0 then when the // server has been // started you can called connector.getLocalPort() to programmatically get the port the server // started on. Server server = new Server(); ServerConnector connector = new ServerConnector(server); connector.setPort(8090); server.setConnectors(new Connector[] {connector}); // Create a Context Handler and ResourceHandler. The ContextHandler is getting set to "/" path // but this could // be anything you like for builing out your url. Note how we are setting the ResourceBase using // our jetty // maven testing utilities to get the proper resource directory, you needn't use these, // you simply need to supply the paths you are looking to serve content from. ContextHandler context0 = new ContextHandler(); context0.setContextPath("/"); ResourceHandler rh0 = new ResourceHandler(); rh0.setBaseResource(Resource.newResource(MavenTestingUtils.getTestResourceDir("dir0"))); context0.setHandler(rh0); // Rinse and repeat the previous item, only specifying a different resource base. ContextHandler context1 = new ContextHandler(); context1.setContextPath("/"); ResourceHandler rh1 = new ResourceHandler(); rh1.setBaseResource(Resource.newResource(MavenTestingUtils.getTestResourceDir("dir1"))); context1.setHandler(rh1); // Create a ContextHandlerCollection and set the context handlers to it. This will let jetty // process urls // against the declared contexts in order to match up content. ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(new Handler[] {context0, context1}); server.setHandler(contexts); // Start things up! By using the server.join() the server thread will join with the current // thread. // See "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()" for more // details. server.start(); System.err.println(server.dump()); server.join(); }
@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(); }
public void start() { server = new Server(port); // Override the context classloader, so that Jetty uses the plugin classloader not the main // DMDirc loader. final Thread currentThread = Thread.currentThread(); final ClassLoader classLoader = currentThread.getContextClassLoader(); currentThread.setContextClassLoader(getClass().getClassLoader()); try { final ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setWelcomeFiles(new String[] {"index.html"}); resourceHandler.setBaseResource(Resource.newClassPathResource("/www")); final ResourceHandler clientResourceHandler = new ResourceHandler(); clientResourceHandler.setBaseResource(Resource.newClassPathResource("/com/dmdirc/res/")); final ContextHandler clientResourceContext = new ContextHandler("/res"); clientResourceContext.setHandler(clientResourceHandler); final ServletContextHandler wsHandler = new ServletContextHandler(); wsHandler.setContextPath("/"); wsHandler.addServlet(WebUiWebSocketServlet.class, "/ws"); HandlerList handlers = new HandlerList(); handlers.setHandlers( new Handler[] {resourceHandler, clientResourceContext, wsHandler, new DefaultHandler()}); server.setHandler(handlers); server.start(); } catch (Exception ex) { LOG.error(LogUtils.USER_ERROR, "Unable to start web server", ex); server = null; } finally { // Restore the usual context class loader. currentThread.setContextClassLoader(classLoader); } }
@SuppressWarnings({"unchecked", "rawtypes"}) public Task<Void> start() { // Ensuring that jersey will use singletons from the orbit container. ServiceLocator locator = Injections.createLocator(); DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class); DynamicConfiguration dc = dcs.createDynamicConfiguration(); final List<Class<?>> classes = new ArrayList<>(providers); if (container != null) { classes.addAll(container.getClasses()); for (final Class<?> c : container.getClasses()) { if (c.isAnnotationPresent(Singleton.class)) { Injections.addBinding( Injections.newFactoryBinder( new Factory() { @Override public Object provide() { return container.get(c); } @Override public void dispose(final Object instance) {} }) .to(c), dc); } } } dc.commit(); final ResourceConfig resourceConfig = new ResourceConfig(); // installing jax-rs classes known by the orbit container. for (final Class c : classes) { if (c.isAnnotationPresent(javax.ws.rs.Path.class) || c.isAnnotationPresent(javax.ws.rs.ext.Provider.class)) { resourceConfig.register(c); } } final WebAppContext webAppContext = new WebAppContext(); final ProtectionDomain protectionDomain = EmbeddedHttpServer.class.getProtectionDomain(); final URL location = protectionDomain.getCodeSource().getLocation(); logger.info(location.toExternalForm()); webAppContext.setInitParameter("useFileMappedBuffer", "false"); webAppContext.setWar(location.toExternalForm()); // this sets the default service locator to one that bridges to the orbit container. webAppContext.getServletContext().setAttribute(ServletProperties.SERVICE_LOCATOR, locator); webAppContext.setContextPath("/*"); webAppContext.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*"); final ContextHandler resourceContext = new ContextHandler(); ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setDirectoriesListed(true); resourceHandler.setWelcomeFiles(new String[] {"index.html"}); resourceHandler.setBaseResource(Resource.newClassPathResource("/web")); resourceContext.setHandler(resourceHandler); resourceContext.setInitParameter("useFileMappedBuffer", "false"); final ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers( new Handler[] { wrapHandlerWithMetrics(resourceContext, "resourceContext"), wrapHandlerWithMetrics(webAppContext, "webAppContext") }); server = new Server(port); server.setHandler(contexts); try { /// Initialize javax.websocket layer final ServerContainer serverContainer = WebSocketServerContainerInitializer.configureContext(webAppContext); for (Class c : classes) { if (c.isAnnotationPresent(ServerEndpoint.class)) { final ServerEndpoint annotation = (ServerEndpoint) c.getAnnotation(ServerEndpoint.class); final ServerEndpointConfig serverEndpointConfig = ServerEndpointConfig.Builder.create(c, annotation.value()) .configurator( new ServerEndpointConfig.Configurator() { @Override public <T> T getEndpointInstance(final Class<T> endpointClass) throws InstantiationException { return container.get(endpointClass); } }) .build(); serverContainer.addEndpoint(serverEndpointConfig); } } } catch (Exception e) { logger.error("Error starting jetty", e); throw new UncheckedException(e); } try { server.start(); } catch (Exception e) { logger.error("Error starting jetty", e); throw new UncheckedException(e); } return Task.done(); }
public WebServer(final int port, String uiPath, String tasksPath, final Simulator simulator) throws Exception { this.server = new Server(); final ServerConnector connector = new ServerConnector(server); connector.setPort(port); this.server.addConnector(connector); this.uiPath = uiPath; this.tasksPath = tasksPath; this.context = new ServletContextHandler(ServletContextHandler.SESSIONS); // serve UI webpage (after dynamically setting server ip) HttpServlet ui_servlet = new IPTokenHTTPServlet(port, UI_PATH); this.context.addServlet(new ServletHolder(ui_servlet), "/"); // serve UI Process webpage (after dynamically setting server ip) HttpServlet ui_process_servlet = new IPTokenHTTPServlet(port, UI_PROCESS_PATH); this.context.addServlet(new ServletHolder(ui_process_servlet), "/uiprocess"); // related static resources ContextHandler resourcesContext = new ContextHandler(); resourcesContext.setContextPath("/resources"); ResourceHandler rh = new ResourceHandler(); rh.setBaseResource(Resource.newClassPathResource(STATIC_RESOURCES_PATH)); resourcesContext.setHandler(rh); ContextHandler webjarsContext = new ContextHandler(); webjarsContext.setContextPath("/webjars/"); rh = new ResourceHandler() { @Override public Resource getResource(String path) throws MalformedURLException { Resource resource = Resource.newClassPathResource(path); if (resource == null || !resource.exists()) { resource = Resource.newClassPathResource(WEBJARS_RESOURCES_PATH + path); } return resource; } }; webjarsContext.setHandler(rh); ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(new Handler[] {webjarsContext, resourcesContext, context}); server.setHandler(contexts); context.setContextPath("/"); // add REST bridge servlet String apiBasePath = eu.learnpad.sim.BridgeInterface.class.getAnnotation(Path.class).value(); context.addServlet( new SimulatorBridgeServletHolder(simulator, context, apiBasePath), apiBasePath + "*"); // start server this.server.start(); // set chat servlet ServletHolder holder = new ServletHolder(new DummyChatServlet()); String fullPath = "/chat/*"; this.context.addServlet(holder, fullPath); System.out.println( "chat servlet launched at " + server.getURI().toString().substring(0, server.getURI().toString().length() - 1) + fullPath); }
private CrawljaxConfiguration getCrawljaxBuilder() { String url = ""; if (options.getUrl().toLowerCase().startsWith("http://")) { url = options.getUrl(); } else { server = new Server(8080); ResourceHandler handler = new ResourceHandler(); try { File fileToCrawl = new File(options.getUrl()); handler.setBaseResource( Resource.newResource(fileToCrawl.getParentFile().getAbsolutePath())); server.setHandler(handler); server.start(); int port = ((ServerConnector) server.getConnectors()[0]).getLocalPort(); url = "http://localhost:" + port + "/" + fileToCrawl.getName(); // URI.create(url); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } CrawljaxConfigurationBuilder builder = CrawljaxConfiguration.builderFor(url); // builder.addPlugin(new CrawlOverview()); builder.addPlugin( new OnNewStatePlugin() { @Override public void onNewState(CrawlerContext arg0, StateVertex arg1) { if (cancelSupplier != null) { if (cancelSupplier.getAsBoolean()) { crawljax.stop(); } } Document document; try { document = arg1.getDocument(); documents.add(document); notifyObservers(document); } catch (IOException e) { e.printStackTrace(); } } }); builder.setBrowserConfig(new BrowserConfiguration(BrowserType.PHANTOMJS, 1)); builder.setOutputDirectory( new File(options.getOutputDirectory().getAbsolutePath() + "/crawljax")); builder.setMaximumDepth(options.getMaxDepth()); builder.setMaximumStates(options.getMaxStates()); CrawlRulesBuilder crawlRules = builder.crawlRules(); if (options.shouldClickDefaultElements()) { crawlRules.clickDefaultElements(); } if (options.getDontClickElements().size() > 0) { for (String dontClick : options.getDontClickElements()) { crawlRules.dontClick(dontClick); // TODO: .withAttribute("value", "I don't recognize"); // TODO: .underXPath("//*[@id='pageFooter']"); // .underXPath("//*[@id='content']/div/div[2]"); } } if (options.getClickElements().size() > 0) { for (String click : options.getClickElements()) { crawlRules.click(click); // TODO: .withAttribute("type", "submit"); } } if (options.getDontClickElementsChildrenOf().size() > 0) { for (String dontClick : options.getDontClickElementsChildrenOf()) { crawlRules.dontClickChildrenOf(dontClick); } } crawlRules.insertRandomDataInInputForms(options.shouldPutRandomDataInForms()); crawlRules.clickElementsInRandomOrder(options.shouldClickElementsInRandomOrder()); crawlRules.crawlFrames(options.shouldCrawlFrames()); crawlRules.waitAfterReloadUrl(options.getWaitTimeAferReload(), TimeUnit.MILLISECONDS); crawlRules.waitAfterEvent(options.getWaitTimeAfterEvent(), TimeUnit.MILLISECONDS); crawlRules.clickOnce(options.shouldClickOnce()); crawlRules.crawlHiddenAnchors(options.shouldCrawlHiddenAnchorsButton()); return builder.build(); }