Java Code Examples for javax.servlet.ServletContext#getResourcePaths()

The following examples show how to use javax.servlet.ServletContext#getResourcePaths() . 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: ServletContextTemplateLocator.java    From trimou with Apache License 2.0 6 votes vote down vote up
private Set<String> listResources(String path, ServletContext ctx) {

        Set<String> resources = new HashSet<>();
        Set<String> resourcePaths = ctx.getResourcePaths(path);

        if (resourcePaths != null) {
            for (String resourcePath : resourcePaths) {
                if (resourcePath.endsWith(Strings.SLASH)) {
                    // Subdirectory
                    String subdirectory = getRootPath() + Strings
                            .substringAfter(resourcePath, getRootPath());
                    resources.addAll(listResources(subdirectory, ctx));
                } else {
                    if (getSuffix() != null
                            && !resourcePath.endsWith(getSuffix())) {
                        continue;
                    }
                    resources.add(resourcePath);
                }
            }
        }
        return resources;
    }
 
Example 2
Source File: cfmlFileCache.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
private Set<cfmlURI> getResourcePaths(ServletContext context, String path) {

		// Check the repositories
		Set<String> resultSet = context.getResourcePaths(path);
		Set<cfmlURI> newResults = new HashSet<cfmlURI>();

		// Check for null because if the path passed to context.getResourcePaths()
		// doesn't contain any files then WLS will return null.
		if (resultSet != null) {
			// Transform the list of strings into a list of cfmlURI's
			Iterator<String> it = resultSet.iterator();
			while (it.hasNext()) {
				newResults.add(new cfmlURI(it.next(), ""));
			}
		}

		return newResults;
	}
 
Example 3
Source File: MavenArtifact.java    From javamelody with Apache License 2.0 6 votes vote down vote up
private static Map<String, MavenArtifact> getWebappDependenciesFromWebInfLib()
		throws IOException {
	final ServletContext servletContext = Parameters.getServletContext();
	final String directory = "/WEB-INF/lib/";

	final Set<String> dependencies = servletContext.getResourcePaths(directory);
	// If needed, catch Exception again because Tomcat 8 can throw
	// "IllegalStateException: The resources may not be accessed if they are not currently started"
	// for some ServletContext states (issue 415)
	if (dependencies == null || dependencies.isEmpty()) {
		return Collections.emptyMap();
	}
	final Map<String, MavenArtifact> result = new TreeMap<String, MavenArtifact>();
	for (final String dependency : dependencies) {
		if (dependency.endsWith(".jar") || dependency.endsWith(".JAR")) {
			final String fileName = dependency.substring(directory.length());
			final URL jarFileLocation = servletContext.getResource(dependency);
			if (jarFileLocation != null) {
				result.put(fileName, parseDependency(jarFileLocation));
			} else {
				result.put(fileName, null);
			}
		}
	}
	return result;
}
 
Example 4
Source File: LanguageResourceService.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
/**
 * Adds or overlays all languages defined within the /translations
 * directory of the given ServletContext. If no such language files exist,
 * nothing is done. If a language is already defined, the strings from the
 * will be overlaid on top of the existing strings, augmenting or
 * overriding the available strings for that language. The language key
 * for each language file is derived from the filename.
 *
 * @param context
 *     The ServletContext from which language files should be loaded.
 */
public void addLanguageResources(ServletContext context) {

    // Get the paths of all the translation files
    Set<?> resourcePaths = context.getResourcePaths(TRANSLATION_PATH);
    
    // If no translation files found, nothing to add
    if (resourcePaths == null)
        return;
    
    // Iterate through all the found language files and add them to the map
    for (Object resourcePathObject : resourcePaths) {

        // Each resource path is guaranteed to be a string
        String resourcePath = (String) resourcePathObject;

        // Parse language key from path
        String languageKey = getLanguageKey(resourcePath);
        if (languageKey == null) {
            logger.warn("Invalid language file name: \"{}\"", resourcePath);
            continue;
        }

        // Add/overlay new resource
        addLanguageResource(
            languageKey,
            new WebApplicationResource(context, "application/json", resourcePath)
        );

    }

}
 
