Search in sources :

Example 1 with WebServlet

use of jakarta.servlet.annotation.WebServlet in project HTTP-RPC by HTTP-RPC.

the class WebService method init.

@Override
public void init() throws ServletException {
    Class<? extends WebService> type = getClass();
    WebServlet webServlet = type.getAnnotation(WebServlet.class);
    String[] urlPatterns = webServlet.urlPatterns();
    if (urlPatterns.length == 0) {
        throw new ServletException("At least one URL pattern is required.");
    }
    String path = urlPatterns[0];
    if (!path.startsWith("/") && (path.length() == 1 || path.endsWith("/*"))) {
        throw new ServletException("Invalid URL pattern.");
    }
    path = path.substring(0, path.length() - 2);
    root = new Resource();
    Method[] methods = getClass().getMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        RequestMethod requestMethod = method.getAnnotation(RequestMethod.class);
        if (requestMethod != null) {
            Handler handler = new Handler(method);
            Resource resource = root;
            ResourcePath resourcePath = method.getAnnotation(ResourcePath.class);
            if (resourcePath != null) {
                String[] components = resourcePath.value().split("/");
                for (int j = 0; j < components.length; j++) {
                    String component = components[j];
                    if (component.length() == 0) {
                        continue;
                    }
                    if (component.startsWith(ResourcePath.PATH_VARIABLE_PREFIX)) {
                        int k = ResourcePath.PATH_VARIABLE_PREFIX.length();
                        String key;
                        if (component.length() > k) {
                            if (component.charAt(k++) != ':') {
                                throw new ServletException("Invalid path variable.");
                            }
                            key = component.substring(k);
                            component = ResourcePath.PATH_VARIABLE_PREFIX;
                        } else {
                            key = null;
                        }
                        handler.keys.add(key);
                    }
                    Resource child = resource.resources.get(component);
                    if (child == null) {
                        child = new Resource();
                        resource.resources.put(component, child);
                    }
                    resource = child;
                }
            }
            String verb = requestMethod.value().toLowerCase();
            List<Handler> handlerList = resource.handlerMap.get(verb);
            if (handlerList == null) {
                handlerList = new LinkedList<>();
                resource.handlerMap.put(verb, handlerList);
            }
            handlerList.add(handler);
        }
    }
    sort(root);
    serviceDescriptor = new ServiceDescriptor(path, type);
    describeResource(path, root, Arrays.stream(type.getAnnotationsByType(Endpoint.class)).collect(Collectors.toMap(endpoint -> serviceDescriptor.path + "/" + endpoint.path(), Function.identity())));
    if (getClass().getAnnotation(WebServlet.class) != null) {
        synchronized (WebService.class) {
            instances.put(type, this);
        }
    }
}
Also used : URLStreamHandler(java.net.URLStreamHandler) Method(java.lang.reflect.Method) ServletException(jakarta.servlet.ServletException) WebServlet(jakarta.servlet.annotation.WebServlet)

Example 2 with WebServlet

use of jakarta.servlet.annotation.WebServlet in project tomee by apache.

the class LightweightWebAppBuilder method deployWebApps.

