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:com.jsmartframework.web.manager.FilterControl.java

private void initResources(FilterConfig config) {
    try {//from   w w w.  j a v a2  s .c  om
        if (CONFIG.getContent().getAssetsUrl() != null) {
            LOGGER.log(Level.INFO, "Using external assets, please provide the jsmart assets content at ["
                    + CONFIG.getContent().getAssetsUrl() + "]");
        }

        ServletContext context = config.getServletContext();
        Set<String> libs = context.getResourcePaths(LIB_FILE_PATH);

        if (libs == null || libs.isEmpty()) {
            LOGGER.log(Level.SEVERE, "Could not find the JSmart library JAR file. Empty [" + LIB_FILE_PATH
                    + "] resource folder.");
            return;
        }

        String libFilePath = null;
        for (String lib : libs) {
            Matcher matcher = JAR_FILE_PATTERN.matcher(lib);
            if (matcher.find()) {
                libFilePath = matcher.group();
                break;
            }
        }

        if (libFilePath == null) {
            LOGGER.log(Level.SEVERE,
                    "Could not find the JSmart library JAR file inside [" + LIB_FILE_PATH + "]");
            return;
        }

        Resources jsonResources = EXPRESSIONS.GSON.fromJson(convertResourceToString(FILTER_RESOURCES),
                Resources.class);

        File libFile = new File(context.getRealPath(libFilePath));
        Dir content = Vfs.fromURL(libFile.toURI().toURL());

        Iterator<Vfs.File> files = content.getFiles().iterator();
        while (files.hasNext()) {
            Vfs.File file = files.next();

            // Copy index.jsp and replace content to redirect to welcome-url case configured
            if (file.getRelativePath().startsWith(INDEX_JSP)) {
                if (CONFIG.getContent().getWelcomeUrl() != null) {
                    StringWriter writer = new StringWriter();
                    IOUtils.copy(file.openInputStream(), writer);
                    String index = writer.toString().replace("{0}", CONFIG.getContent().getWelcomeUrl());
                    copyFileResource(new ByteArrayInputStream(index.getBytes(ENCODING)), file.getRelativePath(),
                            context);
                }
            }

            // Do not copy anything if assets-url was provided
            if (CONFIG.getContent().getAssetsUrl() != null) {
                continue;
            }

            // Copy js, css and font resources to specific location
            for (String resource : jsonResources.getResources()) {
                String resourcePath = resource.replace("*", "");

                if (file.getRelativePath().startsWith(resourcePath)) {
                    initDirResources(context.getRealPath(PATH_SEPARATOR), file.getRelativePath());
                    copyFileResource(file.openInputStream(), file.getRelativePath(), context);
                    break;
                }
            }
        }
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, ex.getMessage());
    }
}

From source file:com.ecyrd.jspwiki.ui.TemplateManager.java

/**
 *   Lists the skins available under this template.  Returns an
 *   empty Set, if there are no extra skins available.  Note that
 *   this method does not check whether there is anything actually
 *   in the directories, it just lists them.  This may change
 *   in the future.//from   w ww .j  a v  a  2s  . c o  m
 *
 *   @param pageContext the JSP PageContext
 *   @param template The template to search
 *   @return Set of Strings with the skin names.
 *   @since 2.3.26
 */
@SuppressWarnings("unchecked")
public Set listSkins(PageContext pageContext, String template) {
    String place = makeFullJSPName(template, SKIN_DIRECTORY);

    ServletContext sContext = pageContext.getServletContext();

    Set<String> skinSet = sContext.getResourcePaths(place);
    TreeSet<String> resultSet = new TreeSet<String>();

    if (log.isDebugEnabled())
        log.debug("Listings skins from " + place);

    if (skinSet != null) {
        String[] skins = {};

        skins = skinSet.toArray(skins);

        for (int i = 0; i < skins.length; i++) {
            String[] s = StringUtils.split(skins[i], "/");

            if (s.length > 2 && skins[i].endsWith("/")) {
                String skinName = s[s.length - 1];
                resultSet.add(skinName);
                if (log.isDebugEnabled())
                    log.debug("...adding skin '" + skinName + "'");
            }
        }
    }

    return resultSet;
}

