Example usage for javax.servlet Servlet getClass

List of usage examples for javax.servlet Servlet getClass

Introduction

In this page you can find the example usage for javax.servlet Servlet getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.vaadin.spring.boot.CustomServletOverrideTest.java

@Test
public void customServletIsInjected() throws Exception {
    Method getServlet = ServletRegistrationBean.class.getDeclaredMethod("getServlet");
    getServlet.setAccessible(true);//from ww w .  j  a v  a2 s.c  o  m
    Servlet servlet = (Servlet) getServlet.invoke(servletRegistrationBean);
    assertTrue("expected MyCustomVaadinServlet, was " + servlet.getClass().getSimpleName(),
            servlet instanceof MyCustomVaadinServlet);
}

From source file:io.nebo.container.NettyEmbeddedContext.java

@Override
public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {
    return addServlet(servletName, servlet.getClass().getName(), servlet);
}

From source file:io.neba.core.logviewer.LogfileViewerConsolePluginTest.java

private void invokeDestroy(Servlet servlet)
        throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
    Method method = servlet.getClass().getMethod("destroy");
    method.setAccessible(true);/* ww w.ja v a  2s .  co m*/
    method.invoke(servlet);
}

From source file:io.neba.core.logviewer.LogfileViewerConsolePluginTest.java

private void invokeInit(Servlet servlet, ServletConfig config)
        throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
    Method method = servlet.getClass().getMethod("init", ServletConfig.class);
    method.setAccessible(true);//from w w  w.j  a  va  2  s . c  o m
    method.invoke(servlet, config);
}

From source file:com.jsmartframework.web.manager.ContextControl.java

