Search in sources :

Example 1 with ServletMapping

use of org.eclipse.jetty.servlet.ServletMapping in project jetty.project by eclipse.

the class TestServletAnnotations method testServletAnnotation.

@Test
public void testServletAnnotation() throws Exception {
    List<String> classes = new ArrayList<String>();
    classes.add("org.eclipse.jetty.annotations.ServletC");
    AnnotationParser parser = new AnnotationParser();
    WebAppContext wac = new WebAppContext();
    List<DiscoveredAnnotation> results = new ArrayList<DiscoveredAnnotation>();
    TestWebServletAnnotationHandler handler = new TestWebServletAnnotationHandler(wac, results);
    parser.parse(Collections.singleton(handler), classes);
    assertEquals(1, results.size());
    assertTrue(results.get(0) instanceof WebServletAnnotation);
    results.get(0).apply();
    ServletHolder[] holders = wac.getServletHandler().getServlets();
    assertNotNull(holders);
    assertEquals(1, holders.length);
    // Verify servlet annotations
    ServletHolder cholder = holders[0];
    assertThat("Servlet Name", cholder.getName(), is("CServlet"));
    assertThat("InitParameter[x]", cholder.getInitParameter("x"), is("y"));
    assertThat("Init Order", cholder.getInitOrder(), is(2));
    assertThat("Async Supported", cholder.isAsyncSupported(), is(false));
    // Verify mappings
    ServletMapping[] mappings = wac.getServletHandler().getServletMappings();
    assertNotNull(mappings);
    assertEquals(1, mappings.length);
    String[] paths = mappings[0].getPathSpecs();
    assertNotNull(paths);
    assertEquals(2, paths.length);
}
Also used : ServletMapping(org.eclipse.jetty.servlet.ServletMapping) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ArrayList(java.util.ArrayList) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) DiscoveredAnnotation(org.eclipse.jetty.webapp.DiscoveredAnnotation) Test(org.junit.Test)

Example 2 with ServletMapping

use of org.eclipse.jetty.servlet.ServletMapping 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 3 with ServletMapping

use of org.eclipse.jetty.servlet.ServletMapping in project jetty.project by eclipse.

the class TestSecurityAnnotationConversions method makeWebAppContext.

private WebAppContext makeWebAppContext(String className, String servletName, String[] paths) {
    WebAppContext wac = new WebAppContext();
    ServletHolder[] holders = new ServletHolder[1];
    holders[0] = new ServletHolder();
    holders[0].setClassName(className);
    holders[0].setName(servletName);
    holders[0].setServletHandler(wac.getServletHandler());
    wac.getServletHandler().setServlets(holders);
    wac.setSecurityHandler(new ConstraintSecurityHandler());
    ServletMapping[] servletMappings = new ServletMapping[1];
    servletMappings[0] = new ServletMapping();
    servletMappings[0].setPathSpecs(paths);
    servletMappings[0].setServletName(servletName);
    wac.getServletHandler().setServletMappings(servletMappings);
    return wac;
}
Also used : WebAppContext(org.eclipse.jetty.webapp.WebAppContext) ServletMapping(org.eclipse.jetty.servlet.ServletMapping) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler)

Example 4 with ServletMapping

use of org.eclipse.jetty.servlet.ServletMapping in project jetty.project by eclipse.

the class TestServletAnnotations method testWebServletAnnotationNoMappings.

@Test
public void testWebServletAnnotationNoMappings() throws Exception {
    //an existing servlet OF THE SAME NAME has no mappings, therefore all mappings in the annotation
    //should be accepted
    WebAppContext wac = new WebAppContext();
    ServletHolder servlet = new ServletHolder();
    servlet.setName("foo");
    wac.getServletHandler().addServlet(servlet);
    WebServletAnnotation annotation = new WebServletAnnotation(wac, "org.eclipse.jetty.annotations.ServletD", null);
    annotation.apply();
    ServletMapping[] resultMappings = wac.getServletHandler().getServletMappings();
    assertEquals(1, resultMappings.length);
    assertEquals(2, resultMappings[0].getPathSpecs().length);
    for (String s : resultMappings[0].getPathSpecs()) {
        if (!s.equals("/") && !s.equals("/bah/*"))
            fail("Unexpected path mapping");
    }
}
Also used : WebAppContext(org.eclipse.jetty.webapp.WebAppContext) ServletMapping(org.eclipse.jetty.servlet.ServletMapping) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) Test(org.junit.Test)

Example 5 with ServletMapping

use of org.eclipse.jetty.servlet.ServletMapping in project jetty.project by eclipse.

the class TestServletAnnotations method testWebServletAnnotationNotOverride.

@Test
public void testWebServletAnnotationNotOverride() throws Exception {
    //if the existing servlet mapping TO A DIFFERENT SERVLET IS NOT from a default descriptor we
    //DO NOT allow the annotation to replace the mapping
    WebAppContext wac = new WebAppContext();
    ServletHolder servlet = new ServletHolder();
    servlet.setClassName("org.eclipse.jetty.servlet.FooServlet");
    servlet.setName("foo");
    wac.getServletHandler().addServlet(servlet);
    ServletMapping m = new ServletMapping();
    m.setPathSpec("/");
    m.setServletName("foo");
    wac.getServletHandler().addServletMapping(m);
    WebServletAnnotation annotation = new WebServletAnnotation(wac, "org.eclipse.jetty.annotations.ServletD", null);
    annotation.apply();
    ServletMapping[] resultMappings = wac.getServletHandler().getServletMappings();
    assertEquals(2, resultMappings.length);
    for (ServletMapping r : resultMappings) {
        if (r.getServletName().equals("DServlet")) {
            assertEquals(2, r.getPathSpecs().length);
        } else if (r.getServletName().equals("foo")) {
            assertEquals(1, r.getPathSpecs().length);
        } else
            fail("Unexpected servlet name");
    }
}
Also used : WebAppContext(org.eclipse.jetty.webapp.WebAppContext) ServletMapping(org.eclipse.jetty.servlet.ServletMapping) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) Test(org.junit.Test)

Aggregations

ServletMapping (org.eclipse.jetty.servlet.ServletMapping)23 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)16 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)7 ArrayList (java.util.ArrayList)6 Test (org.junit.Test)6 ServletHandler (org.eclipse.jetty.servlet.ServletHandler)3 Source (org.eclipse.jetty.servlet.Source)3 ConstraintAware (org.eclipse.jetty.security.ConstraintAware)2 ConstraintMapping (org.eclipse.jetty.security.ConstraintMapping)2 FilterMapping (org.eclipse.jetty.servlet.FilterMapping)2 JspConfig (org.eclipse.jetty.servlet.ServletContextHandler.JspConfig)2 Constraint (org.eclipse.jetty.util.security.Constraint)2 MetaData (org.eclipse.jetty.webapp.MetaData)2 Node (org.eclipse.jetty.xml.XmlParser.Node)2 MalformedURLException (java.net.MalformedURLException)1 CertificateException (java.security.cert.CertificateException)1 EventListener (java.util.EventListener)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Servlet (javax.servlet.Servlet)1