@Override
public void deployWebApps(final AppInfo appInfo, final ClassLoader appClassLoader) throws Exception {
    final CoreContainerSystem cs = (CoreContainerSystem) SystemInstance.get().getComponent(ContainerSystem.class);
    final AppContext appContext = cs.getAppContext(appInfo.appId);
    if (appContext == null) {
        throw new OpenEJBRuntimeException("Can't find app context for " + appInfo.appId);
    }
    for (final WebAppInfo webAppInfo : appInfo.webApps) {
        ClassLoader classLoader = loaderByWebContext.get(webAppInfo.moduleId);
        if (classLoader == null) {
            classLoader = appClassLoader;
        }
        final Set<Injection> injections = new HashSet<>(appContext.getInjections());
        injections.addAll(new InjectionBuilder(classLoader).buildInjections(webAppInfo.jndiEnc));
        final List<BeanContext> beanContexts;
        if (!appInfo.webAppAlone) {
            // add module bindings in app
            final Assembler assembler = SystemInstance.get().getComponent(Assembler.class);
            beanContexts = assembler.initEjbs(classLoader, appInfo, appContext, injections, new ArrayList<>(), webAppInfo.moduleId);
            appContext.getBeanContexts().addAll(beanContexts);
        } else {
            beanContexts = null;
        }
        final Map<String, Object> bindings = new HashMap<>();
        bindings.putAll(appContext.getBindings());
        bindings.putAll(new JndiEncBuilder(webAppInfo.jndiEnc, injections, webAppInfo.moduleId, "Bean", null, webAppInfo.uniqueId, classLoader, appInfo.properties).buildBindings(JndiEncBuilder.JndiScope.comp));
        final WebContext webContext = new WebContext(appContext);
        webContext.setBindings(bindings);
        webContext.getBindings().putAll(new JndiEncBuilder(webAppInfo.jndiEnc, injections, webAppInfo.moduleId, "Bean", null, webAppInfo.uniqueId, classLoader, appInfo.properties).buildBindings(JndiEncBuilder.JndiScope.comp));
        webContext.setJndiEnc(WebInitialContext.create(bindings, appContext.getGlobalJndiContext()));
        webContext.setClassLoader(classLoader);
        webContext.setId(webAppInfo.moduleId);
        webContext.setContextRoot(webAppInfo.contextRoot);
        webContext.setHost(webAppInfo.host);
        webContext.getInjections().addAll(injections);
        webContext.setInitialContext(new EmbeddedInitialContext(webContext.getJndiEnc(), webContext.getBindings()));
        final ServletContext component = SystemInstance.get().getComponent(ServletContext.class);
        final ServletContextEvent sce = component == null ? new MockServletContextEvent() : new ServletContextEvent(new LightServletContext(component, webContext.getClassLoader()));
        servletContextEvents.put(webAppInfo, sce);
        webContext.setServletContext(sce.getServletContext());
        SystemInstance.get().fireEvent(new EmbeddedServletContextCreated(sce.getServletContext()));
        appContext.getWebContexts().add(webContext);
        cs.addWebContext(webContext);
        if (!appInfo.webAppAlone && hasCdi(appInfo)) {
            final Assembler assembler = SystemInstance.get().getComponent(Assembler.class);
            new CdiBuilder().build(appInfo, appContext, beanContexts, webContext);
            assembler.startEjbs(true, beanContexts);
        }
        // listeners
        for (final ListenerInfo listener : webAppInfo.listeners) {
            final Class<?> clazz = webContext.getClassLoader().loadClass(listener.classname);
            final Object instance = webContext.newInstance(clazz);
            if (ServletContextListener.class.isInstance(instance)) {
                switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                    @Override
                    public void run() {
                        ((ServletContextListener) instance).contextInitialized(sce);
                    }
                });
            }
            List<Object> list = listeners.computeIfAbsent(webAppInfo, k -> new ArrayList<>());
            list.add(instance);
        }
        for (final ClassListInfo info : webAppInfo.webAnnotatedClasses) {
            final String url = info.name;
            for (final String filterPath : info.list) {
                final Class<?> clazz = loadFromUrls(webContext.getClassLoader(), url, filterPath);
                final WebListener annotation = clazz.getAnnotation(WebListener.class);
                if (annotation != null) {
                    final Object instance = webContext.newInstance(clazz);
                    if (ServletContextListener.class.isInstance(instance)) {
                        switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                            @Override
                            public void run() {
                                ((ServletContextListener) instance).contextInitialized(sce);
                            }
                        });
                    }
                    List<Object> list = listeners.computeIfAbsent(webAppInfo, k -> new ArrayList<>());
                    list.add(instance);
                }
            }
        }
        final DeployedWebObjects deployedWebObjects = new DeployedWebObjects();
        deployedWebObjects.webContext = webContext;
        servletDeploymentInfo.put(webAppInfo, deployedWebObjects);
        if (webContext.getWebBeansContext() != null && webContext.getWebBeansContext().getBeanManagerImpl().isInUse()) {
            final Thread thread = Thread.currentThread();
            final ClassLoader old = thread.getContextClassLoader();
            thread.setContextClassLoader(webContext.getClassLoader());
            try {
                OpenEJBLifecycle.class.cast(webContext.getWebBeansContext().getService(ContainerLifecycle.class)).startServletContext(sce.getServletContext());
            } finally {
                thread.setContextClassLoader(old);
            }
        }
        if (addServletMethod == null) {
            // can't manage filter/servlets
            continue;
        }
        // register filters
        for (final FilterInfo info : webAppInfo.filters) {
            switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                @Override
                public void run() {
                    for (final String mapping : info.mappings) {
                        final FilterConfig config = new SimpleFilterConfig(sce.getServletContext(), info.name, info.initParams);
                        try {
                            addFilterMethod.invoke(null, info.classname, webContext, mapping, config);
                            deployedWebObjects.filterMappings.add(mapping);
                        } catch (final Exception e) {
                            LOGGER.warning(e.getMessage(), e);
                        }
                    }
                }
            });
        }
        for (final ClassListInfo info : webAppInfo.webAnnotatedClasses) {
            final String url = info.name;
            for (final String filterPath : info.list) {
                final Class<?> clazz = loadFromUrls(webContext.getClassLoader(), url, filterPath);
                final WebFilter annotation = clazz.getAnnotation(WebFilter.class);
                if (annotation != null) {
                    final Properties initParams = new Properties();
                    for (final WebInitParam param : annotation.initParams()) {
                        initParams.put(param.name(), param.value());
                    }
                    final FilterConfig config = new SimpleFilterConfig(sce.getServletContext(), info.name, initParams);
                    for (final String[] mappings : asList(annotation.urlPatterns(), annotation.value())) {
                        switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                            @Override
                            public void run() {
                                for (final String mapping : mappings) {
                                    try {
                                        addFilterMethod.invoke(null, clazz.getName(), webContext, mapping, config);
                                        deployedWebObjects.filterMappings.add(mapping);
                                    } catch (final Exception e) {
                                        LOGGER.warning(e.getMessage(), e);
                                    }
                                }
                            }
                        });
                    }
                }
            }
        }
        final Map<String, PortInfo> ports = new TreeMap<>();
        for (final PortInfo port : webAppInfo.portInfos) {
            ports.put(port.serviceLink, port);
        }
        // register servlets
        for (final ServletInfo info : webAppInfo.servlets) {
            if ("true".equalsIgnoreCase(appInfo.properties.getProperty("openejb.jaxrs.on", "true"))) {
                // skip jaxrs servlets
                boolean skip = false;
                for (final ParamValueInfo pvi : info.initParams) {
                    if ("jakarta.ws.rs.Application".equals(pvi.name) || Application.class.getName().equals(pvi.name)) {
                        skip = true;
                    }
                }
                if (skip) {
                    continue;
                }
                if (info.servletClass == null) {
                    try {
                        if (Application.class.isAssignableFrom(classLoader.loadClass(info.servletName))) {
                            continue;
                        }
                    } catch (final Exception e) {
                    // no-op
                    }
                }
            }
            // If POJO web services, it will be overriden with WsServlet
            if (ports.containsKey(info.servletName) || ports.containsKey(info.servletClass)) {
                continue;
            }
            // deploy
            for (final String mapping : info.mappings) {
                switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                    @Override
                    public void run() {
                        try {
                            addServletMethod.invoke(null, info.servletClass, webContext, mapping);
                            deployedWebObjects.mappings.add(mapping);
                        } catch (final Exception e) {
                            LOGGER.warning(e.getMessage(), e);
                        }
                    }
                });
            }
        }
        for (final ClassListInfo info : webAppInfo.webAnnotatedClasses) {
            final String url = info.name;
            for (final String servletPath : info.list) {
                final Class<?> clazz = loadFromUrls(webContext.getClassLoader(), url, servletPath);
                final WebServlet annotation = clazz.getAnnotation(WebServlet.class);
                if (annotation != null) {
                    for (final String[] mappings : asList(annotation.urlPatterns(), annotation.value())) {
                        switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                            @Override
                            public void run() {
                                for (final String mapping : mappings) {
                                    try {
                                        addServletMethod.invoke(null, clazz.getName(), webContext, mapping);
                                        deployedWebObjects.mappings.add(mapping);
                                    } catch (final Exception e) {
                                        LOGGER.warning(e.getMessage(), e);
                                    }
                                }
                            }
                        });
                    }
                }
            }
        }
        if (addDefaults != null && tryJsp()) {
            addDefaults.invoke(null, webContext);
            deployedWebObjects.mappings.add("*\\.jsp");
        }
    }
}
Also used : CoreContainerSystem(org.apache.openejb.core.CoreContainerSystem) ContainerSystem(org.apache.openejb.spi.ContainerSystem) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ServletInfo(org.apache.openejb.assembler.classic.ServletInfo) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) ParamValueInfo(org.apache.openejb.assembler.classic.ParamValueInfo) FilterConfig(jakarta.servlet.FilterConfig) HashSet(java.util.HashSet) InjectionBuilder(org.apache.openejb.assembler.classic.InjectionBuilder) CoreContainerSystem(org.apache.openejb.core.CoreContainerSystem) Injection(org.apache.openejb.Injection) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) BeanContext(org.apache.openejb.BeanContext) ListenerInfo(org.apache.openejb.assembler.classic.ListenerInfo) CdiBuilder(org.apache.openejb.cdi.CdiBuilder) Assembler(org.apache.openejb.assembler.classic.Assembler) OpenEJBLifecycle(org.apache.openejb.cdi.OpenEJBLifecycle) WebContext(org.apache.openejb.core.WebContext) MockServletContextEvent(org.apache.webbeans.web.lifecycle.test.MockServletContextEvent) Properties(java.util.Properties) ClassListInfo(org.apache.openejb.assembler.classic.ClassListInfo) PortInfo(org.apache.openejb.assembler.classic.PortInfo) WebServlet(jakarta.servlet.annotation.WebServlet) MockServletContext(org.apache.webbeans.web.lifecycle.test.MockServletContext) ServletContext(jakarta.servlet.ServletContext) FilterInfo(org.apache.openejb.assembler.classic.FilterInfo) WebFilter(jakarta.servlet.annotation.WebFilter) AppContext(org.apache.openejb.AppContext) TreeMap(java.util.TreeMap) NamingException(javax.naming.NamingException) NameNotFoundException(javax.naming.NameNotFoundException) MalformedURLException(java.net.MalformedURLException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) WebListener(jakarta.servlet.annotation.WebListener) JndiEncBuilder(org.apache.openejb.assembler.classic.JndiEncBuilder) WebInitParam(jakarta.servlet.annotation.WebInitParam) ServletContextEvent(jakarta.servlet.ServletContextEvent) MockServletContextEvent(org.apache.webbeans.web.lifecycle.test.MockServletContextEvent)