Example 5
Source File: FatJarScanner.java    From oxygen with Apache License 2.0 5 votes vote down vote up
private void doScanWebInfLib(JarScanType scanType, ServletContext context,
    JarScannerCallback callback, Set<URL> processedURLs) {
  Set<String> dirList = context.getResourcePaths(TomcatConf.WEB_INF_LIB);
  if (dirList == null) {
    return;
  }
  for (String path : dirList) {
    if (path.endsWith(TomcatConf.JAR_EXT) && getJarScanFilter()
        .check(scanType, path.substring(path.lastIndexOf(Strings.SLASH) + 1))) {
      // Need to scan this JAR
      if (log.isDebugEnabled()) {
        log.debug(SM.getString("jarScan.webinflibJarScan", path));
      }
      URL url = null;
      try {
        url = context.getResource(path);
        processedURLs.add(url);
        process(scanType, callback, url, path, true, null);
      } catch (IOException e) {
        log.warn(SM.getString("jarScan.webinflibFail", url), e);
      }
    } else {
      if (log.isTraceEnabled()) {
        log.trace(SM.getString("jarScan.webinflibJarNoScan", path));
      }
    }
  }
}
 
Example 6
Source File: InfoServlet.java    From mercury with Apache License 2.0 5 votes vote down vote up
private List<String> getJarList(ServletContext context, String path) {
    List<String> list = new ArrayList<>();
    Set<String> filenames = context.getResourcePaths(path);
    if (filenames != null) {
        for (String name : filenames) {
            String jar = name.startsWith(path)? name.substring(path.length()) : name;
            list.add(jar.endsWith(JAR) ? jar.substring(0, jar.length() - JAR.length()) : jar);
        }
    }
    return list;
}
 
Example 7
Source File: MethodAnnotationRecognizer.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a set of all library files in the designated servlet context resource path.
 * 
 * @param ctx     the servlet context
 * @param path    the resource path
 * 
 * @return        a set of class files
 */
private Set<File> getLibFilesForPath(ServletContext ctx, String path) {
   Set<File> files = new HashSet<File>();
   Set<String> libs = ctx.getResourcePaths(path);
   if (libs != null) {
      for (String lib : libs) {
         if (lib.endsWith(".jar")) {
            try {
               URL url = ctx.getResource(lib);
               File f = new File(url.toURI());
               files.add(f);
            } catch(Exception e) {
               StringBuilder txt = new StringBuilder(128);
               txt.append("Exception getting library file.");
               
               StringWriter sw = new StringWriter();
               PrintWriter pw = new PrintWriter(sw);
               e.printStackTrace(pw);
               pw.flush();
               txt.append(sw.toString());
               
               LOG.warn(txt.toString());
            }
         }
      }
   }
   return files;
}
 
Example 8
Source File: TestStandardContextAliases.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain");

    ServletContext context = getServletContext();

    // Check resources individually
    URL url = context.getResource("/WEB-INF/lib/taglibs-standard-spec-1.2.5.jar");
    if (url != null) {
        resp.getWriter().write("00-PASS\n");
    }

    url = context.getResource("/WEB-INF/lib/taglibs-standard-impl-1.2.5.jar");
    if (url != null) {
        resp.getWriter().write("01-PASS\n");
    }

    // Check a directory listing
    Set<String> libs = context.getResourcePaths("/WEB-INF/lib");
    if (libs == null) {
        return;
    }

    if (!libs.contains("/WEB-INF/lib/taglibs-standard-spec-1.2.5.jar")) {
        return;
    }
    if (!libs.contains("/WEB-INF/lib/taglibs-standard-impl-1.2.5.jar")) {
        return;
    }

    resp.getWriter().write("02-PASS\n");
}
 
Example 9
Source File: MethodAnnotationRecognizer.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a list of all class files available on a given servlet context 
 * resource path.
 * 
 * @param ctx     the servlet context
 * @param path    the resource path
 * 
 * @return        a set of class files
 */
private Set<File> getClassFilesForPath(ServletContext ctx, String path) {
   Set<File> files = new HashSet<File>();
   Set<String> paths = ctx.getResourcePaths(path);
   if (paths != null) {
      for (String pth : paths) {
         if (pth.endsWith("META-INF/")) {
            continue;
         } else if (pth.endsWith("/")) {
            files.addAll(getClassFilesForPath(ctx, pth));
         } else if (pth.endsWith(".class")) {
            try {
               URL url = ctx.getResource(pth);
               File f = new File(url.toURI());
               files.add(f);
            } catch(Exception e) {
               StringBuilder txt = new StringBuilder(128);
               txt.append("Exception getting library file.");
               txt.append(" Servlet context path: ").append(ctx.getContextPath());
               txt.append(", File path: ").append(path).append("\n");

               StringWriter sw = new StringWriter();
               PrintWriter pw = new PrintWriter(sw);
               e.printStackTrace(pw);
               pw.flush();
               txt.append(sw.toString());

               LOG.warn(txt.toString());
            }
         }
      }
   }
   return files;
}
 
