Java Code Examples for org.apache.catalina.Wrapper#setServletClass()

The following examples show how to use org.apache.catalina.Wrapper#setServletClass() . 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: TomcatWebAppBuilder.java    From tomee with Apache License 2.0 6 votes vote down vote up
private void ensureMyFacesDontLooseFacesContext(final StandardContext standardContext) {
    for (final Container w : standardContext.findChildren()) {
        if (!Wrapper.class.isInstance(w)) {
            continue;
        }
        final Wrapper wrapper = Wrapper.class.cast(w);
        if ("FacesServlet".equals(wrapper.getName()) && "javax.faces.webapp.FacesServlet".equals(wrapper.getServletClass())) {
            final ClassLoader loader = standardContext.getLoader().getClassLoader();
            try {
                if (Files.toFile(loader.getResource("javax/faces/webapp/FacesServlet.class")).getName().startsWith("myfaces")) {
                    loader.loadClass("org.apache.tomee.myfaces.TomEEWorkaroundFacesServlet");
                    wrapper.setServletClass("org.apache.tomee.myfaces.TomEEWorkaroundFacesServlet");
                    break;
                }
            } catch (final Throwable t) {
                // not there, not a big deal in most of cases
            }
        }
    }
}
 
Example 2
Source File: TomcatWebSocketTestServer.java    From bearchoke with Apache License 2.0 6 votes vote down vote up
public void deployConfig(Class<? extends WebApplicationInitializer>... initializers) {

        this.context = this.tomcatServer.addContext("", System.getProperty("java.io.tmpdir"));

		// Add Tomcat's DefaultServlet
		Wrapper defaultServlet = this.context.createWrapper();
		defaultServlet.setName("default");
		defaultServlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
		this.context.addChild(defaultServlet);

		// Ensure WebSocket support
		this.context.addApplicationListener(WsContextListener.class.getName());

		this.context.addServletContainerInitializer(
				new SpringServletContainerInitializer(), new HashSet<Class<?>>(Arrays.asList(initializers)));
	}
 
Example 3
Source File: Launcher.java    From lucene-geo-gazetteer with Apache License 2.0 6 votes vote down vote up
public static void launchService(int port, String indexPath)
        throws IOException, LifecycleException {

    Tomcat server = new Tomcat();
    Context context = server.addContext("/", new File(".").getAbsolutePath());
    System.setProperty(INDEX_PATH_PROP, indexPath);

    Wrapper servlet = context.createWrapper();
    servlet.setName("CXFNonSpringJaxrs");
    servlet.setServletClass(CXFNonSpringJaxrsServlet.class.getName());
    servlet.addInitParameter("jaxrs.serviceClasses", SearchResource.class.getName() + " " + HealthCheckAPI.class.getName());

    servlet.setLoadOnStartup(1);
    context.addChild(servlet);
    context.addServletMapping("/api/*", "CXFNonSpringJaxrs");

    System.out.println("Starting Embedded Tomcat on port : " + port );
    server.setPort(port);
    server.start();
    server.getServer().await();
}
 