Example 3 with WebServlet

use of jakarta.servlet.annotation.WebServlet in project org.openntf.xsp.jakartaee by OpenNTF.

the class ServletServletFactory method getExecutorServlet.

private javax.servlet.Servlet getExecutorServlet(WebServlet mapping, Class<? extends Servlet> c) {
    checkInvalidate();
    return this.servlets.computeIfAbsent(c, key -> {
        try {
            Servlet delegate;
            if (LibraryUtil.usesLibrary(CDILibrary.LIBRARY_ID, this.module)) {
                delegate = CDI.current().select(c).get();
            } else {
                delegate = c.newInstance();
            }
            Servlet wrapper = new XspServletWrapper(module, delegate);
            Map<String, String> params = Arrays.stream(mapping.initParams()).collect(Collectors.toMap(WebInitParam::name, WebInitParam::value));
            return module.createServlet(ServletUtil.newToOld(wrapper), mapping.name(), params);
        } catch (InstantiationException | IllegalAccessException | ServletException e) {
            throw new RuntimeException(e);
        }
    });
}
Also used : ServletException(javax.servlet.ServletException) Servlet(jakarta.servlet.Servlet) WebServlet(jakarta.servlet.annotation.WebServlet)

Example 4 with WebServlet

use of jakarta.servlet.annotation.WebServlet in project org.openntf.xsp.jakartaee by OpenNTF.