Example 10
Source File: MCRWCMSNavigationResource.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a json object containing all available templates. 
 */
@GET
@Path("templates")
@Produces(MediaType.APPLICATION_JSON)
public String getTemplates(@Context ServletContext servletContext) throws Exception {
    // templates of navigation.xml
    Document xml = MCRWCMSNavigationUtils.getNavigationAsXML();
    List<Element> elementList = TEMPLATE_PATH.evaluate(xml);
    HashSet<String> entries = elementList.stream()
        .map(e -> e.getAttributeValue("template"))
        .collect(Collectors.toCollection(HashSet::new));

    // templates by folder
    String templatePath = MCRConfiguration2.getString("MCR.WCMS2.templatePath").orElse("/templates/master/");
    Set<String> resourcePaths = servletContext.getResourcePaths(templatePath);
    if (resourcePaths != null) {
        for (String resourcepath : resourcePaths) {
            String newResourcepath = resourcepath.substring(templatePath.length(), resourcepath.length() - 1);
            entries.add(newResourcepath);
        }
    }

    // create returning json
    JsonArray returnArr = new JsonArray();
    for (String entry : entries) {
        returnArr.add(new JsonPrimitive(entry));
    }
    return returnArr.toString();
}
 
Example 11
Source File: TestStandardContextAliases.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain");

    ServletContext context = getServletContext();

    // Check resources individually
    URL url = context.getResource("/WEB-INF/lib/taglibs-standard-spec-1.2.5.jar");
    if (url != null) {
        resp.getWriter().write("00-PASS\n");
    }

    url = context.getResource("/WEB-INF/lib/taglibs-standard-impl-1.2.5.jar");
    if (url != null) {
        resp.getWriter().write("01-PASS\n");
    }

    // Check a directory listing
    Set<String> libs = context.getResourcePaths("/WEB-INF/lib");
    if (libs == null) {
        return;
    }

    if (!libs.contains("/WEB-INF/lib/taglibs-standard-spec-1.2.5.jar")) {
        return;
    }
    if (!libs.contains("/WEB-INF/lib/taglibs-standard-impl-1.2.5.jar")) {
        return;
    }

    resp.getWriter().write("02-PASS\n");
}
 
Example 12
Source File: TestStandardContextAliases.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain");

    ServletContext context = getServletContext();

    // Check resources individually
    URL url = context.getResource("/WEB-INF/lib/taglibs-standard-spec-1.2.5.jar");
    if (url != null) {
        resp.getWriter().write("00-PASS\n");
    }

    url = context.getResource("/WEB-INF/lib/taglibs-standard-impl-1.2.5.jar");
    if (url != null) {
        resp.getWriter().write("01-PASS\n");
    }

    // Check a directory listing
    Set<String> libs = context.getResourcePaths("/WEB-INF/lib");
    if (libs == null) {
        return;
    }

    if (!libs.contains("/WEB-INF/lib/taglibs-standard-spec-1.2.5.jar")) {
        return;
    }
    if (!libs.contains("/WEB-INF/lib/taglibs-standard-impl-1.2.5.jar")) {
        return;
    }

    resp.getWriter().write("02-PASS\n");
}
 
Example 13
Source File: LanguageResourceService.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
/**
 * Adds or overlays all languages defined within the /translations
 * directory of the given ServletContext. If no such language files exist,
 * nothing is done. If a language is already defined, the strings from the
 * will be overlaid on top of the existing strings, augmenting or
 * overriding the available strings for that language. The language key
 * for each language file is derived from the filename.
 *
 * @param context
 *     The ServletContext from which language files should be loaded.
 */