From source file:com.liferay.portal.service.impl.ThemeLocalServiceImpl.java

private void _setSpriteImages(ServletContext servletContext, Theme theme, String resourcePath)
        throws Exception {

    Set<String> resourcePaths = servletContext.getResourcePaths(resourcePath);

    if (resourcePaths == null) {
        return;//from   w  w  w . j  a v a2s  . c  o m
    }

    List<File> images = new ArrayList<File>(resourcePaths.size());

    for (String curResourcePath : resourcePaths) {
        if (curResourcePath.endsWith(StringPool.SLASH)) {
            _setSpriteImages(servletContext, theme, curResourcePath);
        } else if (curResourcePath.endsWith(".png")) {
            String realPath = ServletContextUtil.getRealPath(servletContext, curResourcePath);

            if (realPath != null) {
                images.add(new File(realPath));
            } else {
                if (ServerDetector.isTomcat()) {
                    if (_log.isInfoEnabled()) {
                        _log.info(ServletContextUtil.LOG_INFO_SPRITES);
                    }
                } else {
                    _log.error("Real path for " + curResourcePath + " is null");
                }
            }
        }
    }

    String spriteFileName = PropsValues.SPRITE_FILE_NAME;
    String spritePropertiesFileName = PropsValues.SPRITE_PROPERTIES_FILE_NAME;
    String spritePropertiesRootPath = ServletContextUtil.getRealPath(servletContext, theme.getImagesPath());

    Properties spriteProperties = SpriteProcessorUtil.generate(images, spriteFileName, spritePropertiesFileName,
            spritePropertiesRootPath, 16, 16, 10240);

    if (spriteProperties == null) {
        return;
    }

    spriteFileName = resourcePath.substring(theme.getImagesPath().length(), resourcePath.length())
            + spriteFileName;

    theme.setSpriteImages(spriteFileName, spriteProperties);
}

From source file:com.aurel.track.dbase.HandleHome.java

/**
 * This method copies resources/SSO folder and content from war into Trackplus_Home.
 * @param context/* www. jav a 2s  . c  om*/
 * @throws IOException
 * @throws ServletException
 */
