public void removeValve(Valve valve) { ((StandardEngine) engine).removeValve(valve); } }
Status getStatus() { if (webappContext == null) { return Status.DOWN; } switch (webappContext.getState()) { case NEW: case INITIALIZING: case INITIALIZED: case STARTING_PREP: case STARTING: return Status.DOWN; case STARTED: return Status.UP; default: // problem, stopped or failed return Status.FAILED; } }
public void addValve(Valve valve) { ((StandardEngine) engine).addValve(valve); }
final StandardEngine engine = new StandardEngine(); engine.setName(config.engineName()); engine.setDefaultHost(hostname); engine.setRealm(config.realm()); engine.setBackgroundProcessorDelay(-1); final StandardService service = new StandardService(); service.setName(config.serviceName()); service.setContainer(engine); service.addConnector(connector); final StandardServer server = new StandardServer(); server.setCatalinaBase(baseDir); server.setCatalinaHome(baseDir); server.setPort(EMBEDDED_TOMCAT_PORT); server.addService(service); StandardHost host = (StandardHost) engine.findChild(hostname); if (host == null) { host = new StandardHost(); host.setName(hostname); engine.addChild(host); if (!host.getAppBaseFile().mkdirs()) { throw new TomcatServiceException("failed to create app base file: " + host.getAppBaseFile());
private static StandardContext addContext(Tomcat tomcat, String contextPath, File dir) { try { StandardContext context = (StandardContext) tomcat.addWebapp(contextPath, dir.getAbsolutePath()); context.setClearReferencesHttpClientKeepAliveThread(false); context.setClearReferencesStopThreads(false); context.setClearReferencesStopTimerThreads(false); context.setClearReferencesStopTimerThreads(false); context.setAntiResourceLocking(false); context.setReloadable(false); context.setUseHttpOnly(true); context.setTldValidation(false); context.setXmlValidation(false); context.setXmlNamespaceAware(false); context.setUseNaming(false); context.setDelegate(true); context.setJarScanner(new NullJarScanner()); context.setAllowCasualMultipartParsing(true); context.setCookies(false); // disable JSP and WebSocket support context.setContainerSciFilter("org.apache.tomcat.websocket.server.WsSci|org.apache.jasper.servlet.JasperInitializer"); return context; } catch (ServletException e) { throw new IllegalStateException("Fail to configure webapp from " + dir, e); } }
@Test public void testAuthenticate() throws Exception { InMemoryRealm realm = new InMemoryRealm(); StandardContext ctx = new StandardContext(); ctx.setName("OryxTest"); realm.setContainer(ctx); realm.start(); realm.addUser("foo", "bar"); Principal authPrincipal = realm.authenticate("foo", "bar"); assertNotNull(authPrincipal); assertEquals("foo", authPrincipal.getName()); assertNull(realm.authenticate("foo", "baz")); assertNull(realm.authenticate("bar", "foo")); assertEquals("bar", realm.getPassword("foo")); assertEquals("foo", realm.getPrincipal("foo").getName()); }
public StandardWrapper addServlet(String path, String name, String clazz) throws ServletException { StandardWrapper servlet = (StandardWrapper) rootContext.createWrapper(); servlet.setName(name); servlet.setServletClass(clazz); servlet.setLoadOnStartup(1); rootContext.addChild(servlet); rootContext.addServletMapping(path, name); servlet.setParent(rootContext); // servlet.load(); return servlet; }
@Override public Connector apply(String hostname) { // Create the connector with our protocol handler. Tomcat will call ProtocolHandler.setAdapter() // on its startup with the Coyote Adapter which gives an access to Tomcat's HTTP service pipeline. final Class<?> protocolType = TomcatService.PROTOCOL_HANDLER_CLASS; final Connector connector = new Connector(protocolType.getName()); // We do not really open a port - just trying to stop the Connector from complaining. connector.setPort(0); final StandardServer server = newServer(hostname, connector, config); // Retrieve the components configured by newServer(), so we can use it in checkConfiguration(). final Service service = server.findServices()[0]; final Engine engine = TomcatUtil.engine(service, hostname); final StandardHost host = (StandardHost) engine.findChildren()[0]; final Context context = (Context) host.findChildren()[0]; // Apply custom configurators set via TomcatServiceBuilder.configurator() try { config.configurators().forEach(c -> c.accept(server)); } catch (Throwable t) { throw new TomcatServiceException("failed to configure an embedded Tomcat", t); } // Make sure the configurators did not ruin what we have configured in this method. checkConfiguration(server, service, connector, engine, host, context); assert connector.getService().getServer() != null; return connector; }
public List<ContextInfo> list() { final StandardServer server = getServer(); return Arrays.stream(server.findServices()) .filter(service -> service.getContainer() instanceof Engine) .map(service -> (Engine)service.getContainer()) .flatMap(engine -> Arrays.stream(engine.findChildren())) .filter(possibleHost -> possibleHost instanceof Host) .map(possibleHost -> (Host)possibleHost) .flatMap(host -> Arrays.stream(host.findChildren())) .filter(possibleContext -> possibleContext instanceof Context) .map(possibleContext -> (Context)possibleContext) .map(context -> { // copy to another object -- not the important part final ContextInfo info = new ContextInfo(context.getPath()); info.setThisPart(context.getThisPart()); info.setNotImportant(context.getNotImportant()); return info; }) .collect(Collectors.toList()); }
String webappDirLocation = "src/main/webapp/"; Tomcat tomcat = new Tomcat(); tomcat.setPort(8080); StandardContext ctx = (StandardContext) tomcat.addWebapp("/embeddedTomcat", new File(webappDirLocation).getAbsolutePath()); //declare an alternate location for your "WEB-INF/classes" dir: File additionWebInfClasses = new File("target/classes"); VirtualDirContext resources = new VirtualDirContext(); resources.setExtraResourcePaths("/WEB-INF/classes=" + additionWebInfClasses); ctx.setResources(resources); tomcat.start(); tomcat.getServer().await();
@Override public void setManager(Manager manager) { if (manager instanceof ManagerBase) { ((ManagerBase) manager).setSessionIdGenerator(new LazySessionIdGenerator()); } super.setManager(manager); }
/** * Returns the {@link Engine} of the specified Tomcat {@link Service}. If the {@link Service} has no * {@link Engine} set, a new {@link Engine} will be created and set. * * <p>The return type of {@link Service#getContainer()} has been changed from {@link Container} to * {@link Engine} since 8.5. Calling it directly will cause {@link NoSuchMethodError}. */ static Engine engine(Service service, String hostname) { final Engine engine; try { final Method m = Service.class.getDeclaredMethod("getContainer"); engine = (Engine) m.invoke(service); } catch (Exception e) { throw new Error("failed to invoke Service.getContainer()", e); } if (engine != null) { return engine; } // Create a new engine. final Engine newEngine = new StandardEngine(); newEngine.setName("Tomcat"); newEngine.setDefaultHost(hostname); newEngine.setRealm(new NullRealm()); service.setContainer(newEngine); return newEngine; }
private void load(Wrapper wrapper) { try { wrapper.load(); } catch (ServletException ex) { String message = sm.getString("standardContext.loadOnStartup.loadException", getName(), wrapper.getName()); if (getComputedFailCtxIfServletStartFails()) { throw new WebServerException(message, ex); } getLogger().error(message, StandardWrapper.getRootCause(ex)); } }
public StandardContext configure(Tomcat tomcat, Props props) { addStaticDir(tomcat, getContextPath(props) + "/deploy", new File(props.nonNullValueAsFile(PATH_DATA.getKey()), WEB_DEPLOY_PATH_RELATIVE_TO_DATA_DIR)); StandardContext webapp = addContext(tomcat, getContextPath(props), webappDir(props)); for (Map.Entry<Object, Object> entry : props.rawProperties().entrySet()) { String key = entry.getKey().toString(); webapp.addParameter(key, entry.getValue().toString()); } return webapp; }
private static void configureServer(Server server) { server.addLifecycleListener(new JreMemoryLeakPreventionListener()); server.addLifecycleListener(new ThreadLocalLeakPreventionListener()); }
protected Map<String, String> copyFileName(HttpServletRequest req) { Map<String, String> parts = new HashMap<>(); if (req.getContentType() == null) { return parts; } if (req.getContentType() != null && !req.getContentType().toLowerCase().contains("multipart/form-data")) { return parts; } try { Collection<Part> prs = req.getParts(); for (Part p : prs) { if (p instanceof ApplicationPart) { ApplicationPart ap = (ApplicationPart) p; parts.put(p.getName(), ap.getSubmittedFileName()); } } } catch (IOException | ServletException e) { e.printStackTrace(); } return parts; }
@Override public void customize(Context context) { if (!(context instanceof StandardContext)) { return; } StandardContext standardContext = (StandardContext) context; try { standardContext.setClearReferencesObjectStreamClassCaches(false); standardContext.setClearReferencesRmiTargets(false); standardContext.setClearReferencesThreadLocals(false); } catch (NoSuchMethodError ex) { // Earlier version of Tomcat (probably without // setClearReferencesThreadLocals). Continue. } }
public List<ContextInfo> list() { final List<ContextInfo> list = new ArrayList<ContextInfo>(); final StandardServer server = getServer(); Arrays.stream(server.findServices()) .filter(service -> service.getContainer() instanceof Engine) .map(service -> (Engine)service.getContainer()) .flatMap(engine -> Arrays.stream(engine.findChildren())) .filter(possibleHost -> possibleHost instanceof Host) .map(possibleHost -> (Host)possibleHost) .flatMap(host -> Arrays.stream(host.findChildren())) .filter(possibleContext -> possibleContext instanceof Context) .map(possibleContext -> (Context)possibleContext) .forEach(context -> { // copy to another object -- not the important part final ContextInfo info = new ContextInfo(context.getPath()); info.setThisPart(context.getThisPart()); info.setNotImportant(context.getNotImportant()); list.add(info); }); return list; }
String webappDirLocation = "src/main/webapp/"; Tomcat tomcat = new Tomcat(); tomcat.setPort(8080); StandardContext ctx = (StandardContext) tomcat.addWebapp("/embeddedTomcat", new File(webappDirLocation).getAbsolutePath()); //declare an alternate location for your "WEB-INF/classes" dir: File additionWebInfClasses = new File("target/classes"); WebResourceRoot resources = new StandardRoot(ctx); resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes", additionWebInfClasses.getAbsolutePath(), "/")); ctx.setResources(resources); tomcat.start(); tomcat.getServer().await();
@Test public void configure_root_webapp() throws Exception { props.setProperty("foo", "bar"); StandardContext context = mock(StandardContext.class); when(tomcat.addWebapp(anyString(), anyString())).thenReturn(context); underTest.configure(tomcat, new Props(props)); // configure webapp with properties verify(context).addParameter("foo", "bar"); }