public void addLanguageResources(ServletContext context) {

    // Get the paths of all the translation files
    Set<?> resourcePaths = context.getResourcePaths(TRANSLATION_PATH);
    
    // If no translation files found, nothing to add
    if (resourcePaths == null)
        return;
    
    // Iterate through all the found language files and add them to the map
    for (Object resourcePathObject : resourcePaths) {

        // Each resource path is guaranteed to be a string
        String resourcePath = (String) resourcePathObject;

        // Parse language key from path
        String languageKey = getLanguageKey(resourcePath);
        if (languageKey == null) {
            logger.warn("Invalid language file name: \"{}\"", resourcePath);
            continue;
        }

        // Add/overlay new resource
        addLanguageResource(
            languageKey,
            new WebApplicationResource(context, "application/json", resourcePath)
        );

    }

}
 
Example 14
Source File: ServletContextResourcePatternResolver.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Recursively retrieve ServletContextResources that match the given pattern,
 * adding them to the given result set.
 * @param servletContext the ServletContext to work on
 * @param fullPattern the pattern to match against,
 * with preprended root directory path
 * @param dir the current directory
 * @param result the Set of matching Resources to add to
 * @throws IOException if directory contents could not be retrieved
 * @see ServletContextResource
 * @see javax.servlet.ServletContext#getResourcePaths
 */
protected void doRetrieveMatchingServletContextResources(
		ServletContext servletContext, String fullPattern, String dir, Set<Resource> result)
		throws IOException {

	Set<String> candidates = servletContext.getResourcePaths(dir);
	if (candidates != null) {
		boolean dirDepthNotFixed = fullPattern.contains("**");
		int jarFileSep = fullPattern.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
		String jarFilePath = null;
		String pathInJarFile = null;
		if (jarFileSep > 0 && jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length() < fullPattern.length()) {
			jarFilePath = fullPattern.substring(0, jarFileSep);
			pathInJarFile = fullPattern.substring(jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length());
		}
		for (String currPath : candidates) {
			if (!currPath.startsWith(dir)) {
				// Returned resource path does not start with relative directory:
				// assuming absolute path returned -> strip absolute path.
				int dirIndex = currPath.indexOf(dir);
				if (dirIndex != -1) {
					currPath = currPath.substring(dirIndex);
				}
			}
			if (currPath.endsWith("/") && (dirDepthNotFixed || StringUtils.countOccurrencesOf(currPath, "/") <=
					StringUtils.countOccurrencesOf(fullPattern, "/"))) {
				// Search subdirectories recursively: ServletContext.getResourcePaths
				// only returns entries for one directory level.
				doRetrieveMatchingServletContextResources(servletContext, fullPattern, currPath, result);
			}
			if (jarFilePath != null && getPathMatcher().match(jarFilePath, currPath)) {
				// Base pattern matches a jar file - search for matching entries within.
				String absoluteJarPath = servletContext.getRealPath(currPath);
				if (absoluteJarPath != null) {
					doRetrieveMatchingJarEntries(absoluteJarPath, pathInJarFile, result);
				}
			}
			if (getPathMatcher().match(fullPattern, currPath)) {
				result.add(new ServletContextResource(servletContext, currPath));
			}
		}
	}
}
 
Example 15
Source File: TldConfig.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
private void tldScanResourcePaths(String startPath) {

        if (log.isTraceEnabled()) {
            log.trace(sm.getString("tldConfig.webinfScan", startPath));
        }

        ServletContext ctxt = context.getServletContext();

        Set<String> dirList = ctxt.getResourcePaths(startPath);
        if (dirList != null) {
            Iterator<String> it = dirList.iterator();
            while (it.hasNext()) {
                String path = it.next();
                if (!path.endsWith(TLD_EXT)
                        && (path.startsWith(WEB_INF_LIB)
                                || path.startsWith("/WEB-INF/classes/"))) {
                    continue;
                }
                if (path.endsWith(TLD_EXT)) {
                    if (path.startsWith("/WEB-INF/tags/") &&
                            !path.endsWith("implicit.tld")) {
                        continue;
                    }
                    InputStream stream = ctxt.getResourceAsStream(path);
                    try {
                        XmlErrorHandler handler = tldScanStream(stream);
                        handler.logFindings(log, path);
                    } catch (IOException ioe) {
                        log.warn(sm.getString("tldConfig.webinfFail", path),
                                ioe);
                    } finally {
                        if (stream != null) {
                            try {
                                stream.close();
                            } catch (Throwable t) {
                                ExceptionUtils.handleThrowable(t);
                            }
                        }
                    }
                } else {
                    tldScanResourcePaths(path);
                }
            }
        }
    }
 
