Java Code Examples for org.eclipse.jetty.webapp.WebAppContext#setContextPath()
The following examples show how to use
org.eclipse.jetty.webapp.WebAppContext#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: TestServer.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
public TestServer() { System.clearProperty("DEBUG"); jetty = new Server(); ServerConnector conn = new ServerConnector(jetty); conn.setHost(HOST); conn.setPort(PORT); jetty.addConnector(conn); WebAppContext webapp = new WebAppContext(); webapp.addSystemClass("org.slf4j."); webapp.addSystemClass("ch.qos.logback."); webapp.setContextPath(RDF4J_CONTEXT); // warPath configured in pom.xml maven-war-plugin configuration webapp.setWar("./target/rdf4j-server"); jetty.setHandler(webapp); }
Example 2
Source File: GatewayServer.java From hadoop-mini-clusters with Apache License 2.0 | 6 votes |
private WebAppContext createWebAppContext(Topology topology, File warFile, String warPath) throws IOException, ZipException, TransformerException, SAXException, ParserConfigurationException { String topoName = topology.getName(); WebAppContext context = new WebAppContext(); String contextPath; contextPath = "/" + Urls.trimLeadingAndTrailingSlashJoin(config.getGatewayPath(), topoName, warPath); context.setContextPath(contextPath); context.setWar(warFile.getAbsolutePath()); context.setAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE, topoName); context.setAttribute("org.apache.knox.gateway.frontend.uri", getFrontendUri(context, config)); context.setAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE, config); // // Add support for JSPs. // context.setAttribute( // "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", // ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" ); context.setTempDirectory(FileUtils.getFile(warFile, "META-INF", "temp")); context.setErrorHandler(createErrorHandler()); return context; }
Example 3
Source File: Spring3WebMvcTest.java From java-specialagent with Apache License 2.0 | 6 votes |
@BeforeClass public static void beforeClass() throws Exception { server = new Server(0); final WebAppContext webAppContext = new WebAppContext(); webAppContext.setServer(server); webAppContext.setContextPath("/"); webAppContext.setWar("src/test/webapp"); server.setHandler(webAppContext); server.start(); // jetty starts on random port final int port = ((ServerConnector)server.getConnectors()[0]).getLocalPort(); url = "http://localhost:" + port; }
Example 4
Source File: JettyStart.java From AppStash with Apache License 2.0 | 6 votes |
public static void main(final String[] args) { if (args.length < 1) { System.out.println("JettyStart <httpport>"); return; } Validate.notNull(args[0], "A Port is needed to start the server"); Server server = new Server(Integer.valueOf(args[0])); WebAppContext context = new WebAppContext(); context.setContextPath("/shop"); context.setResourceBase("src/main/webapp/"); context.setDescriptor("src/main/webapp/WEB-INF/web.xml"); context.setParentLoaderPriority(true); server.setHandler(context); try { LOGGER.info("JETTY SERVER STARTING NOW ..."); server.start(); server.join(); } catch (Exception e) { LOGGER.error("Jetty Server could not be started", e); System.exit(100); } }
Example 5
Source File: MetricServer.java From realtime-analytics with GNU General Public License v2.0 | 6 votes |
public void startStandAlone() { try { WebAppContext context = new WebAppContext(); String baseUrl = getBaseUrl(); LOGGER.info("Metric server baseUrl: " + baseUrl); context.setDescriptor(baseUrl + "/WEB-INF/web.xml"); context.setResourceBase(baseUrl); context.setContextPath("/"); context.setParentLoaderPriority(true); context.setAttribute("JetStreamRoot", applicationContext); Server s_server = new Server(s_port); s_server.setHandler(context); LOGGER.info( "Metric server started, listening on port " + s_port); s_server.start(); running.set(true); } catch (Throwable t) { throw CommonUtils.runtimeException(t); } }
Example 6
Source File: HttpServer2.java From hadoop-ozone with Apache License 2.0 | 5 votes |
private static WebAppContext createWebAppContext(Builder b, AccessControlList adminsAcl, final String appDir) { WebAppContext ctx = new WebAppContext(); ctx.setDefaultsDescriptor(null); ServletHolder holder = new ServletHolder(new DefaultServlet()); Map<String, String> params = ImmutableMap.<String, String>builder() .put("acceptRanges", "true") .put("dirAllowed", "false") .put("gzip", "true") .put("useFileMappedBuffer", "true") .build(); holder.setInitParameters(params); ctx.setWelcomeFiles(new String[] {"index.html"}); ctx.addServlet(holder, "/"); ctx.setDisplayName(b.name); ctx.setContextPath("/"); ctx.setWar(appDir + "/" + b.name); String tempDirectory = b.conf.get(HTTP_TEMP_DIR_KEY); if (tempDirectory != null && !tempDirectory.isEmpty()) { ctx.setTempDirectory(new File(tempDirectory)); ctx.setAttribute("javax.servlet.context.tempdir", tempDirectory); } ctx.getServletContext().setAttribute(CONF_CONTEXT_ATTRIBUTE, b.conf); ctx.getServletContext().setAttribute(ADMINS_ACL, adminsAcl); addNoCacheFilter(ctx); return ctx; }
Example 7
Source File: ExampleServerR5IT.java From hapi-fhir-jpaserver-starter with Apache License 2.0 | 5 votes |
@BeforeClass public static void beforeClass() throws Exception { String path = Paths.get("").toAbsolutePath().toString(); ourLog.info("Project base path is: {}", path); ourServer = new Server(0); WebAppContext webAppContext = new WebAppContext(); webAppContext.setContextPath("/hapi-fhir-jpaserver"); webAppContext.setDisplayName("HAPI FHIR"); webAppContext.setDescriptor(path + "/src/main/webapp/WEB-INF/web.xml"); webAppContext.setResourceBase(path + "/target/hapi-fhir-jpaserver-starter"); webAppContext.setParentLoaderPriority(true); ourServer.setHandler(webAppContext); ourServer.start(); ourPort = JettyUtil.getPortForStartedServer(ourServer); ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER); ourCtx.getRestfulClientFactory().setSocketTimeout(1200 * 1000); String ourServerBase = "http://localhost:" + ourPort + "/hapi-fhir-jpaserver/fhir/"; ourClient = ourCtx.newRestfulGenericClient(ourServerBase); ourClient.registerInterceptor(new LoggingInterceptor(true)); }
Example 8
Source File: NiFiTestServer.java From localization_nifi with Apache License 2.0 | 5 votes |
private WebAppContext createWebAppContext(String webappRoot, String contextPath) { webappContext = new WebAppContext(); webappContext.setContextPath(contextPath); webappContext.setWar(webappRoot); webappContext.setLogUrlOnStart(true); webappContext.setTempDirectory(new File("target/jetty")); return webappContext; }
Example 9
Source File: Main.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: need a relative path to the war file to execute"); System.exit(1); } System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StrErrLog"); System.setProperty("org.eclipse.jetty.LEVEL", "INFO"); // Create a basic Jetty server object that will listen on port defined by // the PORT environment variable when present, otherwise on 8080. int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8080")); Server server = new Server(port); // The WebAppContext is the interface to provide configuration for a web // application. In this example, the context path is being set to "/" so // it is suitable for serving root context requests. WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/"); webapp.setWar(args[0]); ClassList classlist = ClassList.setServerDefault(server); // Enable Annotation Scanning. classlist.addBefore( "org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration"); // Set the the WebAppContext as the ContextHandler for the server. server.setHandler(webapp); // Start the server! 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(); server.join(); }
Example 10
Source File: WebServerTestCase.java From htmlunit with Apache License 2.0 | 5 votes |
/** * Starts the web server delivering response from the provided connection. * @param mockConnection the sources for responses * @throws Exception if a problem occurs */ protected void startWebServer(final MockWebConnection mockConnection) throws Exception { if (STATIC_SERVER_ == null) { final Server server = buildServer(PORT); final WebAppContext context = new WebAppContext(); context.setContextPath("/"); context.setResourceBase("./"); if (isBasicAuthentication()) { final Constraint constraint = new Constraint(); constraint.setName(Constraint.__BASIC_AUTH); constraint.setRoles(new String[]{"user"}); constraint.setAuthenticate(true); final ConstraintMapping constraintMapping = new ConstraintMapping(); constraintMapping.setConstraint(constraint); constraintMapping.setPathSpec("/*"); final ConstraintSecurityHandler handler = (ConstraintSecurityHandler) context.getSecurityHandler(); handler.setLoginService(new HashLoginService("MyRealm", "./src/test/resources/realm.properties")); handler.setConstraintMappings(new ConstraintMapping[]{constraintMapping}); } context.addServlet(MockWebConnectionServlet.class, "/*"); server.setHandler(context); tryStart(PORT, server); STATIC_SERVER_ = server; } MockWebConnectionServlet.setMockconnection(mockConnection); }
Example 11
Source File: WebServerTestCase.java From htmlunit with Apache License 2.0 | 5 votes |
/** * Starts the web server on the default {@link #PORT}. * The given resourceBase is used to be the ROOT directory that serves the default context. * <p><b>Don't forget to stop the returned HttpServer after the test</b> * * @param resourceBase the base of resources for the default context * @param classpath additional classpath entries to add (may be null) * @param servlets map of {String, Class} pairs: String is the path spec, while class is the class * @throws Exception if the test fails */ protected void startWebServer(final String resourceBase, final String[] classpath, final Map<String, Class<? extends Servlet>> servlets) throws Exception { if (server_ != null) { throw new IllegalStateException("startWebServer() can not be called twice"); } final Server server = buildServer(PORT); final WebAppContext context = new WebAppContext(); context.setContextPath("/"); context.setResourceBase(resourceBase); for (final Map.Entry<String, Class<? extends Servlet>> entry : servlets.entrySet()) { final String pathSpec = entry.getKey(); final Class<? extends Servlet> servlet = entry.getValue(); context.addServlet(servlet, pathSpec); } final WebAppClassLoader loader = new WebAppClassLoader(context); if (classpath != null) { for (final String path : classpath) { loader.addClassPath(path); } } context.setClassLoader(loader); server.setHandler(context); tryStart(PORT, server); server_ = server; }
Example 12
Source File: SPARQLEmbeddedServer.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * @param repositoryIds */ public SPARQLEmbeddedServer(List<String> repositoryIds) { this.repositoryIds = repositoryIds; System.clearProperty("DEBUG"); jetty = new Server(PORT); WebAppContext webapp = new WebAppContext(); webapp.setContextPath(SERVER_CONTEXT); // warPath configured in pom.xml maven-war-plugin configuration webapp.setWar("./target/rdf4j-server"); jetty.setHandler(webapp); }
Example 13
Source File: VmRuntimeWebAppDeployer.java From appengine-java-vm-runtime with Apache License 2.0 | 5 votes |
@Override protected void doStart() throws Exception { Resource resource = Resource.newResource(webapp); File file = resource.getFile(); if (!resource.exists()) throw new IllegalStateException("WebApp resouce does not exist "+resource); String lcName=file.getName().toLowerCase(Locale.ENGLISH); if (lcName.endsWith(".xml")) { XmlConfiguration xmlc = new XmlConfiguration(resource.getURI().toURL()); xmlc.getIdMap().put("Server", contexts.getServer()); xmlc.getProperties().put("jetty.home",System.getProperty("jetty.home",".")); xmlc.getProperties().put("jetty.base",System.getProperty("jetty.base",".")); xmlc.getProperties().put("jetty.webapp",file.getCanonicalPath()); xmlc.getProperties().put("jetty.webapps",file.getParentFile().getCanonicalPath()); xmlc.getProperties().putAll(properties); handler = (ContextHandler)xmlc.configure(); } else { WebAppContext wac=new WebAppContext(); wac.setWar(webapp); wac.setContextPath("/"); } contexts.addHandler(handler); if (contexts.isRunning()) handler.start(); }
Example 14
Source File: ZeppelinServer.java From zeppelin with Apache License 2.0 | 5 votes |
private static WebAppContext setupWebAppContext( ContextHandlerCollection contexts, ZeppelinConfiguration conf, String warPath, String contextPath) { WebAppContext webApp = new WebAppContext(); webApp.setContextPath(contextPath); LOG.info("warPath is: {}", warPath); File warFile = new File(warPath); if (warFile.isDirectory()) { // Development mode, read from FS // webApp.setDescriptor(warPath+"/WEB-INF/web.xml"); webApp.setResourceBase(warFile.getPath()); webApp.setParentLoaderPriority(true); } else { // use packaged WAR webApp.setWar(warFile.getAbsolutePath()); webApp.setExtractWAR(false); File warTempDirectory = new File(conf.getRelativeDir(ConfVars.ZEPPELIN_WAR_TEMPDIR) + contextPath); warTempDirectory.mkdir(); LOG.info("ZeppelinServer Webapp path: {}", warTempDirectory.getPath()); webApp.setTempDirectory(warTempDirectory); } // Explicit bind to root webApp.addServlet(new ServletHolder(new DefaultServlet()), "/*"); contexts.addHandler(webApp); webApp.addFilter(new FilterHolder(CorsFilter.class), "/*", EnumSet.allOf(DispatcherType.class)); webApp.setInitParameter( "org.eclipse.jetty.servlet.Default.dirAllowed", Boolean.toString(conf.getBoolean(ConfVars.ZEPPELIN_SERVER_DEFAULT_DIR_ALLOWED))); return webApp; }
Example 15
Source File: JettyHelper.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
public static Server addWebApplication(final Server jetty, final String webAppContext, final String warFilePath) throws IOException { WebAppContext webapp = new WebAppContext(); webapp.setContextPath(webAppContext); webapp.setWar(warFilePath); webapp.setParentLoaderPriority(false); File tmpPath = new File(getWebAppBaseDirectory(webAppContext)); Files.createDirectories(tmpPath.toPath()); webapp.setTempDirectory(tmpPath); ((HandlerCollection) jetty.getHandler()).addHandler(webapp); return jetty; }
Example 16
Source File: EmbeddedServer.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
public EmbeddedServer(String host, int port, String contextPath, String warPath) { jetty = new Server(); ServerConnector conn = new ServerConnector(jetty); conn.setHost(host); conn.setPort(port); jetty.addConnector(conn); WebAppContext webapp = new WebAppContext(); webapp.setContextPath(contextPath); webapp.setTempDirectory(new File("temp/webapp/")); webapp.setWar(warPath); jetty.setHandler(webapp); }
Example 17
Source File: Start.java From wicket-orientdb with Apache License 2.0 | 4 votes |
/** * Main function, starts the jetty server. * * @param args */ public static void main(String[] args) { System.setProperty("wicket.configuration", "development"); Server server = new Server(); HttpConfiguration http_config = new HttpConfiguration(); http_config.setSecureScheme("https"); http_config.setSecurePort(8443); http_config.setOutputBufferSize(32768); ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config)); http.setPort(8080); http.setIdleTimeout(1000 * 60 * 60); server.addConnector(http); Resource keystore = Resource.newClassPathResource("/keystore"); if (keystore != null && keystore.exists()) { // if a keystore for a SSL certificate is available, start a SSL // connector on port 8443. // By default, the quickstart comes with a Apache Wicket Quickstart // Certificate that expires about half way september 2021. Do not // use this certificate anywhere important as the passwords are // available in the source. SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStoreResource(keystore); sslContextFactory.setKeyStorePassword("wicket"); sslContextFactory.setKeyManagerPassword("wicket"); HttpConfiguration https_config = new HttpConfiguration(http_config); https_config.addCustomizer(new SecureRequestCustomizer()); ServerConnector https = new ServerConnector(server, new SslConnectionFactory( sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config)); https.setPort(8443); https.setIdleTimeout(500000); server.addConnector(https); System.out.println("SSL access to the examples has been enabled on port 8443"); System.out .println("You can access the application using SSL on https://localhost:8443"); System.out.println(); } WebAppContext bb = new WebAppContext(); bb.setServer(server); bb.setContextPath("/"); bb.setWar("src/main/webapp"); // uncomment next line if you want to test with JSESSIONID encoded in the urls // ((AbstractSessionManager) // bb.getSessionHandler().getSessionManager()).setUsingCookies(false); server.setHandler(bb); MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer); server.addEventListener(mBeanContainer); server.addBean(mBeanContainer); try { server.start(); server.join(); } catch (Exception e) { e.printStackTrace(); System.exit(100); } }
Example 18
Source File: JettyServer.java From artifactory_ssh_proxy with Apache License 2.0 | 4 votes |
@SuppressWarnings({"resource", "boxing"}) public static Server newServer(int jettyPort, String jettyWebAppDir, JettyServiceSetting jettyServiceSetting) throws Exception { if (jettyPort == 0 || jettyWebAppDir == null) { throw new IllegalArgumentException("Jetty port and resource dir may not be empty"); } // server setup Server server = new Server(); server.addBean(new ScheduledExecutorScheduler()); server.setDumpAfterStart(false); server.setDumpBeforeStop(false); server.setStopAtShutdown(true); // http://www.eclipse.org/jetty/documentation/current/embedding-jetty.html#d0e19050 // Setup JMX MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); server.addBean(mbContainer); //setup handlers according to the jetty settings HandlerCollection handlerCollection = new HandlerCollection(); if (jettyServiceSetting == JettyServiceSetting.ARTIFACTORY || jettyServiceSetting == JettyServiceSetting.BOTH) { // The WebAppContext is the entity that controls the environment in // which a web application lives and breathes. In this example the // context path is being set to "/" so it is suitable for serving root // context requests and then we see it setting the location of the war. // A whole host of other configurations are available, ranging from // configuring to support annotation scanning in the webapp (through // PlusConfiguration) to choosing where the webapp will unpack itself. WebAppContext webapp = new WebAppContext(); File warFile = new File(jettyWebAppDir + File.separator + "artifactory.war"); webapp.setContextPath("/artifactory"); webapp.setWar(warFile.getAbsolutePath()); // A WebAppContext is a ContextHandler as well so it needs to be set to // the server so it is aware of where to send the appropriate requests. handlerCollection.addHandler(webapp); } if (jettyServiceSetting == JettyServiceSetting.VIP || jettyServiceSetting == JettyServiceSetting.BOTH) { // Serve resource files which reside in the jettyWebAppDir ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setDirectoriesListed(false); resourceHandler.setResourceBase(jettyWebAppDir); handlerCollection.addHandler(resourceHandler); } server.setHandler(handlerCollection); // http configuration HttpConfiguration http_config = new HttpConfiguration(); http_config.setSendServerVersion(true); // HTTP connector ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config)); http.setPort(jettyPort); server.addConnector(http); // start server server.start(); LOG.info("Started jetty server on port: {}, resource dir: {} ", jettyPort, jettyWebAppDir); return server; }
Example 19
Source File: Manager.java From chipster with MIT License | 4 votes |
private void startAdmin(Configuration configuration) throws IOException, Exception { org.eclipse.jetty.server.Server adminServer = new org.eclipse.jetty.server.Server(); ServerConnector connector = new ServerConnector(adminServer); connector.setPort(configuration.getInt("manager", "admin-port")); adminServer.setConnectors(new Connector[]{ connector }); Constraint constraint = new Constraint(); constraint.setName(Constraint.__BASIC_AUTH); constraint.setRoles(new String[] {ADMIN_ROLE}); constraint.setAuthenticate(true); ConstraintMapping cm = new ConstraintMapping(); cm.setConstraint(constraint); cm.setPathSpec("/*"); HashLoginService loginService = new HashLoginService("Please enter Chipster Admin username and password"); loginService.update(configuration.getString("manager", "admin-username"), new Password(configuration.getString("manager", "admin-password")), new String[] {ADMIN_ROLE}); ConstraintSecurityHandler sh = new ConstraintSecurityHandler(); sh.setLoginService(loginService); sh.addConstraintMapping(cm); WebAppContext context = new WebAppContext(); context.setWar(new File(DirectoryLayout.getInstance().getWebappsDir(), "admin-web.war").getAbsolutePath()); context.setContextPath("/"); // context.setDescriptor(new ClassPathResource("WebContent/WEB-INF/web.xml").getURI().toString()); // context.setResourceBase(new ClassPathResource("WebContent").getURI().toString()); // context.setContextPath("/"); // context.setParentLoaderPriority(true); context.setHandler(sh); HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[] {context, new DefaultHandler()}); adminServer.setHandler(handlers); adminServer.start(); }
Example 20
Source File: JettyLauncher.java From JobX with Apache License 2.0 | 4 votes |
@Override public void start(boolean devMode, int port) throws Exception { Server server = new Server(new QueuedThreadPool(Constants.WEB_THREADPOOL_SIZE)); WebAppContext appContext = new WebAppContext(); String resourceBasePath = ""; //开发者模式 if (devMode) { String artifact = MavenUtils.get(Thread.currentThread().getContextClassLoader()).getArtifactId(); resourceBasePath = artifact + "/src/main/webapp"; } appContext.setDescriptor(resourceBasePath + "WEB-INF/web.xml"); appContext.setResourceBase(resourceBasePath); appContext.setExtractWAR(true); //init param appContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false"); if (CommonUtils.isWindows()) { appContext.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false"); } //for jsp support appContext.addBean(new JettyJspParser(appContext)); appContext.addServlet(JettyJspServlet.class, "*.jsp"); appContext.setContextPath("/"); appContext.getServletContext().setExtendedListenerTypes(true); appContext.setParentLoaderPriority(true); appContext.setThrowUnavailableOnStartupException(true); appContext.setConfigurationDiscovered(true); appContext.setClassLoader(Thread.currentThread().getContextClassLoader()); ServerConnector connector = new ServerConnector(server); connector.setHost("localhost"); connector.setPort(port); server.setConnectors(new Connector[]{connector}); server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", 1024 * 1024 * 1024); server.setDumpAfterStart(false); server.setDumpBeforeStop(false); server.setStopAtShutdown(true); server.setHandler(appContext); logger.info("[JobX] JettyLauncher starting..."); server.start(); }