the class ServletServletFactory method getServletMatch.

@Override
public final ServletMatch getServletMatch(String contextPath, String path) throws javax.servlet.ServletException {
    try {
        if (LibraryUtil.usesLibrary(ServletLibrary.LIBRARY_ID, module)) {
            for (Map.Entry<WebServlet, Class<? extends Servlet>> entry : getModuleServlets().entrySet()) {
                String match = matches(entry.getKey(), path);
                if (match != null) {
                    javax.servlet.Servlet servlet = getExecutorServlet(entry.getKey(), entry.getValue());
                    String pathInfo = findPathInfo(path, match);
                    int pathInfoLen = pathInfo == null ? 0 : pathInfo.length();
                    return new ServletMatch(servlet, path.substring(0, path.length() - pathInfoLen), pathInfo);
                }
            }
        }
    } catch (UncheckedIOException e) {
        throw new javax.servlet.ServletException(e);
    }
    return null;
}
Also used : ServletMatch(com.ibm.designer.runtime.domino.adapter.ServletMatch) WebServlet(jakarta.servlet.annotation.WebServlet) ServletException(javax.servlet.ServletException) Servlet(jakarta.servlet.Servlet) WebServlet(jakarta.servlet.annotation.WebServlet) UncheckedIOException(java.io.UncheckedIOException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with WebServlet

use of jakarta.servlet.annotation.WebServlet in project today-framework by TAKETODAY.

the class WebServletApplicationLoader method configureServletInitializers.

/**
 * Configure {@link Servlet}
 *
 * @param applicationContext {@link ApplicationContext}
 * @param contextInitializers {@link WebApplicationInitializer}s
 */
protected void configureServletInitializers(WebApplicationContext applicationContext, List<WebApplicationInitializer> contextInitializers) {
    Collection<Servlet> servlets = applicationContext.getAnnotatedBeans(WebServlet.class);
    for (Servlet servlet : servlets) {
        Class<?> beanClass = servlet.getClass();
        WebServletInitializer<Servlet> webServletInitializer = new WebServletInitializer<>(servlet);
        WebServlet webServlet = beanClass.getAnnotation(WebServlet.class);
        String[] urlPatterns = webServlet.urlPatterns();
        if (ObjectUtils.isEmpty(urlPatterns)) {
            urlPatterns = new String[] { BeanDefinitionBuilder.defaultBeanName(beanClass) };
        }
        webServletInitializer.addUrlMappings(urlPatterns);
        webServletInitializer.setLoadOnStartup(webServlet.loadOnStartup());
        webServletInitializer.setAsyncSupported(webServlet.asyncSupported());
        for (WebInitParam initParam : webServlet.initParams()) {
            webServletInitializer.addInitParameter(initParam.name(), initParam.value());
        }
        MultipartConfig multipartConfig = beanClass.getAnnotation(MultipartConfig.class);
        if (multipartConfig != null) {
            webServletInitializer.setMultipartConfig(new MultipartConfigElement(multipartConfig));
        }
        ServletSecurity servletSecurity = beanClass.getAnnotation(ServletSecurity.class);
        if (servletSecurity != null) {
            webServletInitializer.setServletSecurity(new ServletSecurityElement(servletSecurity));
        }
        String name = webServlet.name();
        if (StringUtils.isEmpty(name)) {
            String displayName = webServlet.displayName();
            if (StringUtils.isEmpty(displayName)) {
                name = BeanDefinitionBuilder.defaultBeanName(beanClass);
            } else {
                name = displayName;
            }
        }
        webServletInitializer.setName(name);
        contextInitializers.add(webServletInitializer);
    }
}
Also used : ServletSecurity(jakarta.servlet.annotation.ServletSecurity) ServletSecurityElement(jakarta.servlet.ServletSecurityElement) MultipartConfigElement(jakarta.servlet.MultipartConfigElement) WebServlet(jakarta.servlet.annotation.WebServlet) MultipartConfig(jakarta.servlet.annotation.MultipartConfig) WebInitParam(jakarta.servlet.annotation.WebInitParam) Servlet(jakarta.servlet.Servlet) WebServlet(jakarta.servlet.annotation.WebServlet) WebServletInitializer(cn.taketoday.web.servlet.initializer.WebServletInitializer)

Aggregations

WebServlet (jakarta.servlet.annotation.WebServlet)5 Servlet (jakarta.servlet.Servlet)3 WebInitParam (jakarta.servlet.annotation.WebInitParam)2 HashMap (java.util.HashMap)2 ServletException (javax.servlet.ServletException)2 WebServletInitializer (cn.taketoday.web.servlet.initializer.WebServletInitializer)1 ServletMatch (com.ibm.designer.runtime.domino.adapter.ServletMatch)1 FilterConfig (jakarta.servlet.FilterConfig)1 MultipartConfigElement (jakarta.servlet.MultipartConfigElement)1 ServletContext (jakarta.servlet.ServletContext)1 ServletContextEvent (jakarta.servlet.ServletContextEvent)1 ServletException (jakarta.servlet.ServletException)1 ServletSecurityElement (jakarta.servlet.ServletSecurityElement)1 MultipartConfig (jakarta.servlet.annotation.MultipartConfig)1 ServletSecurity (jakarta.servlet.annotation.ServletSecurity)1 WebFilter (jakarta.servlet.annotation.WebFilter)1 WebListener (jakarta.servlet.annotation.WebListener)1 UncheckedIOException (java.io.UncheckedIOException)1 Method (java.lang.reflect.Method)1 MalformedURLException (java.net.MalformedURLException)1