Example usage for javax.servlet ServletContext getResource

List of usage examples for javax.servlet ServletContext getResource

Introduction

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

Prototype

public URL getResource(String path) throws MalformedURLException;

Source Link

Document

Returns a URL to the resource that is mapped to the given path.

Usage

From source file:com.liferay.portal.deploy.hot.ExtHotDeployListener.java

protected void mergePortalProperties(String portalWebDir, ServletContext servletContext) throws Exception {
    URL pluginPropsURL = servletContext
            .getResource("WEB-INF/ext-web/docroot/WEB-INF/classes/portal-ext.properties");
    if (pluginPropsURL == null) {
        if (_log.isDebugEnabled()) {
            _log.debug("Ext Plugin's portal-ext.properties not found");
        }//from w  ww.j a  v  a2s  . co  m
        return;
    }
    if (_log.isDebugEnabled()) {
        _log.debug("Loading portal-ext.properties from " + pluginPropsURL);
    }
    PropertiesConfiguration pluginProps = new PropertiesConfiguration(pluginPropsURL);

    PropertiesConfiguration portalProps = new PropertiesConfiguration(
            this.getClass().getClassLoader().getResource("portal.properties"));

    File extPluginPropsFile = new File(portalWebDir + "WEB-INF/classes/portal-ext-plugin.properties");
    PropertiesConfiguration extPluginPortalProps = new PropertiesConfiguration();
    if (extPluginPropsFile.exists()) {
        extPluginPortalProps.load(extPluginPropsFile);
    }

    for (Iterator it = pluginProps.getKeys(); it.hasNext();) {
        String key = (String) it.next();
        List value = pluginProps.getList(key);
        if (key.endsWith("+")) {
            key = key.substring(0, key.length() - 1);
            List newValue = new ArrayList();
            if (extPluginPortalProps.containsKey(key)) {
                // already rewrited
                newValue.addAll(extPluginPortalProps.getList(key));
            } else {
                newValue.addAll(portalProps.getList(key));
            }

            newValue.addAll(value);
            extPluginPortalProps.setProperty(key, newValue);
        } else {
            extPluginPortalProps.setProperty(key, value);
        }
    }

    extPluginPortalProps.save(extPluginPropsFile);
}

From source file:de.drv.dsrv.spoc.web.webservice.jax.ExtraSchemaValidationHandler.java

private void validateExtraRequest(final Node transportNode, final ServletContext servletContext)
        throws Exception {

    // Validator-Objekt mit eXTra-Schema als Basis erstellen
    final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = factory.newSchema(servletContext.getResource(SCHEMA_PATH));
    final Validator validator = schema.newValidator();

    try {/*from   w ww . java  2  s  .  c o m*/
        // Validiere Transport-Element gegen eXTra-Schema
        validator.validate(new DOMSource(transportNode));
    } catch (final SAXException e) {
        // Falls MTOM-Attachement, dann den Fehler bzgl. cid-Referenz
        // ignorieren
        if (!(e.getMessage().contains("cid:") && e.getMessage().contains("'base64Binary'"))) {
            LOG.warn("Fehler bei der XML-Validierung: " + e.getMessage());
            throw new InvalidExtraRequestException(e.getMessage());
        }
    }
}

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

/**
 * Gets the PropertiesConfiguration for a property file from servlet context
 * @param propFile//from   w w w  . j av a 2  s . com
 * @param servletContext
 * @return
 * @throws ServletException
 */
public static PropertiesConfiguration loadServletContextPropFile(String propFile, ServletContext servletContext)
        throws ServletException {
    PropertiesConfiguration pc = null;
    InputStream in = null;
    URL propFileURL = null;
    try {
        if (pc == null && servletContext != null) {
            propFileURL = servletContext.getResource("/WEB-INF/" + propFile);
            in = propFileURL.openStream();
            pc = new PropertiesConfiguration();
            pc.load(in);
            in.close();
        }
    } catch (Exception e) {
        LOGGER.error("Could not read " + propFile + " from servlet context " + propFileURL == null ? ""
                : propFileURL.toExternalForm() + ". Exiting. " + e.getMessage());
        throw new ServletException(e);
    }
    return pc;
}

From source file:com.ocpsoft.pretty.faces.el.resolver.FacesConfigBeanNameResolver.java

/**
 * Returns a set of faces-config.xml files. This set includes the default
 * configuration file, all additional files mentioned via the
 * <code>javax.faces.CONFIG_FILES</code> init parameter and all files found
 * in META-INF folders./*from w  w w . j  a  v  a 2 s  .  co m*/
 * 
 * @param servletContext
 *           The ServletContext
 * @param classLoader
 *           The classloader used to find files in META-INF directories
 * @return A set of URLs
 */
