Example usage for javax.servlet ServletContext getResourcePaths

List of usage examples for javax.servlet ServletContext getResourcePaths

Introduction

In this page you can find the example usage for javax.servlet ServletContext getResourcePaths.

Prototype

public Set<String> getResourcePaths(String path);

Source Link

Document

Returns a directory-like listing of all the paths to resources within the web application whose longest sub-path matches the supplied path argument.

Usage

From source file:net.bull.javamelody.TestMonitoringFilter.java

/**
 * Initialisation.//from  w  w w  . ja va 2 s.c  om
 * @throws ServletException e
 */
@Before
public void setUp() throws ServletException {
    try {
        final Field field = MonitoringFilter.class.getDeclaredField("instanceCreated");
        field.setAccessible(true);
        field.set(null, false);
    } catch (final IllegalAccessException e) {
        throw new IllegalStateException(e);
    } catch (final NoSuchFieldException e) {
        throw new IllegalStateException(e);
    }
    final FilterConfig config = createNiceMock(FilterConfig.class);
    final ServletContext context = createNiceMock(ServletContext.class);
    expect(config.getServletContext()).andReturn(context).anyTimes();
    expect(config.getFilterName()).andReturn(FILTER_NAME).anyTimes();
    // anyTimes sur getInitParameter car TestJdbcDriver a pu fixer la proprit systme  false
    expect(context.getInitParameter(Parameters.PARAMETER_SYSTEM_PREFIX + Parameter.DISABLED.getCode()))
            .andReturn(null).anyTimes();
    expect(config.getInitParameter(Parameter.DISABLED.getCode())).andReturn(null).anyTimes();
    expect(context.getMajorVersion()).andReturn(2).anyTimes();
    expect(context.getMinorVersion()).andReturn(5).anyTimes();
    expect(context.getServletContextName()).andReturn("test webapp").anyTimes();
    // mockJetty pour avoir un applicationServerIconName dans JavaInformations
    expect(context.getServerInfo()).andReturn("mockJetty").anyTimes();
    // dependencies pour avoir des dpendances dans JavaInformations
    final Set<String> dependencies = new LinkedHashSet<String>(
            Arrays.asList("/WEB-INF/lib/jrobin.jar", "/WEB-INF/lib/javamelody.jar"));
    // et flags pour considrer que les ressources pom.xml et web.xml existent
    JavaInformations.setWebXmlExistsAndPomXmlExists(true, true);
    expect(context.getResourcePaths("/WEB-INF/lib/")).andReturn(dependencies).anyTimes();
    expect(context.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
    monitoringFilter = new MonitoringFilter();
    monitoringFilter.setApplicationType("Test");
    replay(config);
    replay(context);
    monitoringFilter.init(config);
    verify(config);
    verify(context);
}

From source file:no.kantega.publishing.common.util.database.dbConnectionFactory.java

public static void migrateDatabase(ServletContext servletContext, DataSource dataSource) {
    DbMigrate migrate = new DbMigrate();

    try {//from   ww  w  .  ja va  2  s  .co m
        new JdbcTemplate(dataSource).queryForObject("select count(version) from oa_db_migrations",
                Integer.class);
    } catch (DataAccessException e) {
        log.info("Automatic database migration cannot be enabled before the final manual upgrade is performed");
        return;
    }
    String root = "/WEB-INF/dbmigrate/";
    ServletContextScriptSource scriptSource = new ServletContextScriptSource(servletContext, root);

    Set<String> domainPaths = servletContext.getResourcePaths(root);
    List<String> domains = new ArrayList<>();
    // We want the oa domain first
    domains.add("oa");

    for (String domainPath : domainPaths) {
        if (domainPath.endsWith("/")) {
            // Remove last slash
            domainPath = domainPath.substring(0, domainPath.length() - 1);
            String domain = domainPath.substring(domainPath.lastIndexOf('/') + 1);
            if (!domain.startsWith(".") && !"oa".equals(domain)) {
                domains.add(domain);
            }
        }
    }

    for (String domain : domains) {
        log.info("Migrating database domain '" + domain + "'");
        migrate.migrate(dataSource, domain, scriptSource);
    }

}

From source file:org.amplafi.jawr.maven.JawrMojo.java

private void setupJawrConfig(ServletConfig config, ServletContext context, final Map<String, Object> attributes,
        final Response respData) {
    expect(config.getServletContext()).andReturn(context).anyTimes();
    expect(config.getServletName()).andReturn("maven-jawr-plugin").anyTimes();

    context.log(isA(String.class));
    expectLastCall().anyTimes();// w  ww  .jav  a 2 s  .  c  o  m

    expect(context.getResourcePaths(isA(String.class))).andAnswer(new IAnswer<Set>() {

        public Set<String> answer() throws Throwable {
            final Set<String> set = new HashSet<String>();

            // hack to disallow orphan bundles
            Exception e = new Exception();
            for (StackTraceElement trace : e.getStackTrace()) {
                if (trace.getClassName().endsWith("OrphanResourceBundlesMapper")) {
                    return set;
                }
            }

            String path = (String) EasyMock.getCurrentArguments()[0];
            File file = new File(getRootPath() + path);

            if (file.exists() && file.isDirectory()) {
                for (String one : file.list()) {
                    set.add(path + one);
                }
            }

            return set;
        }

    }).anyTimes();

    expect(context.getResourceAsStream(isA(String.class))).andAnswer(new IAnswer<InputStream>() {

        public InputStream answer() throws Throwable {
            String path = (String) EasyMock.getCurrentArguments()[0];
            File file = new File(getRootPath(), path);
            return new FileInputStream(file);
        }

    }).anyTimes();

    expect(context.getAttribute(isA(String.class))).andAnswer(new IAnswer<Object>() {

        public Object answer() throws Throwable {
            return attributes.get(EasyMock.getCurrentArguments()[0]);
        }

    }).anyTimes();

    context.setAttribute(isA(String.class), isA(Object.class));
    expectLastCall().andAnswer(new IAnswer<Object>() {

        public Object answer() throws Throwable {
            String key = (String) EasyMock.getCurrentArguments()[0];
            Object value = EasyMock.getCurrentArguments()[1];
            attributes.put(key, value);
            return null;
        }

    }).anyTimes();

    expect(config.getInitParameterNames()).andReturn(new Enumeration<String>() {

        public boolean hasMoreElements() {
            return false;
        }

        public String nextElement() {
            return null;
        }

    }).anyTimes();

    expect(config.getInitParameter(JawrConstant.TYPE_INIT_PARAMETER)).andAnswer(new IAnswer<String>() {
        public String answer() throws Throwable {
            return respData == null ? null : respData.getType();
        }
    }).anyTimes();

    expect(config.getInitParameter("configLocation")).andReturn(getConfigLocation()).anyTimes();
    expect(config.getInitParameter("configPropertiesSourceClass")).andReturn(null).anyTimes();
}

From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java

/**
 * Discover the directories holding plugins within the classpath.
 *
 * @param path the path where to start the search from
 * @param servletContext the servlet context event
 *///from  w w w . j  av  a 2 s  .co  m
private Set<String> discoverClasses(String path, ServletContext servletContext) {
    Set<String> plugins = new HashSet<String>();

    Set<String> directory = servletContext.getResourcePaths(path);
    if (null != directory && !directory.isEmpty()) {
        Iterator<String> itr = directory.iterator();
        while (itr.hasNext()) {
            String currentDirectory = itr.next();
            boolean skip = false;
            // AVOID USELESS LOOPS IF POSSIBLE
            Iterator<String> exclude = _plugin_exclusion_directories.iterator();
            while (exclude.hasNext()) {
                String currentDirectoryExcluded = exclude.next();
                if (currentDirectory.contains(currentDirectoryExcluded)
                        && !currentDirectory.contains(PLUGIN_DIRECTORY)) {
                    skip = true;
                    break;
                }
            }
            if (skip) {
                continue;
            }
            if (currentDirectory.contains(PLUGIN_DIRECTORY)
                    && currentDirectory.endsWith(PLUGIN_APSADMIN_PATH)) {
                currentDirectory = currentDirectory.replaceFirst(TOMCAT_CLASSES, "");
                plugins.add(currentDirectory);
            } else {
                plugins.addAll(discoverClasses(currentDirectory, servletContext));
            }
        }
    }
    return plugins;
}

From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java

private Set<String> discoverJars(String path, ServletContext servletContext) {
    Set<String> plugins = new HashSet<String>();
    Set<String> directory = servletContext.getResourcePaths(path);
    Iterator<String> itr = directory.iterator();
    // ITERATE OVER PATHS
    while (null != itr && itr.hasNext()) {
        String currentJar = itr.next();
        InputStream is = servletContext.getResourceAsStream(currentJar);
        plugins.addAll(discoverJarPlugin(is));
    }/*from  w  w  w . j a  v a  2 s .co  m*/
    return plugins;
}

From source file:org.j2free.invoker.InvokerFilter.java

/**
 *
 * @param fc// ww w. j  ava  2  s  .c  o m
 */
public void init(javax.servlet.FilterConfig fc) {
    try {
        write.lock();

        Configuration config = (Configuration) Global.get(CONTEXT_ATTR_CONFIG);
        if (config != null)
            configure(config);

        // Use a custom exception handler, if there is one
        UncaughtServletExceptionHandler ueh = (UncaughtServletExceptionHandler) Global
                .get(CONTEXT_ATTR_UNCAUGHT_EXCEPTION_HANDLER);
        if (ueh != null)
            uncaughtExceptionHandler = ueh;

        // Use a custom request examiner, if there is one
        RequestExaminer reqex = (RequestExaminer) Global.get(CONTEXT_ATTR_REQUEST_EXAMINER);
        if (reqex != null)
            requestExaminer = reqex;

        ServletContext context = fc.getServletContext();
        load(context);

        // StaticJspServlet
        if (config.getBoolean(PROP_STATICJSP_ON, false)) {
            String staticJspDir = config == null ? DEFAULT_STATICJSP_DIR
                    : config.getString(PROP_STATICJSP_DIR, DEFAULT_STATICJSP_DIR);
            String staticJspPath = config == null ? DEFAULT_STATICJSP_PATH
                    : config.getString(PROP_STATICJSP_PATH, DEFAULT_STATICJSP_PATH);

            StaticJspServlet.directory.set(staticJspDir);

            Set<String> staticJsps = context.getResourcePaths(staticJspDir);
            if (staticJsps != null && !staticJsps.isEmpty()) {
                for (String jsp : staticJsps) {
                    if (jsp.endsWith(".jsp")) {
                        jsp = staticJspPath + jsp.replace(staticJspDir, EMPTY).replaceAll("\\.jsp$", EMPTY);
                        addServletMapping(jsp, StaticJspServlet.class);
                    }
                }
            }
        }

        // LogoutServlet
        if (config.getBoolean(PROP_SERVLET_LOGOUT_ON, false))
            addServletMapping(config, PROP_SERVLET_LOGOUT_PATH, DEFAULT_LOGOUT_PATH, LogoutServlet.class);

        // ProxyServlet
        if (config.getBoolean(PROP_SERVLET_PROXY_ON, false))
            addServletMapping(config, PROP_SERVLET_PROXY_PATH, DEFAULT_PROXY_PATH, ProxyServlet.class);

        // Admin Servlet
        if (config.getBoolean(PROP_SERVLET_ADMIN_ON, false))
            addServletMapping(config, PROP_SERVLET_ADMIN_PATH, DEFAULT_ADMIN_PATH, EntityAdminServlet.class);
    } finally {
        write.unlock();
    }
}

From source file:org.jahia.ajax.gwt.helper.StubHelper.java

/**
 * Returns a map of code snippets./*  w w w.  ja  v a 2 s  .  c o m*/
 * 
 * @param fileType
 *            the type of the file to lookup snippets for, e.g. "jsp"
 * @param snippetType
 *            the snippet type to lookup code snippets for, e.g. "conditionals", "loops" etc.
 * @param nodeTypeName
 *            null or the node type associated with the file
 * @return a map of code snippets
 */
private Map<String, String> getCodeSnippets(String fileType, String snippetType, String nodeTypeName) {
    Map<String, String> stub = new LinkedHashMap<String, String>();
    InputStream is = null;
    try {
        ServletContext servletContext = JahiaContextLoaderListener.getServletContext();
        @SuppressWarnings("unchecked")
        Set<String> resources = servletContext
                .getResourcePaths("/WEB-INF/etc/snippets/" + fileType + "/" + snippetType + "/");
        ExtendedNodeType n = null;
        if (resources != null) {
            for (String resource : resources) {
                String resourceName = StringUtils.substringAfterLast(resource, "/");
                String viewNodeType = getResourceViewNodeType(resourceName);
                if (nodeTypeName != null && viewNodeType != null) {
                    // check if the view node type matches the requested one
                    if (null == n) {
                        try {
                            n = NodeTypeRegistry.getInstance().getNodeType(nodeTypeName);
                        } catch (NoSuchNodeTypeException e) {
                            // node type not found, do nothing
                        }
                    }
                    if (n != null && !n.isNodeType(viewNodeType)) {
                        // we skip that stub as it's node type does not match the requested one
                        continue;
                    }
                }
                is = servletContext.getResourceAsStream(resource);
                try {
                    stub.put(viewNodeType != null ? (resourceName + "/" + viewNodeType) : resourceName,
                            StringUtils.join(IOUtils.readLines(is), "\n"));
                } finally {
                    IOUtils.closeQuietly(is);
                }
            }
        }
    } catch (IOException e) {
        logger.error("Failed to read code snippets from " + fileType + "/" + snippetType, e);
    }
    return stub;
}

From source file:org.nuxeo.runtime.deployment.NuxeoStarter.java

protected void findBundles(ServletContext servletContext) throws IOException {
    InputStream bundlesListStream = servletContext.getResourceAsStream("/WEB-INF/" + NUXEO_BUNDLES_LIST);
    if (bundlesListStream != null) {
        File lib = new File(servletContext.getRealPath("/WEB-INF/lib/"));
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(bundlesListStream))) {
            String bundleName;//from w w w. j  av  a  2s .c o  m
            while ((bundleName = reader.readLine()) != null) {
                bundleFiles.add(new File(lib, bundleName));
            }
        }
    }
    if (bundleFiles.isEmpty()) { // Fallback on directory scan
        File root = new File(servletContext.getRealPath("/"));
        Set<String> ctxpaths = servletContext.getResourcePaths("/WEB-INF/lib/");
        if (ctxpaths != null) {
            for (String ctxpath : ctxpaths) {
                if (!ctxpath.endsWith(".jar")) {
                    continue;
                }
                bundleFiles.add(new File(root, ctxpath));
            }
        }
    }
}

From source file:org.sonar.server.startup.GenerateBootstrapIndex.java

public static List<String> getLibs(ServletContext servletContext) {
    List<String> libs = Lists.newArrayList();
    Set<String> paths = servletContext.getResourcePaths("/WEB-INF/lib");
    for (String path : paths) {
        if (StringUtils.endsWith(path, ".jar")) {
            String filename = StringUtils.removeStart(path, "/WEB-INF/lib/");
            if (!isIgnored(filename)) {
                libs.add(filename);/*from ww w.j  a  v a2 s.co  m*/
            }
        }
    }
    return libs;
}

From source file:org.springframework.web.context.support.ServletContextResourcePatternResolver.java

/**
 * Recursively retrieve ServletContextResources that match the given pattern,
 * adding them to the given result set.//from  w w  w  . java  2s .c o m
 * @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));
            }
        }
    }
}