org.apache.tomcat.util.descriptor.web.WebXml Java Examples

The following examples show how to use org.apache.tomcat.util.descriptor.web.WebXml. 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: ContextConfig.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private void convertJsps(WebXml webXml) {
    Map<String,String> jspInitParams;
    ServletDef jspServlet = webXml.getServlets().get("jsp");
    if (jspServlet == null) {
        jspInitParams = new HashMap<>();
        Wrapper w = (Wrapper) context.findChild("jsp");
        if (w != null) {
            String[] params = w.findInitParameters();
            for (String param : params) {
                jspInitParams.put(param, w.findInitParameter(param));
            }
        }
    } else {
        jspInitParams = jspServlet.getParameterMap();
    }
    for (ServletDef servletDef: webXml.getServlets().values()) {
        if (servletDef.getJspFile() != null) {
            convertJsp(servletDef, jspInitParams);
        }
    }
}
 
Example #2
Source File: TestContextConfigAnnotation.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testDuplicateFilterMapping() throws Exception {
    WebXml webxml = new WebXml();
    Map<String,JavaClassCacheEntry> javaClassCache = new HashMap<>();
    ContextConfig config = new ContextConfig();
    File pFile = paramClassResource(
            "org/apache/catalina/startup/DuplicateMappingParamFilter");
    Assert.assertTrue(pFile.exists());
    try {
        config.processAnnotationsFile(pFile, webxml, false, javaClassCache);
        Assert.fail();
    } catch (IllegalArgumentException ex) {
        // ignore
    }
    FilterDef filterDef = webxml.getFilters().get("paramD");
    Assert.assertNull(filterDef);
}
 
Example #3
Source File: TestContextConfigAnnotation.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testDuplicateMapping() throws Exception {
    WebXml webxml = new WebXml();
    Map<String,JavaClassCacheEntry> javaClassCache = new HashMap<>();
    ContextConfig config = new ContextConfig();
    File pFile = paramClassResource(
            "org/apache/catalina/startup/DuplicateMappingParamServlet");
    Assert.assertTrue(pFile.exists());
    try {
        config.processAnnotationsFile(pFile, webxml, false, javaClassCache);
        Assert.fail();
    } catch (IllegalArgumentException ex) {
        // ignore
    }
    ServletDef servletDef = webxml.getServlets().get("param");
    Assert.assertNull(servletDef);
}
 
Example #4
Source File: TestContextConfigAnnotation.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testSetupWebXMLNoMapping() throws Exception {
    WebXml webxml = new WebXml();
    Map<String,JavaClassCacheEntry> javaClassCache = new HashMap<>();
    ServletDef servletDef = new ServletDef();
    servletDef.setServletName("param1");
    servletDef.setServletClass(
            "org.apache.catalina.startup.NoMappingParamServlet");
    servletDef.addInitParameter("foo", "tomcat");

    webxml.addServlet(servletDef);
    webxml.addServletMapping("/param", "param1");
    ContextConfig config = new ContextConfig();
    File pFile = paramClassResource(
            "org/apache/catalina/startup/NoMappingParamServlet");
    Assert.assertTrue(pFile.exists());
    config.processAnnotationsFile(pFile, webxml, false, javaClassCache);
    Assert.assertEquals("tomcat", servletDef.getParameterMap().get("foo"));
    Assert.assertEquals("World!", servletDef.getParameterMap().get("bar"));
    ServletDef servletDef1 = webxml.getServlets().get("param1");
    Assert.assertNotNull(servletDef1);
    Assert.assertEquals(servletDef, servletDef1);
}
 
Example #5
Source File: TestContextConfigAnnotation.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testNoMapping() throws Exception {
    WebXml webxml = new WebXml();
    Map<String,JavaClassCacheEntry> javaClassCache = new HashMap<>();
    ContextConfig config = new ContextConfig();
    File pFile = paramClassResource(
            "org/apache/catalina/startup/NoMappingParamServlet");
    Assert.assertTrue(pFile.exists());
    config.processAnnotationsFile(pFile, webxml, false, javaClassCache);
    ServletDef servletDef = webxml.getServlets().get("param1");
    Assert.assertNull(servletDef);

    webxml.addServletMapping("/param", "param1");
    config.processAnnotationsFile(pFile, webxml, false, javaClassCache);
    servletDef = webxml.getServlets().get("param1");
    Assert.assertNull(servletDef);

}
 