Example 4
Source File: Tomcat.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Static version of {@link #addServlet(String, String, String)}
 * @param ctx           Context to add Servlet to
 * @param servletName   Servlet name (used in mappings)
 * @param servletClass  The class to be used for the Servlet
 * @return The wrapper for the servlet
 */
public static Wrapper addServlet(Context ctx, 
                                  String servletName, 
                                  String servletClass) {
    // will do class for name and set init params
    Wrapper sw = ctx.createWrapper();
    sw.setServletClass(servletClass);
    sw.setName(servletName);
    ctx.addChild(sw);
    
    return sw;
}
 
Example 5
Source File: OpenEJBContextConfig.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void addAddedJAXWsServices() {
    final WebAppInfo webAppInfo = info.get();
    final AppInfo appInfo = info.app();
    if (webAppInfo == null || appInfo == null || "false".equalsIgnoreCase(appInfo.properties.getProperty("openejb.jaxws.add-missing-servlets", "true"))) {
        return;
    }

    try { // if no jaxws classes are here don't try anything
        OpenEJBContextConfig.class.getClassLoader().loadClass("org.apache.openejb.server.webservices.WsServlet");
    } catch (final ClassNotFoundException | NoClassDefFoundError e) {
        return;
    }

    for (final ServletInfo servlet : webAppInfo.servlets) {
        if (!servlet.mappings.iterator().hasNext()) { // no need to do anything
            continue;
        }

        for (final ParamValueInfo pv : servlet.initParams) {
            if ("openejb-internal".equals(pv.name) && "true".equals(pv.value)) {
                if (context.findChild(servlet.servletName) == null) {
                    final Wrapper wrapper = context.createWrapper();
                    wrapper.setName(servlet.servletName);
                    wrapper.setServletClass("org.apache.openejb.server.webservices.WsServlet");

                    // add servlet to context
                    context.addChild(wrapper);
                    context.addServletMappingDecoded(servlet.mappings.iterator().next(), wrapper.getName());
                }
                break;
            }
        }
    }
}
 
Example 6
Source File: TomEERemoteWebapp.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
protected void initInternal() throws LifecycleException {
    super.initInternal();
    final Wrapper servlet = createWrapper();
    servlet.setName(ServerServlet.class.getSimpleName());
    servlet.setServletClass(ServerServlet.class.getName());
    addChild(servlet);
    addServletMappingDecoded(MAPPING, ServerServlet.class.getSimpleName());
}
 
Example 7
Source File: Tomcat.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Static version of {@link #addServlet(String, String, String)}
 * @param ctx           Context to add Servlet to
 * @param servletName   Servlet name (used in mappings)
 * @param servletClass  The class to be used for the Servlet
 * @return The wrapper for the servlet
 */
public static Wrapper addServlet(Context ctx,
                                  String servletName,
                                  String servletClass) {
    // will do class for name and set init params
    Wrapper sw = ctx.createWrapper();
    sw.setServletClass(servletClass);
    sw.setName(servletName);
    ctx.addChild(sw);

    return sw;
}
 
Example 8
Source File: SpringBootTomcatPlusIT.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public void onDeployUAVApp(Object... args) {
    
    if(UAVServer.ServerVendor.SPRINGBOOT!=UAVServer.instance().getServerInfo(CaptureConstants.INFO_APPSERVER_VENDOR)) {
        return;
    }
    
    Tomcat tomcat=(Tomcat) args[0];
    String mofRoot=(String) args[1];
    
    //add uavApp
    StandardContext context=new StandardContext();
    context.setName("com.creditease.uav");
    context.setPath("/com.creditease.uav");
    context.setDocBase(mofRoot + "/com.creditease.uav");
    context.addLifecycleListener(new Tomcat.FixContextListener());
    tomcat.getHost().addChild(context);
    
    //add default servlet
    Wrapper servlet = context.createWrapper();
    servlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
    servlet.setName("default");
    context.addChild(servlet);    
    servlet.setOverridable(true);
    context.addServletMapping("/", "default");
    
    //init webapp classloader
    context.setLoader(new WebappLoader(Thread.currentThread().getContextClassLoader()));
    context.setDelegate(true);
    
    //after tomcat8, skip jarscan
    Object obj=ReflectionHelper.newInstance("org.apache.tomcat.util.scan.StandardJarScanner", Thread.currentThread().getContextClassLoader());
    if(obj!=null) {
        ReflectionHelper.invoke("org.apache.tomcat.util.scan.StandardJarScanner", obj, "setScanAllFiles", new Class<?>[]{Boolean.class}, new Object[] { false}, Thread.currentThread().getContextClassLoader());
        ReflectionHelper.invoke("org.apache.tomcat.util.scan.StandardJarScanner", obj, "setScanClassPath", new Class<?>[]{Boolean.class}, new Object[] { false}, Thread.currentThread().getContextClassLoader());
        ReflectionHelper.invoke("org.apache.tomcat.util.scan.StandardJarScanner", obj, "setScanAllDirectories", new Class<?>[]{Boolean.class}, new Object[] { false}, Thread.currentThread().getContextClassLoader());            
        
        context.setJarScanner((JarScanner) obj);      
    }        
}
 
Example 9
Source File: Tomcat.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Static version of {@link #addServlet(String, String, String)}
 * @param ctx           Context to add Servlet to
 * @param servletName   Servlet name (used in mappings)
 * @param servletClass  The class to be used for the Servlet
 * @return The wrapper for the servlet
 */
public static Wrapper addServlet(Context ctx, 
                                  String servletName, 
                                  String servletClass) {
    // will do class for name and set init params
    Wrapper sw = ctx.createWrapper();
    sw.setServletClass(servletClass);
    sw.setName(servletName);
    ctx.addChild(sw);
    
    return sw;
}
 
Example 10
Source File: ArkTomcatServletWebServerFactory.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
private void addJspServlet(Context context) {
    Wrapper jspServlet = context.createWrapper();
    jspServlet.setName("jsp");
    jspServlet.setServletClass(getJsp().getClassName());
    jspServlet.addInitParameter("fork", "false");
    for (Map.Entry<String, String> entry : getJsp().getInitParameters().entrySet()) {
        jspServlet.addInitParameter(entry.getKey(), entry.getValue());
    }
    jspServlet.setLoadOnStartup(3);
    context.addChild(jspServlet);
    context.addServletMappingDecoded("*.jsp", "jsp");
    context.addServletMappingDecoded("*.jspx", "jsp");
}
 
Example 11
Source File: ArkTomcatServletWebServerFactory.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
private void addDefaultServlet(Context context) {
    Wrapper defaultServlet = context.createWrapper();
    defaultServlet.setName("default");
    defaultServlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
    defaultServlet.addInitParameter("debug", "0");
    defaultServlet.addInitParameter("listings", "false");
    defaultServlet.setLoadOnStartup(1);
    // Otherwise the default location of a Spring DispatcherServlet cannot be set
    defaultServlet.setOverridable(true);
    context.addChild(defaultServlet);
    context.addServletMappingDecoded("/", "default");
}
 
Example 12
Source File: ApplicationContext.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
private ServletRegistration.Dynamic addServlet(String servletName,
        String servletClass, Servlet servlet) throws IllegalStateException {

    if (servletName == null || servletName.equals("")) {
        throw new IllegalArgumentException(sm.getString(
                "applicationContext.invalidServletName", servletName));
    }

    if (!context.getState().equals(LifecycleState.STARTING_PREP)) {
        //TODO Spec breaking enhancement to ignore this restriction
        throw new IllegalStateException(
                sm.getString("applicationContext.addServlet.ise",
                        getContextPath()));
    }

    Wrapper wrapper = (Wrapper) context.findChild(servletName);

    // Assume a 'complete' ServletRegistration is one that has a class and
    // a name
    if (wrapper == null) {
        wrapper = context.createWrapper();
        wrapper.setName(servletName);
        context.addChild(wrapper);
    } else {
        if (wrapper.getName() != null &&
                wrapper.getServletClass() != null) {
            if (wrapper.isOverridable()) {
                wrapper.setOverridable(false);
            } else {
                return null;
            }
        }
    }

    if (servlet == null) {
        wrapper.setServletClass(servletClass);
    } else {
        wrapper.setServletClass(servlet.getClass().getName());
        wrapper.setServlet(servlet);
    }

    return context.dynamicServletAdded(wrapper);
}
 
Example 13
Source File: ApplicationContext.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
private ServletRegistration.Dynamic addServlet(String servletName,
        String servletClass, Servlet servlet) throws IllegalStateException {

    if (servletName == null || servletName.equals("")) {
        throw new IllegalArgumentException(sm.getString(
                "applicationContext.invalidServletName", servletName));
    }

    if (!context.getState().equals(LifecycleState.STARTING_PREP)) {
        //TODO Spec breaking enhancement to ignore this restriction
        throw new IllegalStateException(
                sm.getString("applicationContext.addServlet.ise",
                        getContextPath()));
    }

    Wrapper wrapper = (Wrapper) context.findChild(servletName);

    // Assume a 'complete' ServletRegistration is one that has a class and
    // a name
    if (wrapper == null) {
        wrapper = context.createWrapper();
        wrapper.setName(servletName);
        context.addChild(wrapper);
    } else {
        if (wrapper.getName() != null &&
                wrapper.getServletClass() != null) {
            if (wrapper.isOverridable()) {
                wrapper.setOverridable(false);
            } else {
                return null;
            }
        }
    }

    if (servlet == null) {
        wrapper.setServletClass(servletClass);
    } else {
        wrapper.setServletClass(servlet.getClass().getName());
        wrapper.setServlet(servlet);
    }

    return context.dynamicServletAdded(wrapper);
}
 
Example 14
Source File: TomcatWsRegistry.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public List<String> setWsContainer(final HttpListener httpListener,
                                   final ClassLoader classLoader,
                                   String contextRoot, String virtualHost, final ServletInfo servletInfo,
                                   final String realmName, final String transportGuarantee, final String authMethod,
                                   final String moduleId) throws Exception {

    if (virtualHost == null) {
        virtualHost = engine.getDefaultHost();
    }

    final Container host = engine.findChild(virtualHost);
    if (host == null) {
        throw new IllegalArgumentException("Invalid virtual host '" + virtualHost + "'.  Do you have a matchiing Host entry in the server.xml?");
    }

    if ("ROOT".equals(contextRoot)) { // doesn't happen in tomee itself but with all our tooling around
        contextRoot = "";
    }
    if (!contextRoot.startsWith("/") && !contextRoot.isEmpty()) {
        contextRoot = "/" + contextRoot;
    }

    final Context context = (Context) host.findChild(contextRoot);
    if (context == null) {
        throw new IllegalArgumentException("Could not find web application context " + contextRoot + " in host " + host.getName());
    }

    final Wrapper wrapper = (Wrapper) context.findChild(servletInfo.servletName);
    if (wrapper == null) {
        throw new IllegalArgumentException("Could not find servlet " + servletInfo.servletName + " in web application context " + context.getName());
    }

    // for Pojo web services, we need to change the servlet class which is the service implementation
    // by the WsServler class
    wrapper.setServletClass(WsServlet.class.getName());
    if (wrapper.getServlet() != null) {
        wrapper.unload(); // deallocate previous one
        wrapper.load(); // reload this one withuot unloading it to keep the instance - unload is called during stop()
        // boolean controlling this method call can't be set to false through API so let do it ourself
        wrapper.getServlet().init(StandardWrapper.class.cast(wrapper)); // or Reflections.set(wrapper, "instanceInitialized", false);
    }

    setWsContainer(context, wrapper, httpListener);

    // add service locations
    final List<String> addresses = new ArrayList<>();
    for (final Connector connector : connectors) {
        for (final String mapping : wrapper.findMappings()) {
            final URI address = new URI(connector.getScheme(), null, host.getName(), connector.getPort(), (contextRoot.startsWith("/") ? "" : "/") + contextRoot + mapping, null, null);
            addresses.add(address.toString());
        }
    }
    return addresses;
}
 
Example 15
Source File: TomcatWsRegistry.java    From tomee with Apache License 2.0 4 votes vote down vote up
private void addServlet(final Container host, final Context context, final String mapping, final HttpListener httpListener, final String path,
                        final List<String> addresses, final boolean fakeDeployment, final String moduleId) {
    // build the servlet
    final Wrapper wrapper = context.createWrapper();
    wrapper.setName("webservice" + path.substring(1));
    wrapper.setServletClass(WsServlet.class.getName());

    // add servlet to context
    context.addChild(wrapper);
    context.addServletMappingDecoded(mapping, wrapper.getName());

    final String webServicecontainerID = wrapper.getName() + WsServlet.WEBSERVICE_CONTAINER + httpListener.hashCode();
    wrapper.addInitParameter(WsServlet.WEBSERVICE_CONTAINER, webServicecontainerID);

    setWsContainer(context, wrapper, httpListener);

    webserviceContexts.put(new Key(path, moduleId), context);

    // register wsdl locations for service-ref resolution
    for (final Connector connector : connectors) {
        final StringBuilder fullContextpath;
        if (!WEBSERVICE_OLDCONTEXT_ACTIVE && !fakeDeployment) {
            String contextPath = context.getPath();
            if (contextPath == null ||  !contextPath.isEmpty()) {
                if (contextPath != null && !contextPath.startsWith("/")) {
                    contextPath = "/" + contextPath;
                } else if (contextPath == null) {
                    contextPath = "/";
                }
            }

            fullContextpath = new StringBuilder(contextPath);
            if (!WEBSERVICE_SUB_CONTEXT.equals("/")) {
                fullContextpath.append(WEBSERVICE_SUB_CONTEXT);
            }
            fullContextpath.append(path);
        } else {
            fullContextpath = new StringBuilder(context.getPath()).append(path);
        }

        try {
            final URI address = new URI(connector.getScheme(), null, host.getName(), connector.getPort(), fullContextpath.toString(), null, null);
            addresses.add(address.toString());
        } catch (final URISyntaxException ignored) {
            // no-op
        }
    }
}
 
Example 16
Source File: TomcatOnlyApplication.java    From spring-graalvm-native with Apache License 2.0 4 votes vote down vote up
public static void main(String... args) throws Exception {
	Registry.disableRegistry();

	tomcatBase.mkdir();
	docBase.mkdir();
	serverBase.mkdir();

	Tomcat tomcat = new Tomcat();
	tomcat.setBaseDir(serverBase.getAbsolutePath());
	Connector connector = new Connector(Http11NioProtocol.class.getName());
	connector.setThrowOnFailure(true);
	connector.setPort(8080);
	tomcat.getService().addConnector(connector);
	tomcat.setConnector(connector);
	tomcat.getHost().setAutoDeploy(false);

	TomcatEmbeddedContext context = new TomcatEmbeddedContext();
	context.setResources(new LoaderHidingResourceRoot(context));
	context.setName("ROOT");
	context.setDisplayName("sample-tomcat-context");
	context.setPath("");
	context.setDocBase(docBase.getAbsolutePath());
	context.addLifecycleListener(new Tomcat.FixContextListener());
	context.setParentClassLoader(Thread.currentThread().getContextClassLoader());
	context.addLocaleEncodingMappingParameter(Locale.ENGLISH.toString(), DEFAULT_CHARSET.displayName());
	context.addLocaleEncodingMappingParameter(Locale.FRENCH.toString(), DEFAULT_CHARSET.displayName());
	context.setUseRelativeRedirects(false);
	try {
		context.setCreateUploadTargets(true);
	}
	catch (NoSuchMethodError ex) {
		// Tomcat is < 8.5.39. Continue.
	}
	StandardJarScanFilter filter = new StandardJarScanFilter();
	filter.setTldSkip(collectionToDelimitedString(TldSkipPatterns.DEFAULT, ",", "", ""));
	context.getJarScanner().setJarScanFilter(filter);
	WebappLoader loader = new WebappLoader(context.getParentClassLoader());
	loader.setLoaderClass(TomcatEmbeddedWebappClassLoader.class.getName());
	loader.setDelegate(true);
	context.setLoader(loader);

	Wrapper helloServlet = context.createWrapper();
	String servletName = HelloFromTomcatServlet.class.getSimpleName();
	helloServlet.setName(servletName);
	helloServlet.setServletClass(HelloFromTomcatServlet.class.getName());
	helloServlet.setLoadOnStartup(1);
	helloServlet.setOverridable(true);
	context.addChild(helloServlet);
	context.addServletMappingDecoded("/", servletName);

	tomcat.getHost().addChild(context);
	tomcat.getHost().setAutoDeploy(false);
	TomcatWebServer server = new TomcatWebServer(tomcat);
	server.start();
}
 
Example 17
Source File: ApplicationContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private ServletRegistration.Dynamic addServlet(String servletName, String servletClass,
        Servlet servlet, Map<String,String> initParams) throws IllegalStateException {

    if (servletName == null || servletName.equals("")) {
        throw new IllegalArgumentException(sm.getString(
                "applicationContext.invalidServletName", servletName));
    }

    if (!context.getState().equals(LifecycleState.STARTING_PREP)) {
        //TODO Spec breaking enhancement to ignore this restriction
        throw new IllegalStateException(
                sm.getString("applicationContext.addServlet.ise",
                        getContextPath()));
    }

    Wrapper wrapper = (Wrapper) context.findChild(servletName);

    // Assume a 'complete' ServletRegistration is one that has a class and
    // a name
    if (wrapper == null) {
        wrapper = context.createWrapper();
        wrapper.setName(servletName);
        context.addChild(wrapper);
    } else {
        if (wrapper.getName() != null &&
                wrapper.getServletClass() != null) {
            if (wrapper.isOverridable()) {
                wrapper.setOverridable(false);
            } else {
                return null;
            }
        }
    }

    ServletSecurity annotation = null;
    if (servlet == null) {
        wrapper.setServletClass(servletClass);
        Class<?> clazz = Introspection.loadClass(context, servletClass);
        if (clazz != null) {
            annotation = clazz.getAnnotation(ServletSecurity.class);
        }
    } else {
        wrapper.setServletClass(servlet.getClass().getName());
        wrapper.setServlet(servlet);
        if (context.wasCreatedDynamicServlet(servlet)) {
            annotation = servlet.getClass().getAnnotation(ServletSecurity.class);
        }
    }

    if (initParams != null) {
        for (Map.Entry<String, String> initParam: initParams.entrySet()) {
            wrapper.addInitParameter(initParam.getKey(), initParam.getValue());
        }
    }

    ServletRegistration.Dynamic registration =
            new ApplicationServletRegistration(wrapper, context);
    if (annotation != null) {
        registration.setServletSecurity(new ServletSecurityElement(annotation));
    }
    return registration;
}