@Override
@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent event) {
    try {/* w ww .  j a  v  a  2  s . c o m*/
        ServletContext servletContext = event.getServletContext();

        CONFIG.init(servletContext);
        if (CONFIG.getContent() == null) {
            throw new RuntimeException("Configuration file " + Constants.WEB_CONFIG_XML
                    + " was not found in WEB-INF resources folder!");
        }

        String contextConfigLocation = "com.jsmartframework.web.manager";
        if (CONFIG.getContent().getPackageScan() != null) {
            contextConfigLocation += "," + CONFIG.getContent().getPackageScan();
        }

        // Configure necessary parameters in the ServletContext to set Spring configuration without needing an XML file
        AnnotationConfigWebApplicationContext configWebAppContext = new AnnotationConfigWebApplicationContext();
        configWebAppContext.setConfigLocation(contextConfigLocation);

        CONTEXT_LOADER = new ContextLoader(configWebAppContext);
        CONTEXT_LOADER.initWebApplicationContext(servletContext);

        TagEncrypter.init();
        TEXTS.init();
        IMAGES.init(servletContext);
        HANDLER.init(servletContext);

        // ServletControl -> @MultipartConfig @WebServlet(name = "ServletControl", displayName = "ServletControl", loadOnStartup = 1)
        Servlet servletControl = servletContext.createServlet(
                (Class<? extends Servlet>) Class.forName("com.jsmartframework.web.manager.ServletControl"));
        ServletRegistration.Dynamic servletControlReg = (ServletRegistration.Dynamic) servletContext
                .addServlet("ServletControl", servletControl);
        servletControlReg.setAsyncSupported(true);
        servletControlReg.setLoadOnStartup(1);

        // ServletControl Initial Parameters
        InitParam[] initParams = CONFIG.getContent().getInitParams();
        if (initParams != null) {
            for (InitParam initParam : initParams) {
                servletControlReg.setInitParameter(initParam.getName(), initParam.getValue());
            }
        }

        // MultiPart to allow file upload on ServletControl
        MultipartConfigElement multipartElement = getServletMultipartElement();
        if (multipartElement != null) {
            servletControlReg.setMultipartConfig(multipartElement);
        }

        // Security constraint to ServletControl
        ServletSecurityElement servletSecurityElement = getServletSecurityElement(servletContext);
        if (servletSecurityElement != null) {
            servletControlReg.setServletSecurity(servletSecurityElement);
        }

        // TODO: Fix problem related to authentication by container to use SSL dynamically (Maybe create more than one servlet for secure and non-secure patterns)
        // Check also the use of request.login(user, pswd)
        // Check the HttpServletRequest.BASIC_AUTH, CLIENT_CERT_AUTH, FORM_AUTH, DIGEST_AUTH
        // servletReg.setRunAsRole("admin");
        // servletContext.declareRoles("admin");

        // ServletControl URL mapping
        String[] servletMapping = getServletMapping();
        servletControlReg.addMapping(servletMapping);

        // ErrorFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter errorFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.ErrorFilter"));
        FilterRegistration.Dynamic errorFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("ErrorFilter", errorFilter);

        errorFilterReg.setAsyncSupported(true);
        errorFilterReg.addMappingForUrlPatterns(
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ERROR), true, "/*");

        // EncodeFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter encodeFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.EncodeFilter"));
        FilterRegistration.Dynamic encodeFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("EncodeFilter", encodeFilter);

        encodeFilterReg.setAsyncSupported(true);
        encodeFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR), true,
                "/*");

        // CacheFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter cacheFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.CacheFilter"));
        FilterRegistration.Dynamic cacheFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("CacheFilter", cacheFilter);

        cacheFilterReg.setAsyncSupported(true);
        cacheFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR), true,
                "/*");

        // Add custom filters defined by client
        for (String filterName : sortCustomFilters()) {
            Filter customFilter = servletContext
                    .createFilter((Class<? extends Filter>) HANDLER.webFilters.get(filterName));
            HANDLER.executeInjection(customFilter);

            WebFilter webFilter = customFilter.getClass().getAnnotation(WebFilter.class);
            FilterRegistration.Dynamic customFilterReg = (FilterRegistration.Dynamic) servletContext
                    .addFilter(filterName, customFilter);

            if (webFilter.initParams() != null) {
                for (WebInitParam initParam : webFilter.initParams()) {
                    customFilterReg.setInitParameter(initParam.name(), initParam.value());
                }
            }
            customFilterReg.setAsyncSupported(webFilter.asyncSupported());
            customFilterReg.addMappingForUrlPatterns(EnumSet.copyOf(Arrays.asList(webFilter.dispatcherTypes())),
                    true, webFilter.urlPatterns());
        }

        // FilterControl -> @WebFilter(servletNames = {"ServletControl"})
        Filter filterControl = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.FilterControl"));
        FilterRegistration.Dynamic filterControlReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("FilterControl", filterControl);

        filterControlReg.setAsyncSupported(true);
        filterControlReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.ERROR, DispatcherType.INCLUDE), true, "ServletControl");

        // OutputFilter -> @WebFilter(servletNames = {"ServletControl"})
        Filter outputFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.OutputFilter"));
        FilterRegistration.Dynamic outputFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("OutputFilter", outputFilter);

        outputFilterReg.setAsyncSupported(true);
        outputFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.ERROR, DispatcherType.INCLUDE), true, "ServletControl");

        // AsyncFilter -> @WebFilter(servletNames = {"ServletControl"})
        // Filter used case AsyncContext is dispatched internally by AsyncBean implementation
        Filter asyncFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.AsyncFilter"));
        FilterRegistration.Dynamic asyncFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("AsyncFilter", asyncFilter);

        asyncFilterReg.setAsyncSupported(true);
        asyncFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.ASYNC), true, "ServletControl");

        // SessionControl -> @WebListener
        EventListener sessionListener = servletContext.createListener((Class<? extends EventListener>) Class
                .forName("com.jsmartframework.web.manager.SessionControl"));
        servletContext.addListener(sessionListener);

        // RequestControl -> @WebListener
        EventListener requestListener = servletContext.createListener((Class<? extends EventListener>) Class
                .forName("com.jsmartframework.web.manager.RequestControl"));
        servletContext.addListener(requestListener);

        // Custom WebServlet -> Custom Servlets created by application
        for (String servletName : HANDLER.webServlets.keySet()) {
            Servlet customServlet = servletContext
                    .createServlet((Class<? extends Servlet>) HANDLER.webServlets.get(servletName));
            HANDLER.executeInjection(customServlet);

            WebServlet webServlet = customServlet.getClass().getAnnotation(WebServlet.class);
            ServletRegistration.Dynamic customReg = (ServletRegistration.Dynamic) servletContext
                    .addServlet(servletName, customServlet);

            customReg.setLoadOnStartup(webServlet.loadOnStartup());
            customReg.setAsyncSupported(webServlet.asyncSupported());

            WebInitParam[] customInitParams = webServlet.initParams();
            if (customInitParams != null) {
                for (WebInitParam customInitParam : customInitParams) {
                    customReg.setInitParameter(customInitParam.name(), customInitParam.value());
                }
            }

            // Add mapping url for custom servlet
            customReg.addMapping(webServlet.urlPatterns());

            if (customServlet.getClass().isAnnotationPresent(MultipartConfig.class)) {
                customReg.setMultipartConfig(new MultipartConfigElement(
                        customServlet.getClass().getAnnotation(MultipartConfig.class)));
            }
        }

        // Controller Dispatcher for Spring MVC
        Set<String> requestPaths = HANDLER.requestPaths.keySet();
        if (!requestPaths.isEmpty()) {
            ServletRegistration.Dynamic mvcDispatcherReg = servletContext.addServlet("DispatcherServlet",
                    new DispatcherServlet(configWebAppContext));
            mvcDispatcherReg.setLoadOnStartup(1);
            mvcDispatcherReg.addMapping(requestPaths.toArray(new String[requestPaths.size()]));

            // RequestPathFilter -> @WebFilter(servletNames = {"DispatcherServlet"})
            Filter requestPathFilter = servletContext.createFilter((Class<? extends Filter>) Class
                    .forName("com.jsmartframework.web.manager.RequestPathFilter"));
            FilterRegistration.Dynamic reqPathFilterReg = (FilterRegistration.Dynamic) servletContext
                    .addFilter("RequestPathFilter", requestPathFilter);

            reqPathFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST,
                    DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.INCLUDE, DispatcherType.ASYNC),
                    true, "DispatcherServlet");
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.ireland.jnetty.webapp.WebApp.java