Example #6
Source File: ControlServlet.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * SCIPIO: Locates the ControlServlet servlet definition in the given WebXml, or null
 * if does not appear to be present.
 * Best-effort operation.
 * <p>
 * Factored out and modified from stock method {@link org.ofbiz.webapp.WebAppUtil#getControlServletPath(WebappInfo, boolean)}.
 * <p>
 * SCIPIO: 2017-12-05: Adds subclass support, oddly missing from stock ofbiz code.
 * <p>
 * Added 2017-12.
 */
public static ServletDef getControlServletDefFromWebXml(WebXml webXml) {
    ServletDef bestServletDef = null;
    for (ServletDef servletDef : webXml.getServlets().values()) {
        String servletClassName = servletDef.getServletClass();
        // exact name is the original Ofbiz solution, return exact if found
        if (ControlServlet.class.getName().equals(servletClassName)) {
            return servletDef;
        }
        // we must now also check for class that extends ControlServlet (this will return the last one)
        if (servletClassName != null) {
            try {
                Class<?> cls = Thread.currentThread().getContextClassLoader().loadClass(servletClassName);
                if (ControlServlet.class.isAssignableFrom(cls)) bestServletDef = servletDef;
            } catch(Exception e) {
                // NOTE: 2018-05-11: this should not be a warning because this is a regular occurrence
                // for webapps which have servlet classes in libs under WEB-INF/lib
                //Debug.logWarning("Could not load or test servlet class (" + servletClassName + "); may be invalid or a classloader issue: "
                //        + e.getMessage(), module);
            }
        }
    }
    return bestServletDef;
}
 
Example #7
Source File: TestContextConfigAnnotation.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testAnnotation() throws Exception {
    WebXml webxml = new WebXml();
    Map<String,JavaClassCacheEntry> javaClassCache = new HashMap<>();
    ContextConfig config = new ContextConfig();
    File pFile = paramClassResource(
            "org/apache/catalina/startup/ParamServlet");
    Assert.assertTrue(pFile.exists());
    config.processAnnotationsFile(pFile, webxml, false, javaClassCache);
    ServletDef servletDef = webxml.getServlets().get("param");
    Assert.assertNotNull(servletDef);
    Assert.assertEquals("Hello", servletDef.getParameterMap().get("foo"));
    Assert.assertEquals("World!", servletDef.getParameterMap().get("bar"));
    Assert.assertEquals("param", webxml.getServletMappings().get(
            "/annotation/overwrite"));

    Assert.assertEquals("param", servletDef.getDescription());
    Assert.assertEquals("param", servletDef.getDisplayName());
    Assert.assertEquals("paramLarge.png", servletDef.getLargeIcon());
    Assert.assertEquals("paramSmall.png", servletDef.getSmallIcon());
    Assert.assertEquals(Boolean.FALSE, servletDef.getAsyncSupported());
    Assert.assertEquals(Integer.valueOf(0), servletDef.getLoadOnStartup());
    Assert.assertNull(servletDef.getEnabled());
    Assert.assertNull(servletDef.getJspFile());

}
 
Example #8
Source File: OpenEJBContextConfig.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
protected WebXml createWebXml() {
    String prefix = "";
    if (context instanceof StandardContext) {
        final StandardContext standardContext = (StandardContext) context;
        prefix = standardContext.getEncodedPath();
        if (prefix.startsWith("/")) {
            prefix = prefix.substring(1);
        }
    }
    final OpenEJBWebXml webXml = new OpenEJBWebXml(prefix);

    if (DEFERRED_SYNTAX != null) {
        for (final String s : DEFERRED_SYNTAX.split(",")) {
            if (!s.isEmpty()) {
                final JspPropertyGroup propertyGroup = new JspPropertyGroup();
                propertyGroup.addUrlPattern(s);
                propertyGroup.setDeferredSyntax("true");
                webXml.addJspPropertyGroup(propertyGroup);
            }
        }
    }

    return webXml;
}
 
Example #9
Source File: OpenEJBContextConfig.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
protected void processAnnotationsFile(final File file, final WebXml fragment, final boolean handlesTypesOnly,
                                      final Map<String,JavaClassCacheEntry> javaClassCache) {
    try {
        if (NewLoaderLogic.skip(file.toURI().toURL())) {
            return;
        }
    } catch (final MalformedURLException e) {
        // no-op: let it be
    }

    final WebAppInfo webAppInfo = info.get();
    if (webAppInfo == null) {
        super.processAnnotationsFile(file, fragment, handlesTypesOnly, javaClassCache);
        return;
    }

    internalProcessAnnotations(file, webAppInfo, fragment);
}
 
Example #10
Source File: ContextConfig.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
protected void processClass(WebXml fragment, JavaClass clazz) {
    AnnotationEntry[] annotationsEntries = clazz.getAnnotationEntries();
    if (annotationsEntries != null) {
        String className = clazz.getClassName();
        for (AnnotationEntry ae : annotationsEntries) {
            String type = ae.getAnnotationType();
            if ("Ljavax/servlet/annotation/WebServlet;".equals(type)) {
                processAnnotationWebServlet(className, ae, fragment);
            }else if ("Ljavax/servlet/annotation/WebFilter;".equals(type)) {
                processAnnotationWebFilter(className, ae, fragment);
            }else if ("Ljavax/servlet/annotation/WebListener;".equals(type)) {
                fragment.addListener(className);
            } else {
                // Unknown annotation - ignore
            }
        }
    }
}
 
Example #11
Source File: OpenEJBContextConfig.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
protected void processAnnotationsUrl(final URL currentUrl, final WebXml fragment, final boolean handlesTypeOnly,
                                     final Map<String,JavaClassCacheEntry> javaClassCache) {
    if (NewLoaderLogic.skip(currentUrl)) { // we potentially see all common loader urls
        return;
    }

    final WebAppInfo webAppInfo = info.get();
    if (webAppInfo == null) {
        super.processAnnotationsUrl(currentUrl, fragment, handlesTypeOnly, javaClassCache);
        return;
    }

    File currentUrlAsFile;
    try {
        currentUrlAsFile = URLs.toFile(currentUrl);
    } catch (final IllegalArgumentException iae) {
        logger.error("Don't know this url: " + currentUrl);
        return;
    }

    internalProcessAnnotations(currentUrlAsFile, webAppInfo, fragment);
}
 
Example #12
Source File: ContextConfig.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
protected void processAnnotationsUrl(URL url, WebXml fragment,
        boolean handlesTypesOnly, Map<String,JavaClassCacheEntry> javaClassCache) {
    if (url == null) {
        // Nothing to do.
        return;
    } else if ("jar".equals(url.getProtocol()) || url.toString().endsWith(".jar")) {
        processAnnotationsJar(url, fragment, handlesTypesOnly, javaClassCache);
    } else if ("file".equals(url.getProtocol())) {
        try {
            processAnnotationsFile(
                    new File(url.toURI()), fragment, handlesTypesOnly, javaClassCache);
        } catch (URISyntaxException e) {
            log.error(sm.getString("contextConfig.fileUrl", url), e);
        }
    } else {
        log.error(sm.getString("contextConfig.unknownUrlProtocol",
                url.getProtocol(), url));
    }

}
 
Example #13
Source File: ContextConfig.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
protected void processAnnotations(Set<WebXml> fragments,
        boolean handlesTypesOnly, Map<String,JavaClassCacheEntry> javaClassCache) {
    for(WebXml fragment : fragments) {
        // Only need to scan for @HandlesTypes matches if any of the
        // following are true:
        // - it has already been determined only @HandlesTypes is required
        //   (e.g. main web.xml has metadata-complete="true"
        // - this fragment is for a container JAR (Servlet 3.1 section 8.1)
        // - this fragment has metadata-complete="true"
        boolean htOnly = handlesTypesOnly || !fragment.getWebappJar() ||
                fragment.isMetadataComplete();

        WebXml annotations = new WebXml();
        // no impact on distributable
        annotations.setDistributable(true);
        URL url = fragment.getURL();
        processAnnotationsUrl(url, annotations, htOnly, javaClassCache);
        Set<WebXml> set = new HashSet<>();
        set.add(annotations);
        // Merge annotations into fragment - fragment takes priority
        fragment.merge(set);
    }
}
 
Example #14
Source File: ServletUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the first mapping for the given servlet name, or null or none or not found.
 */
public static String getServletMapping(WebXml webXml, String servletName) {
    if (servletName == null || servletName.isEmpty()) return null;
    // Catalina servlet mappings: key = url-pattern, value = servlet-name.
    for (Entry<String, String> entry : webXml.getServletMappings().entrySet()) {
        if (servletName.equals(entry.getValue())) {
            return entry.getKey();
        }
    }
    return null;
}
 
Example #15
Source File: ContextFilter.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * SCIPIO: Reads the forwardRootControllerUris value from ContextFilter init-params from webXml,
 * trying to find the most appropriate setting.
 */
public static Boolean readForwardRootControllerUrisSetting(WebXml webXml, String logPrefix) {
    // HEURISTIC: we return the value of the highest-rated ContextFilter that
    // has forwardRootControllerUris present in its init-params (even if empty)

    int bestRating = 0;
    String aliasStr = null;
    String filterName = null;
    for(FilterDef filter : webXml.getFilters().values()) {
        int currentRating = rateContextFilterCandidate(filter);
        if (currentRating > 0) {
            Map<String, String> initParams = filter.getParameterMap();
            if (initParams != null && initParams.containsKey("forwardRootControllerUris")) {
                if (currentRating > bestRating) {
                    bestRating = currentRating;
                    aliasStr = initParams.get("forwardRootControllerUris");
                    filterName = filter.getFilterName();
                }
            }
        }
    }
    if (bestRating > 0) {
        Boolean alias = UtilMisc.booleanValueVersatile(aliasStr);
        if (alias != null) {
            if (logPrefix != null) Debug.logInfo(logPrefix+"Found web.xml ContextFilter (filter name '" + filterName + "') init-param forwardRootControllerUris boolean value: " + alias, module);
            return alias;
        } else {
            if (UtilValidate.isNotEmpty(aliasStr)) {
                if (logPrefix != null) Debug.logError(logPrefix+"web.xml ContextFilter (filter name '" + filterName + "') init-param forwardRootControllerUris has invalid boolean value: " + aliasStr, module);
            } else {
                if (logPrefix != null) Debug.logInfo(logPrefix+"Found web.xml ContextFilter (filter name '" + filterName + "') init-param forwardRootControllerUris, was empty; returning as unset", module);
                return null;
            }
        }
    } else {
        if (logPrefix != null) Debug.logInfo(logPrefix+"web.xml ContextFilter init-param forwardRootControllerUris setting not found", module);
    }
    return null;
}
 
Example #16
Source File: ServletUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all servlet mappings for the given servlet name.
 */
public static Collection<String> getServletMappings(WebXml webXml, String servletName) {
    if (servletName == null || servletName.isEmpty()) return Collections.emptyList();
    List<String> servletMappings = new ArrayList<>(webXml.getServletMappings().size());
    // Catalina servlet mappings: key = url-pattern, value = servlet-name.
    for (Entry<String, String> entry : webXml.getServletMappings().entrySet()) {
        if (servletName.equals(entry.getValue())) {
            servletMappings.add(entry.getKey());
        }
    }
    return servletMappings;
}
 
Example #17
Source File: WebXmlTest.java    From JQF with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void testWithInputStream(InputStream in) {
    InputSource inputSource = new InputSource(in);
    WebXml webXml = new WebXml();
    WebXmlParser parser = new WebXmlParser(false, false, true);
    boolean success = parser.parseWebXml(inputSource, webXml, false);
    Assume.assumeTrue(success);
}
 
Example #18
Source File: OpenEJBContextConfig.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
protected void processAnnotationWebServlet(final String className, final AnnotationEntry ae, final WebXml fragment) {
    try {
        super.processAnnotationWebServlet(className, ae, fragment);
    } catch (final IllegalArgumentException iae) {
        // otherwise TCKs are not passing, hope to be able to let it with next TCK versions

        String[] urlPatterns = null;
        for (final ElementValuePair evp : ae.getElementValuePairs()) {
            final String name = evp.getNameString();
            if ("value".equals(name) || "urlPatterns".equals(name)) {
                urlPatterns = processAnnotationsStringArray(evp.getValue());
                break;
            }
        }

        if (urlPatterns != null) {
            for (final String pattern : urlPatterns) {
                if (fragment.getServletMappings().containsKey(pattern)) {
                    logger.warning(iae.getMessage(), iae);
                    return;
                }
            }
        }

        throw iae;
    }
}
 
Example #19
Source File: WebAppUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the control servlet path. The path consists of the web application's mount-point
 * specified in the <code>scipio-component.xml</code> file and the servlet mapping specified
 * in the web application's <code>web.xml</code> file.
 * <p>
 * SCIPIO: NOTE: This stock method always returns with a trailing slash (unless null).
 *
 *
 * @param webAppInfo
 * @param optional SCIPIO: if true, return null if not found; otherwise throw IllegalArgumentException (added 2017-11-18)
 * @throws IOException
 * @throws SAXException
 */
public static String getControlServletPath(WebappInfo webAppInfo, boolean optional) throws IOException, SAXException {
    Assert.notNull("webAppInfo", webAppInfo);
    // SCIPIO: Go through cache first. No need to synchronize, doesn't matter.
    String res = controlServletPathWebappInfoCache.get(webAppInfo.getContextRoot()); // key on context root (global unique)
    if (res != null) {
        // We take empty string to mean lookup found nothing
        if (res.isEmpty()) {
            if (optional) return null; // SCIPIO
            else throw new IllegalArgumentException("org.ofbiz.webapp.control.ControlServlet mapping not found in " + webAppInfo.getLocation() + webAppFileName);
        }
        else {
            return res;
        }
    }
    else {
        String servletMapping = null;
        WebXml webXml = getWebXml(webAppInfo);
        ServletDef controlServletDef = ControlServlet.getControlServletDefFromWebXml(webXml); // SCIPIO: 2017-12-05: factored out and fixed logic
        if (controlServletDef != null) {
            servletMapping = ServletUtil.getServletMapping(webXml, controlServletDef.getServletName()); // SCIPIO: 2017-12-05: delegated
        }
        if (servletMapping == null) {
            // SCIPIO: empty string means we did lookup and failed
            controlServletPathWebappInfoCache.put(webAppInfo.getContextRoot(), "");
            if (optional) return null; // SCIPIO
            else throw new IllegalArgumentException("org.ofbiz.webapp.control.ControlServlet mapping not found in " + webAppInfo.getLocation() + webAppFileName);
        }
        servletMapping = servletMapping.replace("*", "");
        if (!servletMapping.endsWith("/")) { // SCIPIO: 2017-12-05: extra guarantee the path ends with trailing slash
            servletMapping += "/";
        }
        String servletPath = webAppInfo.contextRoot.concat(servletMapping);
        // SCIPIO: save result
        controlServletPathWebappInfoCache.put(webAppInfo.getContextRoot(), servletPath);
        return servletPath;
    }
}
 
Example #20
Source File: WebAppUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a <code>WebXml</code> instance that models the web application's <code>web.xml</code> file.
 * <p>
 * SCIPIO: WARN: 2018-09-25: If you intended to use the WebXml to read the context-params, you should
 * use {@link #getWebappContextParams(WebappInfo)} instead of this method, because the raw WebXml
 * descriptor may miss extra context-params from other sources. In fact, for superior caching,
 * you should like go through {@link ExtWebappInfo#getContextParams()}.
 * @param webAppInfo
 * @throws IOException
 * @throws SAXException
 */
public static WebXml getWebXml(WebappInfo webAppInfo) throws IOException, SAXException {
    Assert.notNull("webAppInfo", webAppInfo);
    String webXmlFileLocation = webAppInfo.getLocation().concat(webAppFileName);
    // SCIPIO: TEMPORARILY CHANGED THIS TO NON-VALIDATING
    // FIXME: RETURN THIS TO VALIDATING ONCE ALL web.xml VALIDATION ISSUES ARE MERGED FROM UPSTREAM
    // The ofbiz team neglected to do it in this part of code, probably
    // because stock doesn't use it much yet... but we rely on it
    // NOTE: it's also possible this code is missing something that is done in CatalinaContainer
    // but not here... don't know... wait for upstream
    //return parseWebXmlFile(webXmlFileLocation, true);
    return parseWebXmlFile(webXmlFileLocation, false);
}
 
Example #21
Source File: TestSchemaValidation.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testWebapp_3_1() throws Exception {
    XmlErrorHandler handler = new XmlErrorHandler();
    Digester digester = DigesterFactory.newDigester(
            true, true, new WebRuleSet(false), true);
    digester.setErrorHandler(handler);
    digester.push(new WebXml());
    WebXml desc = (WebXml) digester.parse(
            new File("test/webapp-3.1/WEB-INF/web.xml"));
    Assert.assertEquals("3.1", desc.getVersion());
    Assert.assertEquals(0, handler.getErrors().size());
    Assert.assertEquals(0, handler.getWarnings().size());
}
 
Example #22
Source File: WebAppUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * SCIPIO: Returns the web.xml context-params for webappInfo, and tries to include
 * the init-params defined in scipio-component.xml as well. This is a best-effort operation,
 * because it is technically possible for custom code to add context-params from other sources unexpectedly.
 * <p>
 * NOTE: 2018-09-25: It is recommended to use {@link ExtWebappInfo#getContextParams()} instead of this, for caching reasons.
 * <p>
 * Added 2018-09-25 (refactored).
 *
 * @return the combined webapp context-params, unmodifiable
 */
public static Map<String, String> getWebappContextParams(WebappInfo webappInfo, WebXml webXml) { // SCIPIO
    Map<String, String> contextParams = webXml.getContextParams();
    if (contextParams != null && !contextParams.isEmpty()) {
        if (webappInfo.getInitParameters().isEmpty()) {
            return Collections.unmodifiableMap(contextParams);
        }
        contextParams = new HashMap<>(contextParams);
        contextParams.putAll(webappInfo.getInitParameters());
        return Collections.unmodifiableMap(contextParams);
    }
    return webappInfo.getInitParameters(); // never empty, already unmodifiable
}
 
Example #23
Source File: ExtWebappInfo.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Helper wrapper to read WebXml reliably.
 */
public static WebXml getWebXmlAlways(String webSiteId, WebappInfo webappInfo) throws IllegalArgumentException {
    try {
        return WebAppUtil.getWebXml(webappInfo);
    } catch(Exception e) {
        throw new IllegalArgumentException("Could not read or find webapp container info (web.xml) for website ID '" + webSiteId
                    + "' (mount-point '" + webappInfo.getContextRoot() + "'): " + e.getMessage(), e);
    }
}
 
Example #24
Source File: ExtWebappInfo.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
private static String getUrlRewriteConfPathFromWebXml(WebXml webXml) {
    for (FilterDef filterDef : webXml.getFilters().values()) {
        String filterClassName = filterDef.getFilterClass();
        // exact name is the original Ofbiz solution, return exact if found
        if (org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.class.getName().equals(filterClassName)) {
            String confPath = filterDef.getParameterMap().get("confPath");
            if (UtilValidate.isNotEmpty(confPath)) {
                return confPath;
            }
            return DEFAULT_WEBAPP_URLREWRITE_FILE;
        }
    }
    return null;
}
 
Example #25
Source File: MeecrowaveContextConfig.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@Override
protected void processClasses(final WebXml webXml, final Set<WebXml> orderedFragments) {
    final ClassLoader loader = context.getLoader().getClassLoader();
    orderedFragments.forEach(fragment -> {
        final WebXml annotations = new WebXml();
        annotations.setDistributable(true);
        final URL url = fragment.getURL();
        String urlString = url.toExternalForm();
        Collection<Class<?>> classes = webClasses.get(urlString);
        if (classes == null) { // mainly java 11, no need on java 8
            if (urlString.startsWith("file:") && urlString.endsWith("jar")) {
                urlString = "jar:" + urlString + "!/";
            } else {
                return;
            }
            classes = webClasses.get(urlString);
            if (classes == null) {
                return;
            }
        }
        classes.forEach(clazz -> {
            try (final InputStream stream = loader.getResourceAsStream(clazz.getName().replace('.', '/') + ".class")) {
                processClass(annotations, new ClassParser(stream).parse());
            } catch (final IOException e) {
                new LogFacade(MeecrowaveContextConfig.class.getName()).error("Can't parse " + clazz);
            }
        });
        fragment.merge(singleton(annotations));
    });
}
 
Example #26
Source File: OpenEJBContextConfig.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
protected void processAnnotationsStream(final InputStream is, final WebXml fragment,
                                        final boolean handlesTypesOnly,
                                        final Map<String,JavaClassCacheEntry> javaClassCache)
        throws ClassFormatException, IOException {
    // no-op
}
 
Example #27
Source File: OpenEJBContextConfig.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void internalProcessAnnotations(final File currentUrlAsFile, final WebAppInfo webAppInfo, final WebXml fragment) {
    for (final ClassListInfo webAnnotated : webAppInfo.webAnnotatedClasses) {
        try {
            if (!isIncludedIn(webAnnotated.name, currentUrlAsFile)) {
                continue;
            }

            internalProcessAnnotationsStream(webAnnotated.list, fragment, false);
        } catch (final MalformedURLException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
 
Example #28
Source File: OpenEJBContextConfig.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void internalProcessAnnotationsStream(final Collection<String> urls, final WebXml fragment,
                                              final boolean handlesTypeOnly) {
    for (final String url : urls) {
        InputStream is = null;
        try {
            is = new URL(url).openStream();
            super.processAnnotationsStream(is, fragment, handlesTypeOnly, EMPTY_MAP);
        } catch (final IOException e) {
            throw new IllegalArgumentException(e);
        } finally {
            IO.close(is);
        }
    }
}
 
Example #29
Source File: ContextConfig.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
protected void processClasses(WebXml webXml, Set<WebXml> orderedFragments) {
    // Step 4. Process /WEB-INF/classes for annotations and
    // @HandlesTypes matches
    Map<String, JavaClassCacheEntry> javaClassCache = new HashMap<>();

    if (ok) {
        WebResource[] webResources =
                context.getResources().listResources("/WEB-INF/classes");

        for (WebResource webResource : webResources) {
            // Skip the META-INF directory from any JARs that have been
            // expanded in to WEB-INF/classes (sometimes IDEs do this).
            if ("META-INF".equals(webResource.getName())) {
                continue;
            }
            processAnnotationsWebResource(webResource, webXml,
                    webXml.isMetadataComplete(), javaClassCache);
        }
    }

    // Step 5. Process JARs for annotations and
    // @HandlesTypes matches - only need to process those fragments we
    // are going to use (remember orderedFragments includes any
    // container fragments)
    if (ok) {
        processAnnotations(
                orderedFragments, webXml.isMetadataComplete(), javaClassCache);
    }

    // Cache, if used, is no longer required so clear it
    javaClassCache.clear();
}
 
Example #30
Source File: ContextConfig.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Scan JARs that contain web-fragment.xml files that will be used to
 * configure this application to see if they also contain static resources.
 * If static resources are found, add them to the context. Resources are
 * added in web-fragment.xml priority order.
 * @param fragments The set of fragments that will be scanned for
 *  static resources
 */
protected void processResourceJARs(Set<WebXml> fragments) {
    for (WebXml fragment : fragments) {
        URL url = fragment.getURL();
        try {
            if ("jar".equals(url.getProtocol()) || url.toString().endsWith(".jar")) {
                try (Jar jar = JarFactory.newInstance(url)) {
                    jar.nextEntry();
                    String entryName = jar.getEntryName();
                    while (entryName != null) {
                        if (entryName.startsWith("META-INF/resources/")) {
                            context.getResources().createWebResourceSet(
                                    WebResourceRoot.ResourceSetType.RESOURCE_JAR,
                                    "/", url, "/META-INF/resources");
                            break;
                        }
                        jar.nextEntry();
                        entryName = jar.getEntryName();
                    }
                }
            } else if ("file".equals(url.getProtocol())) {
                File file = new File(url.toURI());
                File resources = new File(file, "META-INF/resources/");
                if (resources.isDirectory()) {
                    context.getResources().createWebResourceSet(
                            WebResourceRoot.ResourceSetType.RESOURCE_JAR,
                            "/", resources.getAbsolutePath(), null, "/");
                }
            }
        } catch (IOException ioe) {
            log.error(sm.getString("contextConfig.resourceJarFail", url,
                    context.getName()));
        } catch (URISyntaxException e) {
            log.error(sm.getString("contextConfig.resourceJarFail", url,
                context.getName()));
        }
    }
}