private Set<URL> getFacesConfigFiles(ServletContext servletContext, ClassLoader classLoader) {

    // set of URLs to process
    Set<URL> result = new HashSet<URL>();

    try {

        // get default faces-config.xml
        URL defaultFacesConfig = servletContext.getResource(WEB_INF_FACES_CONFIG_XML);
        if (defaultFacesConfig != null) {
            result.add(defaultFacesConfig);
        }

        // get additional configuration files from init parameter
        result.addAll(getConfigFilesFromInitParameter(servletContext));

        // Find configuration files META-INF directories
        try {
            Enumeration<URL> resources = classLoader.getResources(META_INF_FACES_CONFIG_XML);
            while (resources.hasMoreElements()) {
                result.add(resources.nextElement());
            }
        } catch (IOException e) {
            log.error("Failed to load faces-config.xml files from META-INF directories", e);
        }

    } catch (MalformedURLException e) {
        // should not happen, because URLs are hard-coded
        throw new IllegalArgumentException(e);
    }

    return result;
}

From source file:com.aurel.track.util.PluginUtils.java

/**
 * Gets a file (or directory) with a specific name from the root of the web application
 * @param servletContext//from   www . j a  va2s  .  c o  m
 * @param fileName
 * @return
 */
public static File getResourceFileFromWebAppRoot(ServletContext servletContext, String fileName) {
    URL urlDest;
    File file = null;
    //first try to get the template dir through class.getResource(path)
    urlDest = PluginUtils.class.getResource("/../../" + fileName);
    urlDest = createValidFileURL(urlDest);
    if (urlDest != null) {
        file = new File(urlDest.getPath());
    }
    //second try to get the template dir through servletContext.getResource(path)
    if ((file == null || !file.exists()) && servletContext != null) {
        try {
            urlDest = servletContext.getResource("/" + fileName);
            urlDest = createValidFileURL(urlDest);
            if (urlDest != null) {
                file = new File(urlDest.getPath());
            }
        } catch (MalformedURLException e) {
            LOGGER.error("Getting the URL through getServletContext().getResource(path) failed with "
                    + e.getMessage());
        }
    }
    //third try to get the template dir through servletContext.getRealPath(path)
    if ((file == null || !file.exists()) && servletContext != null) {
        String path;
        //does not work for unexpanded .war
        path = servletContext.getRealPath(File.separator) + fileName;
        file = new File(path);
    }
    return file;
}

From source file:com.trendmicro.hdfs.webdav.HDFSWebDAVServlet.java

@Override
public void init() throws ServletException {
    super.init();
    resourcePathPrefix = getInitParameter(INIT_PARAM_RESOURCE_PATH_PREFIX);
    if (resourcePathPrefix == null) {
        LOG.debug("Missing path prefix -> setting to empty string.");
        resourcePathPrefix = "";
    } else if (resourcePathPrefix.endsWith("/")) {
        LOG.debug("Path prefix ends with '/' -> removing trailing slash.");
        resourcePathPrefix = resourcePathPrefix.substring(0, resourcePathPrefix.length() - 1);
    }//from   ww w  .  j  a  v a 2s .c  o m

    LOG.info("ServletName: " + getServletName());
    LOG.info("ServletInfo: " + getServletInfo());

    ServletContext context = getServletContext();

    context.setAttribute(CTX_ATTR_RESOURCE_PATH_PREFIX, resourcePathPrefix);
    LOG.info(INIT_PARAM_RESOURCE_PATH_PREFIX + " is '" + resourcePathPrefix + "'");

    String configParam = getInitParameter(INIT_PARAM_RESOURCE_CONFIG);
    if (configParam != null)
        try {
            getResourceConfig().parse(context.getResource(configParam));
        } catch (MalformedURLException e) {
            LOG.debug("Unable to build resource filter provider");
        }
}

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  va2 s .  c  om
    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  www . j  a  va2 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);
        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:org.motechproject.server.osgi.OsgiFrameworkService.java

/**
 * Find built-in/mandatory bundles/*from w  ww.j a v  a 2s.c o  m*/
 * 
 * @param servletContext
 * @return
 * @throws Exception
 */
private List<URL> findInternalBundles(ServletContext servletContext) throws Exception {
    List<URL> list = new ArrayList<URL>();
    if (StringUtils.isNotBlank(internalBundleFolder)) {
        @SuppressWarnings("unchecked")
        Set<String> paths = servletContext.getResourcePaths(internalBundleFolder);
        if (paths != null) {
            for (String path : paths) {
                if (path.endsWith(".jar")) {
                    URL url = servletContext.getResource(path);
                    if (url != null) {
                        list.add(url);
                    }
                }
            }
        }
    }
    return list;
}