Search in sources :

Example 1 with WebServlet

use of javax.servlet.annotation.WebServlet in project jetty.project by eclipse.

the class WebServletAnnotation method apply.

/**
     * @see DiscoveredAnnotation#apply()
     */
public void apply() {
    //TODO check this algorithm with new rules for applying descriptors and annotations in order
    Class<? extends Servlet> clazz = (Class<? extends Servlet>) getTargetClass();
    if (clazz == null) {
        LOG.warn(_className + " cannot be loaded");
        return;
    }
    //Servlet Spec 8.1.1
    if (!HttpServlet.class.isAssignableFrom(clazz)) {
        LOG.warn(clazz.getName() + " is not assignable from javax.servlet.http.HttpServlet");
        return;
    }
    WebServlet annotation = (WebServlet) clazz.getAnnotation(WebServlet.class);
    if (annotation.urlPatterns().length > 0 && annotation.value().length > 0) {
        LOG.warn(clazz.getName() + " defines both @WebServlet.value and @WebServlet.urlPatterns");
        return;
    }
    String[] urlPatterns = annotation.value();
    if (urlPatterns.length == 0)
        urlPatterns = annotation.urlPatterns();
    if (urlPatterns.length == 0) {
        LOG.warn(clazz.getName() + " defines neither @WebServlet.value nor @WebServlet.urlPatterns");
        return;
    }
    //canonicalize the patterns
    ArrayList<String> urlPatternList = new ArrayList<String>();
    for (String p : urlPatterns) urlPatternList.add(ServletPathSpec.normalize(p));
    String servletName = (annotation.name().equals("") ? clazz.getName() : annotation.name());
    MetaData metaData = _context.getMetaData();
    //the new mapping
    ServletMapping mapping = null;
    //Find out if a <servlet> already exists with this name
    ServletHolder[] holders = _context.getServletHandler().getServlets();
    ServletHolder holder = null;
    if (holders != null) {
        for (ServletHolder h : holders) {
            if (h.getName() != null && servletName.equals(h.getName())) {
                holder = h;
                break;
            }
        }
    }
    //handle creation/completion of a servlet
    if (holder == null) {
        //No servlet of this name has already been defined, either by a descriptor
        //or another annotation (which would be impossible).
        Source source = new Source(Source.Origin.ANNOTATION, clazz.getName());
        holder = _context.getServletHandler().newServletHolder(source);
        holder.setHeldClass(clazz);
        metaData.setOrigin(servletName + ".servlet.servlet-class", annotation, clazz);
        holder.setName(servletName);
        holder.setDisplayName(annotation.displayName());
        metaData.setOrigin(servletName + ".servlet.display-name", annotation, clazz);
        holder.setInitOrder(annotation.loadOnStartup());
        metaData.setOrigin(servletName + ".servlet.load-on-startup", annotation, clazz);
        holder.setAsyncSupported(annotation.asyncSupported());
        metaData.setOrigin(servletName + ".servlet.async-supported", annotation, clazz);
        for (WebInitParam ip : annotation.initParams()) {
            holder.setInitParameter(ip.name(), ip.value());
            metaData.setOrigin(servletName + ".servlet.init-param." + ip.name(), ip, clazz);
        }
        _context.getServletHandler().addServlet(holder);
        mapping = new ServletMapping(source);
        mapping.setServletName(holder.getName());
        mapping.setPathSpecs(LazyList.toStringArray(urlPatternList));
    } else {
        //can complete it, see http://java.net/jira/browse/SERVLET_SPEC-42
        if (holder.getClassName() == null)
            holder.setClassName(clazz.getName());
        if (holder.getHeldClass() == null)
            holder.setHeldClass(clazz);
        //if not, add it
        for (WebInitParam ip : annotation.initParams()) {
            if (metaData.getOrigin(servletName + ".servlet.init-param." + ip.name()) == Origin.NotSet) {
                holder.setInitParameter(ip.name(), ip.value());
                metaData.setOrigin(servletName + ".servlet.init-param." + ip.name(), ip, clazz);
            }
        }
        //check the url-patterns
        //ServletSpec 3.0 p81 If a servlet already has url mappings from a
        //webxml or fragment descriptor the annotation is ignored.
        //However, we want to be able to replace mappings that were given in webdefault.xml
        List<ServletMapping> existingMappings = getServletMappingsForServlet(servletName);
        //about processing these url mappings
        if (existingMappings.isEmpty() || !containsNonDefaultMappings(existingMappings)) {
            mapping = new ServletMapping(new Source(Source.Origin.ANNOTATION, clazz.getName()));
            mapping.setServletName(servletName);
            mapping.setPathSpecs(LazyList.toStringArray(urlPatternList));
        }
    }
    //servlet
    if (mapping != null) {
        //url mapping was permitted by annotation processing rules
        //take a copy of the existing servlet mappings that we can iterate over and remove from. This is
        //because the ServletHandler interface does not support removal of individual mappings.
        List<ServletMapping> allMappings = ArrayUtil.asMutableList(_context.getServletHandler().getServletMappings());
        //  guard against duplicate path mapping here: that is the job of the ServletHandler
        for (String p : urlPatternList) {
            ServletMapping existingMapping = _context.getServletHandler().getServletMapping(p);
            if (existingMapping != null && existingMapping.isDefault()) {
                String[] updatedPaths = ArrayUtil.removeFromArray(existingMapping.getPathSpecs(), p);
                //if we removed the last path from a servletmapping, delete the servletmapping
                if (updatedPaths == null || updatedPaths.length == 0) {
                    boolean success = allMappings.remove(existingMapping);
                    if (LOG.isDebugEnabled())
                        LOG.debug("Removed empty mapping {} from defaults descriptor success:{}", existingMapping, success);
                } else {
                    existingMapping.setPathSpecs(updatedPaths);
                    if (LOG.isDebugEnabled())
                        LOG.debug("Removed path {} from mapping {} from defaults descriptor ", p, existingMapping);
                }
            }
            _context.getMetaData().setOrigin(servletName + ".servlet.mapping." + p, annotation, clazz);
        }
        allMappings.add(mapping);
        _context.getServletHandler().setServletMappings(allMappings.toArray(new ServletMapping[allMappings.size()]));
    }
}
Also used : ServletMapping(org.eclipse.jetty.servlet.ServletMapping) HttpServlet(javax.servlet.http.HttpServlet) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ArrayList(java.util.ArrayList) Source(org.eclipse.jetty.servlet.Source) WebServlet(javax.servlet.annotation.WebServlet) MetaData(org.eclipse.jetty.webapp.MetaData) WebInitParam(javax.servlet.annotation.WebInitParam) HttpServlet(javax.servlet.http.HttpServlet) Servlet(javax.servlet.Servlet) WebServlet(javax.servlet.annotation.WebServlet)