Example 16
Source File: ServletContextResourcePatternResolver.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Recursively retrieve ServletContextResources that match the given pattern,
 * adding them to the given result set.
 * @param servletContext the ServletContext to work on
 * @param fullPattern the pattern to match against,
 * with preprended root directory path
 * @param dir the current directory
 * @param result the Set of matching Resources to add to
 * @throws IOException if directory contents could not be retrieved
 * @see ServletContextResource
 * @see javax.servlet.ServletContext#getResourcePaths
 */
protected void doRetrieveMatchingServletContextResources(
		ServletContext servletContext, String fullPattern, String dir, Set<Resource> result)
		throws IOException {

	Set<String> candidates = servletContext.getResourcePaths(dir);
	if (candidates != null) {
		boolean dirDepthNotFixed = fullPattern.contains("**");
		int jarFileSep = fullPattern.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
		String jarFilePath = null;
		String pathInJarFile = null;
		if (jarFileSep > 0 && jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length() < fullPattern.length()) {
			jarFilePath = fullPattern.substring(0, jarFileSep);
			pathInJarFile = fullPattern.substring(jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length());
		}
		for (String currPath : candidates) {
			if (!currPath.startsWith(dir)) {
				// Returned resource path does not start with relative directory:
				// assuming absolute path returned -> strip absolute path.
				int dirIndex = currPath.indexOf(dir);
				if (dirIndex != -1) {
					currPath = currPath.substring(dirIndex);
				}
			}
			if (currPath.endsWith("/") && (dirDepthNotFixed || StringUtils.countOccurrencesOf(currPath, "/") <=
					StringUtils.countOccurrencesOf(fullPattern, "/"))) {
				// Search subdirectories recursively: ServletContext.getResourcePaths
				// only returns entries for one directory level.
				doRetrieveMatchingServletContextResources(servletContext, fullPattern, currPath, result);
			}
			if (jarFilePath != null && getPathMatcher().match(jarFilePath, currPath)) {
				// Base pattern matches a jar file - search for matching entries within.
				String absoluteJarPath = servletContext.getRealPath(currPath);
				if (absoluteJarPath != null) {
					doRetrieveMatchingJarEntries(absoluteJarPath, pathInJarFile, result);
				}
			}
			if (getPathMatcher().match(fullPattern, currPath)) {
				result.add(new ServletContextResource(servletContext, currPath));
			}
		}
	}
}
 
Example 17
Source File: TldConfig.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
private void tldScanResourcePaths(String startPath) {

        if (log.isTraceEnabled()) {
            log.trace(sm.getString("tldConfig.webinfScan", startPath));
        }

        ServletContext ctxt = context.getServletContext();

        Set<String> dirList = ctxt.getResourcePaths(startPath);
        if (dirList != null) {
            Iterator<String> it = dirList.iterator();
            while (it.hasNext()) {
                String path = it.next();
                if (!path.endsWith(TLD_EXT)
                        && (path.startsWith(WEB_INF_LIB)
                                || path.startsWith("/WEB-INF/classes/"))) {
                    continue;
                }
                if (path.endsWith(TLD_EXT)) {
                    if (path.startsWith("/WEB-INF/tags/") &&
                            !path.endsWith("implicit.tld")) {
                        continue;
                    }
                    InputStream stream = ctxt.getResourceAsStream(path);
                    try {
                        XmlErrorHandler handler = tldScanStream(stream);
                        handler.logFindings(log, path);
                    } catch (IOException ioe) {
                        log.warn(sm.getString("tldConfig.webinfFail", path),
                                ioe);
                    } finally {
                        if (stream != null) {
                            try {
                                stream.close();
                            } catch (Throwable t) {
                                ExceptionUtils.handleThrowable(t);
                            }
                        }
                    }
                } else {
                    tldScanResourcePaths(path);
                }
            }
        }
    }
 
Example 18
Source File: ServletContextResourcePatternResolver.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Recursively retrieve ServletContextResources that match the given pattern,
 * adding them to the given result set.
 * @param servletContext the ServletContext to work on
 * @param fullPattern the pattern to match against,
 * with preprended root directory path
 * @param dir the current directory
 * @param result the Set of matching Resources to add to
 * @throws IOException if directory contents could not be retrieved
 * @see ServletContextResource
 * @see javax.servlet.ServletContext#getResourcePaths
 */