public static void copySSOFolder(ServletContext context) {
    File ssoDirInHome = new File(HandleHome.getTrackplus_Home() + File.separator + SSO_DIR);
    if (!ssoDirInHome.exists()) {
        ssoDirInHome.mkdir();
        LOGGER.info("Creating folder for SSO in Track home: " + ssoDirInHome.getPath());
        URL rootTillFolder = null;
        String rootPathTillFolder = null;
        try {
            rootTillFolder = context.getResource("/WEB-INF/classes/resources/SSO");
        } catch (IOException ioEx) {
            LOGGER.error("Some errors happened while copying SSO folder from war into Track_Home!");
            LOGGER.error(ExceptionUtils.getStackTrace(ioEx));
        }
        rootPathTillFolder = rootTillFolder.getPath();
        rootPathTillFolder = rootPathTillFolder.substring(rootPathTillFolder.indexOf("/WEB-INF"),
                rootPathTillFolder.length());
        Set<String> folderContent = context.getResourcePaths(rootPathTillFolder);
        String folderNameFound = null;
        for (String fileNameWithPath : folderContent) {
            if (fileNameWithPath.endsWith(".jar")) {
                LOGGER.info("Copying following jar file into Track_home/" + SSO_DIR + ": " + fileNameWithPath);
                String fileName = fileNameWithPath.replace("/WEB-INF/classes/resources/SSO/", "");
                try {
                    copyObject(context, "resources/SSO", fileName, SSO_DIR);
                } catch (ServletException servEx) {
                    LOGGER.error("Some errors happened while copying SSO folder from war into Track_Home!");
                    LOGGER.error(ExceptionUtils.getStackTrace(servEx));
                }
            } else {
                folderNameFound = fileNameWithPath.replace("/WEB-INF/classes/resources/SSO/", "");
            }
        }

        try {
            rootTillFolder = context.getResource("/WEB-INF/classes/resources/SSO/" + folderNameFound);
        } catch (IOException ioEx) {
            LOGGER.error("Some errors happened while copying SSO folder from war into Track_Home!");
            LOGGER.error(ExceptionUtils.getStackTrace(ioEx));
        }
        rootPathTillFolder = rootTillFolder.getPath();
        rootPathTillFolder = rootPathTillFolder.substring(rootPathTillFolder.indexOf("/WEB-INF"),
                rootPathTillFolder.length());
        folderContent = context.getResourcePaths(rootPathTillFolder);
        File ssoSubDirInHome = new File(
                HandleHome.getTrackplus_Home() + File.separator + SSO_DIR + File.separator + folderNameFound);
        if (!ssoSubDirInHome.exists()) {
            LOGGER.info("Creating sub folder in Track_home/SSO: " + ssoSubDirInHome.getPath());
            ssoSubDirInHome.mkdir();
        }
        for (String fileNameWithPath : folderContent) {
            String fileName = fileNameWithPath.replace("/WEB-INF/classes/resources/SSO/" + folderNameFound, "");
            LOGGER.info(
                    "Copying following file into  Track_home/SSO/" + folderNameFound + ": " + fileNameWithPath);
            try {
                copyObject(context, "resources/SSO" + "/" + folderNameFound, fileName,
                        SSO_DIR + "/" + folderNameFound);
            } catch (ServletException servEx) {
                LOGGER.error("Some errors happened while copying SSO folder from war into Track_Home!");
                LOGGER.error(ExceptionUtils.getStackTrace(servEx));
            }
        }
    }
}

From source file:com.aurel.track.dbase.HandleHome.java