Example 2 with WebServlet

use of javax.servlet.annotation.WebServlet in project dropwizard-guicey by xvik.

the class WebServletInstaller method install.

@Override
public void install(final Environment environment, final HttpServlet instance) {
    final Class<? extends HttpServlet> extType = FeatureUtils.getInstanceClass(instance);
    final WebServlet annotation = FeatureUtils.getAnnotation(extType, WebServlet.class);
    final String[] patterns = annotation.urlPatterns().length > 0 ? annotation.urlPatterns() : annotation.value();
    Preconditions.checkArgument(patterns.length > 0, "Servlet %s not specified url pattern for mapping", extType.getName());
    final AdminContext context = FeatureUtils.getAnnotation(extType, AdminContext.class);
    final String name = WebUtils.getServletName(annotation, extType);
    reporter.line("%-15s %-5s %-2s (%s)   %s", Joiner.on(",").join(patterns), WebUtils.getAsyncMarker(annotation), WebUtils.getContextMarkers(context), extType.getName(), name);
    if (WebUtils.isForMain(context)) {
        configure(environment.servlets(), instance, extType, name, annotation);
    }
    if (WebUtils.isForAdmin(context)) {
        configure(environment.admin(), instance, extType, name, annotation);
    }
}
Also used : WebServlet(javax.servlet.annotation.WebServlet)

Example 3 with WebServlet

use of javax.servlet.annotation.WebServlet in project Payara by payara.

the class WebServletHandler method processAnnotation.