protected void doRetrieveMatchingServletContextResources(
		ServletContext servletContext, String fullPattern, String dir, Set<Resource> result)
		throws IOException {

	Set<String> candidates = servletContext.getResourcePaths(dir);
	if (candidates != null) {
		boolean dirDepthNotFixed = fullPattern.contains("**");
		int jarFileSep = fullPattern.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
		String jarFilePath = null;
		String pathInJarFile = null;
		if (jarFileSep > 0 && jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length() < fullPattern.length()) {
			jarFilePath = fullPattern.substring(0, jarFileSep);
			pathInJarFile = fullPattern.substring(jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length());
		}
		for (String currPath : candidates) {
			if (!currPath.startsWith(dir)) {
				// Returned resource path does not start with relative directory:
				// assuming absolute path returned -> strip absolute path.
				int dirIndex = currPath.indexOf(dir);
				if (dirIndex != -1) {
					currPath = currPath.substring(dirIndex);
				}
			}
			if (currPath.endsWith("/") && (dirDepthNotFixed || StringUtils.countOccurrencesOf(currPath, "/") <=
					StringUtils.countOccurrencesOf(fullPattern, "/"))) {
				// Search subdirectories recursively: ServletContext.getResourcePaths
				// only returns entries for one directory level.
				doRetrieveMatchingServletContextResources(servletContext, fullPattern, currPath, result);
			}
			if (jarFilePath != null && getPathMatcher().match(jarFilePath, currPath)) {
				// Base pattern matches a jar file - search for matching entries within.
				String absoluteJarPath = servletContext.getRealPath(currPath);
				if (absoluteJarPath != null) {
					doRetrieveMatchingJarEntries(absoluteJarPath, pathInJarFile, result);
				}
			}
			if (getPathMatcher().match(fullPattern, currPath)) {
				result.add(new ServletContextResource(servletContext, currPath));
			}
		}
	}
}
 
Example 19
Source File: ServletContextResourcePatternResolver.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Recursively retrieve ServletContextResources that match the given pattern,
 * adding them to the given result set.
 * @param servletContext the ServletContext to work on
 * @param fullPattern the pattern to match against,
 * with preprended root directory path
 * @param dir the current directory
 * @param result the Set of matching Resources to add to
 * @throws IOException if directory contents could not be retrieved
 * @see ServletContextResource
 * @see javax.servlet.ServletContext#getResourcePaths
 */
protected void doRetrieveMatchingServletContextResources(
		ServletContext servletContext, String fullPattern, String dir, Set<Resource> result)
		throws IOException {

	Set<String> candidates = servletContext.getResourcePaths(dir);
	if (candidates != null) {
		boolean dirDepthNotFixed = fullPattern.contains("**");
		int jarFileSep = fullPattern.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
		String jarFilePath = null;
		String pathInJarFile = null;
		if (jarFileSep > 0 && jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length() < fullPattern.length()) {
			jarFilePath = fullPattern.substring(0, jarFileSep);
			pathInJarFile = fullPattern.substring(jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length());
		}
		for (String currPath : candidates) {
			if (!currPath.startsWith(dir)) {
				// Returned resource path does not start with relative directory:
				// assuming absolute path returned -> strip absolute path.
				int dirIndex = currPath.indexOf(dir);
				if (dirIndex != -1) {
					currPath = currPath.substring(dirIndex);
				}
			}
			if (currPath.endsWith("/") && (dirDepthNotFixed || StringUtils.countOccurrencesOf(currPath, "/") <=
					StringUtils.countOccurrencesOf(fullPattern, "/"))) {
				// Search subdirectories recursively: ServletContext.getResourcePaths
				// only returns entries for one directory level.
				doRetrieveMatchingServletContextResources(servletContext, fullPattern, currPath, result);
			}
			if (jarFilePath != null && getPathMatcher().match(jarFilePath, currPath)) {
				// Base pattern matches a jar file - search for matching entries within.
				String absoluteJarPath = servletContext.getRealPath(currPath);
				if (absoluteJarPath != null) {
					doRetrieveMatchingJarEntries(absoluteJarPath, pathInJarFile, result);
				}
			}
			if (getPathMatcher().match(fullPattern, currPath)) {
				result.add(new ServletContextResource(servletContext, currPath));
			}
		}
	}
}