@Override
public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {
    Class cl = servlet.getClass();

    return addServlet(servletName, cl.getName(), cl, servlet);
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_Registration11() throws Exception {
    ExtendedHttpService extendedHttpService = (ExtendedHttpService) getHttpService();

    Servlet servlet = new BaseServlet();

    extendedHttpService.registerServlet("/blah1", servlet, null, null);

    BundleContext bundleContext = getBundleContext();

    ServiceReference<HttpServiceRuntime> serviceReference = bundleContext
            .getServiceReference(HttpServiceRuntime.class);
    HttpServiceRuntime runtime = bundleContext.getService(serviceReference);

    RuntimeDTO runtimeDTO = runtime.getRuntimeDTO();

    ServletContextDTO[] servletContextDTOs = runtimeDTO.servletContextDTOs;

    for (ServletContextDTO servletContextDTO : servletContextDTOs) {
        if (servletContextDTO.name.startsWith("org.eclipse.equinox.http.servlet.internal.HttpServiceImpl$")) {
            ServletDTO servletDTO = servletContextDTO.servletDTOs[0];

            Assert.assertFalse(servletDTO.asyncSupported);
            Assert.assertEquals(servlet.getClass().getName(), servletDTO.name);
            Assert.assertEquals("/blah1", servletDTO.patterns[0]);
            Assert.assertTrue(servletDTO.serviceId < 0);
        }/*from w w  w .  ja v  a 2  s  .  c om*/
    }
}

From source file:org.paxle.gui.impl.ServletManager.java

private void registerServlet(ServiceReference servletRef) {
    if (this.http == null)
        return;/*  w w w .j  a  va 2s. c  om*/
    if (this.context == null)
        return;

    String fullAlias = null;
    String servletPID = null;
    try {
        // getting the servlet class
        Servlet servlet = (Servlet) this.context.locateService("servlets", servletRef);
        servletPID = (String) servletRef.getProperty(Constants.SERVICE_PID);

        // getting the path to use
        final String path = (String) servletRef.getProperty(SERVLET_PATH);

        // convert it into a full alias (pathprefix + alias)
        fullAlias = this.getFullAlias(path);

        // getting the httpContext to use
        HttpContext httpContext = this.createHttpAuthContext(servletRef);

        // init servlet properties
        @SuppressWarnings("unchecked")
        Hashtable<String, String> props = (Hashtable<String, String>) this.defaultProps.clone();
        if (servlet instanceof VelocityViewServlet) {
            final Bundle bundle = servletRef.getBundle();
            final BundleContext bundleContext = bundle.getBundleContext();

            // get or create a new velocity factory
            VelocityViewFactory factory = this.factories.get(Long.valueOf(bundle.getBundleId()));
            if (factory == null) {
                factory = new VelocityViewFactory(bundleContext, this);
                this.factories.put(bundle.getBundleId(), factory);
            }

            // configuring the bundle location to use for template loading
            final String bundleLocation = this.getBundleLocation(servletRef.getBundle());
            props.put("bundle.location", bundleLocation);

            // wrapping the servlet into a wrapper
            servlet = (Servlet) Proxy.newProxyInstance(servlet.getClass().getClassLoader(),
                    new Class[] { Servlet.class },
                    new VelocityViewServletWrapper((VelocityViewServlet) servlet, factory));
        }

        // registering the servlet
        this.logger.info(String.format("Registering servlet '%s' for alias '%s'.", servletPID, fullAlias));
        this.http.registerServlet(fullAlias, servlet, props, httpContext);
    } catch (Throwable e) {
        this.logger.error(String.format("Unexpected '%s' while registering servlet '%s' for alias '%s'.",
                e.getClass().getName(), servletPID, fullAlias), e);
    }
}

From source file:org.pentaho.platform.web.servlet.PluginDispatchServlet.java

protected Servlet getTargetServlet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    String dispatchKey = getDispatchKey(request);

    if (StringUtils.isEmpty(dispatchKey)) {
        if (logger.isDebugEnabled()) {
            logger.debug("dispatcher servlet is invoked but there is nothing telling it where to dispatch to"); //$NON-NLS-1$
        }/*from ww w.  jav  a 2  s.  c om*/
        return null;
    }

    Servlet targetServlet = null;
    String checkPath = dispatchKey;
    do {
        logger.debug("checking for servlet registered to service request for \"" + checkPath + "\""); //$NON-NLS-1$//$NON-NLS-2$
        targetServlet = pluginServletMap.get(checkPath);
        if (targetServlet != null) {
            logger.debug("servlet " + targetServlet.getClass().getName() + " will service request for \""
                    + dispatchKey
                    //$NON-NLS-1$//$NON-NLS-2$
                    + "\""); //$NON-NLS-1$
            return targetServlet;
        }
        if (checkPath.contains("/")) { //$NON-NLS-1$
            checkPath = checkPath.substring(0, checkPath.lastIndexOf("/")); //$NON-NLS-1$
        } else {
            checkPath = null;
        }
    } while (checkPath != null);

    if (targetServlet == null) {
        logger.debug("no servlet registered to service request for \"" + dispatchKey + "\""); //$NON-NLS-1$ //$NON-NLS-2$
    }
    return targetServlet;
}