private HandlerProcessingResult processAnnotation(AnnotationInfo ainfo, WebComponentDescriptor webCompDesc) throws AnnotationProcessorException {
    Class webCompClass = (Class) ainfo.getAnnotatedElement();
    if (!HttpServlet.class.isAssignableFrom(webCompClass)) {
        log(Level.SEVERE, ainfo, localStrings.getLocalString("web.deployment.annotation.handlers.needtoextend", "The Class {0} having annotation {1} need to be a derived class of {2}.", new Object[] { webCompClass.getName(), WebServlet.class.getName(), HttpServlet.class.getName() }));
        return getDefaultFailedResult();
    }
    WebServlet webServletAn = (WebServlet) ainfo.getAnnotation();
    String servletName = getServletName(webServletAn, webCompClass);
    if (!servletName.equals(webCompDesc.getCanonicalName())) {
        // skip the processing as it is not for given webCompDesc
        return getDefaultProcessedResult();
    }
    String webCompImpl = webCompDesc.getWebComponentImplementation();
    if (webCompImpl != null && webCompImpl.length() > 0 && (!webCompImpl.equals(webCompClass.getName()) || !webCompDesc.isServlet())) {
        String messageKey = null;
        String defaultMessage = null;
        if (webCompDesc.isServlet()) {
            messageKey = "web.deployment.annotation.handlers.servletimpldontmatch";
            defaultMessage = "The servlet ''{0}'' has implementation ''{1}'' in xml. It does not match with ''{2}'' from annotation @{3}.";
        } else {
            messageKey = "web.deployment.annotation.handlers.servletimpljspdontmatch";
            defaultMessage = "The servlet ''{0}'' is a jsp ''{1}'' in xml. It does not match with ''{2}'' from annotation @{3}.";
        }
        log(Level.SEVERE, ainfo, localStrings.getLocalString(messageKey, defaultMessage, new Object[] { webCompDesc.getCanonicalName(), webCompImpl, webCompClass.getName(), WebServlet.class.getName() }));
        return getDefaultFailedResult();
    }
    webCompDesc.setServlet(true);
    webCompDesc.setWebComponentImplementation(webCompClass.getName());
    if (webCompDesc.getUrlPatternsSet().isEmpty()) {
        String[] urlPatterns = webServletAn.urlPatterns();
        if (urlPatterns == null || urlPatterns.length == 0) {
            urlPatterns = webServletAn.value();
        }
        // no url patterns is accepted as it may be defined in top level xml
        boolean validUrlPatterns = true;
        if (urlPatterns != null && urlPatterns.length > 0) {
            for (String up : urlPatterns) {
                if (!URLPattern.isValid(up)) {
                    validUrlPatterns = false;
                    break;
                }
                webCompDesc.addUrlPattern(TranslatedConfigView.expandValue(up));
            }
        }
        if (!validUrlPatterns) {
            String urlPatternString = (urlPatterns != null) ? Arrays.toString(urlPatterns) : "";
            throw new IllegalArgumentException(localStrings.getLocalString("web.deployment.annotation.handlers.invalidUrlPatterns", "Invalid url patterns for {0}: {1}.", new Object[] { webCompClass, urlPatternString }));
        }
    }
    if (webCompDesc.getLoadOnStartUp() == null) {
        webCompDesc.setLoadOnStartUp(webServletAn.loadOnStartup());
    }
    WebInitParam[] initParams = webServletAn.initParams();
    if (initParams != null && initParams.length > 0) {
        for (WebInitParam initParam : initParams) {
            webCompDesc.addInitializationParameter(new EnvironmentProperty(initParam.name(), TranslatedConfigView.expandValue(initParam.value()), initParam.description()));
        }
    }
    if (webCompDesc.getSmallIconUri() == null) {
        webCompDesc.setSmallIconUri(webServletAn.smallIcon());
    }
    if (webCompDesc.getLargeIconUri() == null) {
        webCompDesc.setLargeIconUri(webServletAn.largeIcon());
    }
    if (webCompDesc.getDescription() == null || webCompDesc.getDescription().length() == 0) {
        webCompDesc.setDescription(webServletAn.description());
    }
    if (webCompDesc.getDisplayName() == null || webCompDesc.getDisplayName().length() == 0) {
        webCompDesc.setDisplayName(webServletAn.displayName());
    }
    if (webCompDesc.isAsyncSupported() == null) {
        webCompDesc.setAsyncSupported(webServletAn.asyncSupported());
    }
    return getDefaultProcessedResult();
}
Also used : WebServlet(javax.servlet.annotation.WebServlet) HttpServlet(javax.servlet.http.HttpServlet) EnvironmentProperty(com.sun.enterprise.deployment.EnvironmentProperty) WebInitParam(javax.servlet.annotation.WebInitParam)