private static void copyLanguageProfiles(ServletContext context, String templateBaseDir) {
    String tpHome = getTrackplus_Home();
    File templatesDir = new File(tpHome + File.separator + templateBaseDir);

    URL rootTillFolder = null;//from w w w  .  j a va 2 s.  c o m
    String rootPathTillFolder = null;
    String templatePath = templateBaseDir.replace("\\", "/");
    try {
        if (context.getResource("/WEB-INF/classes/resources/" + templatePath) != null) {
            rootTillFolder = context.getResource("/WEB-INF/classes/resources/" + templatePath);
        } else if (context.getResource("/WEB-INF/classes/" + templatePath) != null) {
            rootTillFolder = context.getResource("/WEB-INF/classes/" + templatePath);
        } else {
            rootTillFolder = new URL(context.getRealPath("../."));
        }
    } catch (IOException ioEx) {
        LOGGER.error(ExceptionUtils.getStackTrace(ioEx));
    }
    if (rootTillFolder != null) {
        rootPathTillFolder = rootTillFolder.getPath();
        if (rootPathTillFolder.contains("/WEB-INF")) {
            rootPathTillFolder = rootPathTillFolder.substring(rootPathTillFolder.indexOf("/WEB-INF"),
                    rootPathTillFolder.length());
        }
        Set<String> folderContent = context.getResourcePaths(rootPathTillFolder);

        for (String fileNameWithPath : folderContent) {
            String fileName = fileNameWithPath.replace("/WEB-INF/classes/resources/" + templatePath + "/", "");
            try {
                copyObject(context, "resources/" + templatePath, fileName, templateBaseDir);
            } catch (ServletException servEx) {
                LOGGER.error(ExceptionUtils.getStackTrace(servEx));
            }
        }
        try {
            FileUtils.deleteQuietly(new File(HandleHome.getTrackplus_Home() + File.separator
                    + LANGUAGE_PROFILES_DIR + File.separator + "hash.txt"));
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
    }
}

From source file:com.aurel.track.dbase.HandleHome.java

private static void copyExportTemplates(ServletContext context, String templateBaseDir) {
    String tpHome = getTrackplus_Home();
    File templatesDir = new File(tpHome + File.separator + templateBaseDir);

    URL rootTillFolder = null;//from  w  w w .j a  va 2  s  .  com
    String rootPathTillFolder = null;
    String templatePath = templateBaseDir.replace("\\", "/");
    try {
        if (context.getResource("/WEB-INF/classes/resources/" + templatePath) != null) {
            rootTillFolder = context.getResource("/WEB-INF/classes/resources/" + templatePath);
        } else if (context.getResource("/WEB-INF/classes/" + templatePath) != null) {
            rootTillFolder = context.getResource("/WEB-INF/classes/" + templatePath);
        } else {
            rootTillFolder = new URL(context.getRealPath("../."));
        }
    } catch (IOException ioEx) {
        LOGGER.error(ExceptionUtils.getStackTrace(ioEx));
    }
    if (rootTillFolder != null) {
        rootPathTillFolder = rootTillFolder.getPath();
        if (rootPathTillFolder.contains("/WEB-INF")) {
            rootPathTillFolder = rootPathTillFolder.substring(rootPathTillFolder.indexOf("/WEB-INF"),
                    rootPathTillFolder.length());
        }
        Set<String> folderContent = context.getResourcePaths(rootPathTillFolder);
        if (folderContent != null) {
            for (String fileNameWithPath : folderContent) {
                String fileName = fileNameWithPath.replace("/WEB-INF/classes/resources/" + templatePath + "/",
                        "");
                if (fileName.endsWith(".docx") || fileName.endsWith(".tex") || fileName.endsWith(".jpg")
                        || fileName.endsWith(".png") || fileName.endsWith(".tlx") || fileName.endsWith(".sh")
                        || fileName.endsWith(".cmd") || fileName.endsWith(".pdf")) {
                    try {
                        copyObject(context, "resources/" + templatePath, fileName, templateBaseDir);
                    } catch (ServletException servEx) {
                        LOGGER.error(ExceptionUtils.getStackTrace(servEx));
                    }
                }

                if (fileName.endsWith(".sh") || fileName.endsWith(".cmd")) {
                    File fileToCopyInHome = new File(
                            tpHome + File.separator + templateBaseDir + File.separator + fileName);
                    fileToCopyInHome.setExecutable(true);
                }

                if (fileName.endsWith(".zip") || fileName.endsWith(".tlx")) {
                    try {
                        File fileToCopyInHome = new File(
                                tpHome + File.separator + templateBaseDir + File.separator + fileName);
                        copyObject(context, "resources/" + templatePath, fileName, templateBaseDir);
                        File fileToUnzip = new File(
                                tpHome + File.separator + templateBaseDir + File.separator + fileName);
                        PluginUtils.unzipFileIntoDirectory(fileToUnzip, templatesDir);
                    } catch (ServletException servEx) {
                        LOGGER.error(ExceptionUtils.getStackTrace(servEx));
                    }
                }
            }
        }
    }
}

From source file:com.jsmartframework.web.manager.BeanHandler.java

private void lookupInResourcePath(ServletContext servletContext, String path) {
    Set<String> resources = servletContext.getResourcePaths(path);
    if (resources != null) {
        for (String res : resources) {
            if (res.endsWith(".jsp") || res.endsWith(".jspf") || res.endsWith(".html")) {
                String[] bars = res.split(Constants.PATH_SEPARATOR);
                if (res.endsWith(".jspf")) {

                    // Save the entire resource path to capture it later when reading JSP include tags
                    forwardPaths.put(res, res);
                } else {
                    forwardPaths.put(Constants.PATH_SEPARATOR
                            + bars[bars.length - 1].replace(".jsp", "").replace(".html", ""), res);
                }//from w w  w  . j a v a 2s. c o  m
            } else {
                lookupInResourcePath(servletContext, res);
            }
        }
    }
}

From source file:com.liferay.portal.service.impl.PortletLocalServiceImpl.java

private void _setSpriteImages(ServletContext servletContext, PortletApp portletApp, String resourcePath)
        throws Exception {

    Set<String> resourcePaths = servletContext.getResourcePaths(resourcePath);

    if (resourcePaths == null) {
        return;/*from  www.  j  a  va 2  s  .co  m*/
    }

    List<File> images = new ArrayList<File>(resourcePaths.size());

    for (String curResourcePath : resourcePaths) {
        if (curResourcePath.endsWith(StringPool.SLASH)) {
            _setSpriteImages(servletContext, portletApp, curResourcePath);
        } else if (curResourcePath.endsWith(".png")) {
            String realPath = ServletContextUtil.getRealPath(servletContext, curResourcePath);

            if (realPath != null) {
                images.add(new File(realPath));
            } else {
                if (ServerDetector.isTomcat()) {
                    if (_log.isInfoEnabled()) {
                        _log.info(ServletContextUtil.LOG_INFO_SPRITES);
                    }
                } else {
                    _log.error("Real path for " + curResourcePath + " is null");
                }
            }
        }
    }

    String spriteFileName = PropsValues.SPRITE_FILE_NAME;
    String spritePropertiesFileName = PropsValues.SPRITE_PROPERTIES_FILE_NAME;
    String spritePropertiesRootPath = ServletContextUtil.getRealPath(servletContext, StringPool.SLASH);

    Properties spriteProperties = SpriteProcessorUtil.generate(images, spriteFileName, spritePropertiesFileName,
            spritePropertiesRootPath, 16, 16, 10240);

    if (spriteProperties == null) {
        return;
    }

    spriteFileName = resourcePath.substring(0, resourcePath.length()) + spriteFileName;

    portletApp.setSpriteImages(spriteFileName, spriteProperties);
}

From source file:com.concursive.connect.config.ApplicationPrefs.java

/**
 * Description of the Method// w  ww.  j a  v a2 s .c o  m
 *
 * @param context Description of the Parameter
 */
public void configureDefaultBehavior(ServletContext context) {
    LOG.info("Configuring default behavior...");
    // Default login and session validation
    if (!this.has(LOGIN_MODE)) {
        this.add(LOGIN_MODE, "Default");
    }
    // Detect if this instance is using a legacy default, and upgrade to a theme
    if (!this.has(THEME)) {
        if (!this.has(JSP_TEMPLATE) || "/layoutDefault.jsp".equals(this.get(JSP_TEMPLATE))) {
            this.add(THEME, "default");
            this.add(COLOR_SCHEME, "dark_blue");
        }
    }

    // Determine the site theme
    if (this.has(THEME)) {
        // Use a theme and its color scheme; always use the default if the theme is missing
        String theme = "default";
        String colorScheme = "dark_blue";
        Set<String> themeFiles = context.getResourcePaths("/themes/" + this.get(THEME) + "/color-schemes");
        if (themeFiles != null && themeFiles.size() > 0) {
            for (String thisFile : themeFiles) {
                if (thisFile.startsWith(
                        "/themes/" + this.get(THEME) + "/color-schemes/" + this.get(COLOR_SCHEME))) {
                    theme = this.get(THEME);
                    colorScheme = this.get(COLOR_SCHEME);
                }
            }
        }
        if (!theme.equals(get(THEME))) {
            LOG.error("The theme (" + get(THEME) + ") and color scheme (" + get(COLOR_SCHEME)
                    + ") could not be found, using default theme");
        }
        addParameter(context, Constants.TEMPLATE_THEME, theme);
        addParameter(context, Constants.TEMPLATE_COLOR_SCHEME, colorScheme);
        // Determine the layout (or use the default layout)
        String layout = "default";
        Set<String> layoutFiles = context.getResourcePaths("/themes/" + this.get(THEME) + "/jsp/");
        if (layoutFiles != null && layoutFiles.size() > 0) {
            for (String thisFile : layoutFiles) {
                if (("/themes/" + this.get(THEME) + "/jsp/layout.jsp").equals(thisFile)) {
                    layout = this.get(THEME);
                }
            }
        }
        if ("default".equals(layout) && !"default".equals(this.get(THEME))) {
            try {
                // Check for a compiled layout
                Class.forName("org.apache.jsp.themes." + JspUtils.makeJavaIdentifier(this.get(THEME))
                        + ".jsp.layout_jsp");
                layout = this.get(THEME);
            } catch (Exception e) {
                LOG.info("Using default theme: " + e.getMessage());
            }
        }
        addParameter(context, Constants.TEMPLATE_LAYOUT, "/themes/" + layout + "/jsp/layout.jsp");
        LOG.info("THEME: " + get(THEME));
        LOG.info("  COLOR SCHEME: " + get(COLOR_SCHEME));
        LOG.info("  LAYOUT: " + "/themes/" + layout + "/jsp/layout.jsp");
    } else {
        // Use the specified template
        addParameter(context, Constants.TEMPLATE_LAYOUT, this.get(JSP_TEMPLATE));
        // Default CSS for all items on page
        addParameter(context, Constants.TEMPLATE_CSS, this.get(CSS_FILE));
    }

    // Default color scheme for themeable items (deprecated)
    if (this.has("SKIN")) {
        addParameter(context, "SKIN", this.get("SKIN"));
    } else {
        addParameter(context, "SKIN", "blue");
        this.add("SKIN", "blue");
    }

    // Application Settings
    if (!this.has(USERS_CAN_REGISTER)) {
        this.add(USERS_CAN_REGISTER, "true");
    }
    if (!this.has(USERS_CAN_INVITE)) {
        this.add(USERS_CAN_INVITE, "true");
    }
    if (!this.has(SHOW_TERMS_AND_CONDITIONS)) {
        this.add(SHOW_TERMS_AND_CONDITIONS, "true");
    }
    if (!this.has(USERS_CAN_START_PROJECTS)) {
        this.add(USERS_CAN_START_PROJECTS, "false");
    }
    if (!this.has(USERS_ARE_ANONYMOUS)) {
        this.add(USERS_ARE_ANONYMOUS, "false");
    }
    if (!this.has(SEARCH_USES_LOCATION)) {
        this.add(SEARCH_USES_LOCATION, "true");
    }
    if (!this.has(SHOW_HOLIDAYS)) {
        this.add(SHOW_HOLIDAYS, "true");
    }

    // Portal
    if (!this.has(HOME_URL)) {
        this.add(HOME_URL, "index.shtml");
    } else if ("Portal.do?command=Default".equals(this.get(HOME_URL))) {
        this.add(HOME_URL, "index.shtml");
    }
    if (!this.has("PORTAL")) {
        this.add("PORTAL", "true");
    }
    if (!this.has(WEB_PAGE_TITLE)) {
        this.add(WEB_PAGE_TITLE, ApplicationVersion.TITLE);
    }
    if (!this.has(LANGUAGE)) {
        this.add(LANGUAGE, "en_US");
    }
    if (!this.has(TIMEZONE)) {
        this.add(TIMEZONE, TimeZone.getDefault().getID());
    }
    if (!this.has(CURRENCY)) {
        this.add(CURRENCY, NumberFormat.getCurrencyInstance().getCurrency().getCurrencyCode());
    }
    if (!this.has(LANGUAGES_SUPPORTED)) {
        this.add(LANGUAGES_SUPPORTED, "en_US");
    }
    if (!this.has(MAIN_PROFILE)) {
        this.add(MAIN_PROFILE, "main-profile");
    }

    // Dimdim service
    if (!this.has(DIMDIM_ENABLED)) {
        this.add(DIMDIM_ENABLED, "false");
    }
    if (!this.has(DIMDIM_API_DOMAIN)) {
        // @note Dimdim public API is no longer available
        //this.add(DIMDIM_API_DOMAIN, "http://webmeeting.dimdim.com/portal");
    }
}