From source file:org.pentaho.platform.web.servlet.PluginDispatchServlet.java

@SuppressWarnings("unchecked")
/** Restore the caching once the Plugin Type Tracking system is in place, for now we'll look-up every time **/
private synchronized void doInit() throws ServletException {
    if (logger.isDebugEnabled()) {
        logger.debug("PluginDispatchServlet.init"); //$NON-NLS-1$
    }//  w ww .  j a  va  2  s.c o m

    if (initialized) {
        return;
    }
    pluginServletMap.clear();

    Map<String, ListableBeanFactory> pluginBeanFactoryMap = getPluginBeanFactories();

    for (Map.Entry<String, ListableBeanFactory> pluginBeanFactoryEntry : pluginBeanFactoryMap.entrySet()) {

        Map<String, Object> beans = BeanFactoryUtils
                .beansOfTypeIncludingAncestors(pluginBeanFactoryEntry.getValue(), Servlet.class, true, true);

        if (logger.isDebugEnabled()) {
            logger.debug("found " + beans.size() + " servlets in " + pluginBeanFactoryEntry.getKey()); //$NON-NLS-1$//$NON-NLS-2$
        }

        for (Map.Entry<String, Object> beanEntry : beans.entrySet()) {
            Servlet pluginServlet = (Servlet) beanEntry.getValue();
            String servletId = beanEntry.getKey();

            String pluginId = pluginBeanFactoryEntry.getKey();
            String context = pluginId + "/" + servletId; //$NON-NLS-1$

            pluginServletMap.put(context, pluginServlet);
            if (logger.isDebugEnabled()) {
                logger.debug("calling init on servlet " + pluginServlet.getClass().getName()
                        + " serving context " + context); //$NON-NLS-1$//$NON-NLS-2$
            }
            try {
                pluginServlet.init(servletConfig);
            } catch (Throwable t) {
                logger.error("Could not load servlet '" + context + "'", t); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            }
        }
    }

    // Set initialized to true at the end of the synchronized method, so
    // that invocations of service() before this method has completed will not
    // cause NullPointerException
    initialized = true;
}