Example 4 with WebServlet

use of javax.servlet.annotation.WebServlet in project Payara by payara.

the class WebServletHandler method processAnnotation.

@Override
protected HandlerProcessingResult processAnnotation(AnnotationInfo ainfo, WebBundleContext webBundleContext) throws AnnotationProcessorException {
    WebServlet webServletAn = (WebServlet) ainfo.getAnnotation();
    Class webCompClass = (Class) ainfo.getAnnotatedElement();
    String servletName = getServletName(webServletAn, webCompClass);
    WebComponentDescriptor webCompDesc = webBundleContext.getDescriptor().getWebComponentByCanonicalName(servletName);
    if (webCompDesc == null) {
        webCompDesc = createWebComponentDescriptor(servletName, webCompClass, webBundleContext.getDescriptor());
    }
    HandlerProcessingResult result = processAnnotation(ainfo, webCompDesc);
    if (result.getOverallResult() == ResultType.PROCESSED) {
        WebComponentContext webCompContext = new WebComponentContext(webCompDesc);
        // we push the new context on the stack...
        webBundleContext.getProcessingContext().pushHandler(webCompContext);
    }
    return result;
}
Also used : WebComponentDescriptor(com.sun.enterprise.deployment.WebComponentDescriptor) WebServlet(javax.servlet.annotation.WebServlet) WebComponentContext(com.sun.enterprise.deployment.annotation.context.WebComponentContext)

Example 5 with WebServlet

use of javax.servlet.annotation.WebServlet in project Payara by payara.

the class WebServletHandler method processAnnotation.

@Override
public HandlerProcessingResult processAnnotation(AnnotationInfo ainfo) throws AnnotationProcessorException {
    ProcessingContext context = ainfo.getProcessingContext();
    AnnotatedElementHandler aeHandler = context.getHandler();
    if (aeHandler instanceof WebBundleContext) {
        WebBundleContext webBundleContext = (WebBundleContext) aeHandler;
        WebBundleDescriptor descriptor = webBundleContext.getDescriptor();
        WebServlet webServletAn = (WebServlet) ainfo.getAnnotation();
        Class servletClass = (Class) ainfo.getAnnotatedElement();
        String servletName = getServletName(webServletAn, servletClass);
        // create a WebComponentDescriptor if there is none
        WebComponentDescriptor webCompDesc = findWebComponentDescriptor(servletName, servletClass, descriptor, context);
        if (webCompDesc == null) {
            createWebComponentDescriptor(servletName, servletClass, descriptor);
        }
    }
    return super.processAnnotation(ainfo);
}
Also used : WebComponentDescriptor(com.sun.enterprise.deployment.WebComponentDescriptor) WebBundleContext(com.sun.enterprise.deployment.annotation.context.WebBundleContext) WebServlet(javax.servlet.annotation.WebServlet) WebBundleDescriptor(com.sun.enterprise.deployment.WebBundleDescriptor)

Aggregations

WebServlet (javax.servlet.annotation.WebServlet)9 ArrayList (java.util.ArrayList)3 WebInitParam (javax.servlet.annotation.WebInitParam)3 WebComponentDescriptor (com.sun.enterprise.deployment.WebComponentDescriptor)2 HttpServlet (javax.servlet.http.HttpServlet)2 EnvironmentProperty (com.sun.enterprise.deployment.EnvironmentProperty)1 WebBundleDescriptor (com.sun.enterprise.deployment.WebBundleDescriptor)1 WebBundleContext (com.sun.enterprise.deployment.annotation.context.WebBundleContext)1 WebComponentContext (com.sun.enterprise.deployment.annotation.context.WebComponentContext)1 MalformedURLException (java.net.MalformedURLException)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Properties (java.util.Properties)1 TreeMap (java.util.TreeMap)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 NameNotFoundException (javax.naming.NameNotFoundException)1 NamingException (javax.naming.NamingException)1 FilterConfig (javax.servlet.FilterConfig)1 Servlet (javax.servlet.Servlet)1 ServletContext (javax.servlet.ServletContext)1