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:org.ambraproject.configuration.WebAppListener.java

/**
 * Initialize the configuration singleton since this web application is getting deployed.<p>
 *
 * By default, WebAppListener uses the default ConfigurationStore initialization. This
 * usually means using /etc/.../ambra.xml. This can be overridden by setting the
 * org.ambraproject.configuration system property or webapp context variable to a URL or a name
 * resolvable as a resource./*from   w w w .ja v a 2s.c o  m*/
 *
 * @param event The servlet event associated with initializing this context
 * @throws Error on non-recoverable config load error
 */
public void contextInitialized(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    FactoryConfig config = getFactoryConfig(context);

    try {
        URL url;

        // Locate the config url.
        if (config.name.startsWith("/WEB-INF")) {
            url = context.getResource(config.name);

            if (url == null)
                throw new MalformedURLException("'" + config.name + "' not found in the web-app context");
        } else {
            try {
                // First see if it is a valid URL
                url = new URL(config.name);
            } catch (MalformedURLException e) {
                // Otherwise, load as a resource
                url = WebAppListener.class.getResource(config.name);
                if (url == null)
                    throw e;
            }
        }

        // Now load the config
        log.info("Loading '" + url + "' (" + config.name + ") configured via " + config.source);
        ConfigurationStore.getInstance().loadConfiguration(url);

        // Setup an application scope attribute that something like freemarker or struts might use
        context.setAttribute("config", ConfigurationStore.getInstance().getConfiguration());
    } catch (MalformedURLException e) {
        log.fatal(config.name + " defined by " + config.source + " is not a valid URL or resource", e);
        throw new Error("Failed to load configuration", e);
    } catch (ConfigurationException e) {
        log.fatal("Failed to initialize configuration factory.", e);
        throw new Error("Failed to load configuration", e);
    }
}

From source file:org.ambraproject.web.VirtualJournalContext.java

/**
 * Search in servlet context - struts directory
 * @param resource path to resource//  ww w  .  ja v  a 2 s .c  om
 * @return true if resource exists in servlet context
 * @throws ServletException Servlet exception
 */
private boolean resourceExistsInServletContext(String resource, ServletContext servletContext)
        throws ServletException {
    try {
        return servletContext.getResource(resource) != null;
    } catch (MalformedURLException mre) {
        throw new ServletException("Invalid resource path: " + resource, mre);
    }
}

From source file:org.apache.catalina.loader.WebappLoader.java

/**
 * Configure associated class loader permissions.
 *///from www .  jav a2 s.c  o m
private void setPermissions() {

    if (System.getSecurityManager() == null)
        return;
    if (!(container instanceof Context))
        return;

    // Tell the class loader the root of the context
    ServletContext servletContext = ((Context) container).getServletContext();

    // Assigning permissions for the work directory
    File workDir = (File) servletContext.getAttribute(Globals.WORK_DIR_ATTR);
    if (workDir != null) {
        try {
            String workDirPath = workDir.getCanonicalPath();
            classLoader.addPermission(new FilePermission(workDirPath, "read,write"));
            classLoader
                    .addPermission(new FilePermission(workDirPath + File.separator + "-", "read,write,delete"));
        } catch (IOException e) {
            // Ignore
        }
    }

    try {

        URL rootURL = servletContext.getResource("/");
        classLoader.addPermission(rootURL);

        String contextRoot = servletContext.getRealPath("/");
        if (contextRoot != null) {
            try {
                contextRoot = (new File(contextRoot)).getCanonicalPath();
                classLoader.addPermission(contextRoot);
            } catch (IOException e) {
                // Ignore
            }
        }

        URL classesURL = servletContext.getResource("/WEB-INF/classes/");
        classLoader.addPermission(classesURL);
        URL libURL = servletContext.getResource("/WEB-INF/lib/");
        classLoader.addPermission(libURL);

        if (contextRoot != null) {

            if (libURL != null) {
                File rootDir = new File(contextRoot);
                File libDir = new File(rootDir, "WEB-INF/lib/");
                try {
                    String path = libDir.getCanonicalPath();
                    classLoader.addPermission(path);
                } catch (IOException e) {
                }
            }

        } else {

            if (workDir != null) {
                if (libURL != null) {
                    File libDir = new File(workDir, "WEB-INF/lib/");
                    try {
                        String path = libDir.getCanonicalPath();
                        classLoader.addPermission(path);
                    } catch (IOException e) {
                    }
                }
                if (classesURL != null) {
                    File classesDir = new File(workDir, "WEB-INF/classes/");
                    try {
                        String path = classesDir.getCanonicalPath();
                        classLoader.addPermission(path);
                    } catch (IOException e) {
                    }
                }
            }

        }

    } catch (MalformedURLException e) {
    }

}

From source file:org.apache.click.service.VelocityTemplateService.java

/**
 * Return the Velocity Engine initialization properties.
 *
 * @return the Velocity Engine initialization properties
 * @throws MalformedURLException if a resource cannot be loaded
 *///from ww  w.j  av  a2 s .c  o  m
@SuppressWarnings("unchecked")
protected Properties getInitProperties() throws MalformedURLException {

    final Properties velProps = new Properties();

    // Set default velocity runtime properties.

    velProps.setProperty(RuntimeConstants.RESOURCE_LOADER, "webapp, class");
    velProps.setProperty("webapp.resource.loader.class", WebappResourceLoader.class.getName());
    velProps.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());

    if (configService.isProductionMode() || configService.isProfileMode()) {
        velProps.put("webapp.resource.loader.cache", "true");
        velProps.put("webapp.resource.loader.modificationCheckInterval", "0");
        velProps.put("class.resource.loader.cache", "true");
        velProps.put("class.resource.loader.modificationCheckInterval", "0");
        velProps.put("velocimacro.library.autoreload", "false");

    } else {
        velProps.put("webapp.resource.loader.cache", "false");
        velProps.put("class.resource.loader.cache", "false");
        velProps.put("velocimacro.library.autoreload", "true");
    }

    velProps.put(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, LogChuteAdapter.class.getName());

    velProps.put("directive.if.tostring.nullcheck", "false");

    // Use 'macro.vm' exists set it as default VM library
    ServletContext servletContext = configService.getServletContext();
    URL macroURL = servletContext.getResource("/" + MACRO_VM_FILE_NAME);
    if (macroURL != null) {
        velProps.put("velocimacro.library", "/" + MACRO_VM_FILE_NAME);

    } else {
        // Else use '/click/VM_global_library.vm' if available.
        URL globalMacroURL = servletContext.getResource(VM_FILE_PATH);
        if (globalMacroURL != null) {
            velProps.put("velocimacro.library", VM_FILE_PATH);

        } else {
            // Else use '/WEB-INF/classes/macro.vm' if available.
            String webInfMacroPath = "/WEB-INF/classes/macro.vm";
            URL webInfMacroURL = servletContext.getResource(webInfMacroPath);
            if (webInfMacroURL != null) {
                velProps.put("velocimacro.library", webInfMacroPath);
            }
        }
    }

    // Set the character encoding
    String charset = configService.getCharset();
    if (charset != null) {
        velProps.put("input.encoding", charset);
    }

    // Load user velocity properties.
    Properties userProperties = new Properties();

    String filename = DEFAULT_TEMPLATE_PROPS;

    InputStream inputStream = servletContext.getResourceAsStream(filename);

    if (inputStream != null) {
        try {
            userProperties.load(inputStream);

        } catch (IOException ioe) {
            String message = "error loading velocity properties file: " + filename;
            configService.getLogService().error(message, ioe);

        } finally {
            try {
                inputStream.close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    }

    // Add user properties.
    Iterator iterator = userProperties.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry entry = (Map.Entry) iterator.next();

        Object pop = velProps.put(entry.getKey(), entry.getValue());

        LogService logService = configService.getLogService();
        if (pop != null && logService.isDebugEnabled()) {
            String message = "user defined property '" + entry.getKey() + "=" + entry.getValue()
                    + "' replaced default property '" + entry.getKey() + "=" + pop + "'";
            logService.debug(message);
        }
    }

    ConfigService configService = ClickUtils.getConfigService(servletContext);
    LogService logger = configService.getLogService();
    if (logger.isTraceEnabled()) {
        TreeMap sortedPropMap = new TreeMap();

        Iterator i = velProps.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry entry = (Map.Entry) i.next();
            sortedPropMap.put(entry.getKey(), entry.getValue());
        }

        logger.trace("velocity properties: " + sortedPropMap);
    }

    return velProps;
}

From source file:org.apache.juddi.adminconsole.hub.UddiAdminHub.java

private UddiAdminHub(ServletContext application, HttpSession _session) throws Exception {
    URL prop = application.getResource("/WEB-INF/config.properties");
    if (prop == null) {
        application.getResource("WEB-INF/config.properties");
    }/*from  w ww . ja  va 2s  .c  om*/
    if (prop == null) {
        throw new Exception("Cannot locate the configuration file.");
    }
    session = _session;

    InputStream in = prop.openStream();
    Properties p = new Properties();
    p.load(in);
    in.close();
    session = _session;
    properties = p;
    EnsureConfig();
}

From source file:org.apache.juddi.webconsole.hub.UddiHub.java

private UddiHub(ServletContext application, HttpSession _session) throws Exception {
    session = _session;//from w w  w. j  a va2s.  c om

    URL prop = application.getResource("/META-INF/config.properties");
    if (prop == null) {
        prop = application.getResource("META-INF/config.properties");
    }
    if (prop == null) {
        throw new Exception("Cannot locate the configuration file.");
    }

    InputStream in = prop.openStream();
    Properties p = new Properties();
    p.load(in);
    in.close();
    properties = p;

    EnsureConfig();
}

From source file:org.apache.struts2.s1.ActionFormValidationInterceptor.java

/**
 * Initialize the validator resources for this module.
 *
 * @throws IOException      if an input/output error is encountered
 * @throws ServletException if we cannot initialize these resources
 *///from  w  w  w.j  a v  a  2  s  . c  om
protected ValidatorResources loadResources(ServletContext ctx) throws IOException, ServletException {
    if ((pathnames == null) || (pathnames.length() <= 0)) {
        return null;
    }

    StringTokenizer st = new StringTokenizer(pathnames, RESOURCE_DELIM);

    List urlList = new ArrayList();
    ValidatorResources resources = null;
    try {
        while (st.hasMoreTokens()) {
            String validatorRules = st.nextToken().trim();

            if (LOG.isInfoEnabled()) {
                LOG.info("Loading validation rules file from '" + validatorRules + "'");
            }

            URL input = ctx.getResource(validatorRules);

            // If the config isn't in the servlet context, try the class
            // loader which allows the config files to be stored in a jar
            if (input == null) {
                input = getClass().getResource(validatorRules);
            }

            if (input != null) {
                urlList.add(input);
            } else {
                throw new ServletException("Skipping validation rules file from '" + validatorRules
                        + "'.  No url could be located.");
            }
        }

        int urlSize = urlList.size();
        String[] urlArray = new String[urlSize];

        for (int urlIndex = 0; urlIndex < urlSize; urlIndex++) {
            URL url = (URL) urlList.get(urlIndex);

            urlArray[urlIndex] = url.toExternalForm();
        }

        resources = new ValidatorResources(urlArray);
    } catch (SAXException sex) {
        LOG.error("Skipping all validation", sex);
        throw new StrutsException("Skipping all validation because the validation files cannot be loaded", sex);
    }
    return resources;
}

From source file:org.auraframework.http.AuraResourceServlet.java

public static boolean isResourceLocallyAvailable(String resourceURI) {
    if (resourceURI != null && resourceURI.startsWith("/") && servletContext != null) {
        try {//from   w  w w.  jav  a 2 s .c o m
            URI uri = URI.create(resourceURI);
            if (uri != null) {
                ServletContext c = servletContext.getContext(uri.getPath());
                if (c != null && c.getResource(uri.getPath()) != null) {
                    return true;
                }
            }
        } catch (Exception e) {
        }
    }
    return false;
}

From source file:org.b3log.latke.Latkes.java

/**
 * Gets a file in web application with the specified path.
 *
 * @param path the specified path/* ww  w.j a v  a 2  s .co m*/
 * @return file,
 * @see ServletContext#getResource(String)
 * @see ServletContext#getResourceAsStream(String)
 */
public static File getWebFile(final String path) {
    final ServletContext servletContext = AbstractServletListener.getServletContext();

    File ret;

    try {
        final URL resource = servletContext.getResource(path);

        if (null == resource) {
            return null;
        }

        ret = FileUtils.toFile(resource);

        if (null == ret) {
            final File tempdir = (File) servletContext.getAttribute("javax.servlet.context.tempdir");

            ret = new File(tempdir.getPath() + path);

            FileUtils.copyURLToFile(resource, ret);

            ret.deleteOnExit();
        }

        return ret;
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Reads file [path=" + path + "] failed", e);

        return null;
    }
}

From source file:org.eclipse.birt.report.utility.ParameterAccessor.java

/**
 * Returns real path relative to context
 * /*w w  w  .ja v  a2  s  .  c  o m*/
 * @param path
 * @param context
 * @return
 */
private static String getRealPath(String path, ServletContext context) {
    assert path != null;
    String realPath = null;
    try {
        String orginalPath = path;

        if (!path.startsWith("/")) //$NON-NLS-1$
        {
            path = "/" + path; //$NON-NLS-1$
        }

        realPath = context.getRealPath(path);
        if (realPath == null) {
            // try to get root path from system properties
            String rootPath = System.getProperty(IBirtConstants.SYS_PROP_ROOT_PATH);
            if (rootPath != null && isUniversalPath(rootPath)) {
                path = path.substring(1);
                realPath = DataUtil.trimSepEnd(rootPath) + "/" + path; //$NON-NLS-1$
            } else {
                URL url = context.getResource("/"); //$NON-NLS-1$
                if (url != null) {
                    String urlRoot = null;
                    // for file urls
                    if ("file".equalsIgnoreCase(url.getProtocol())) //$NON-NLS-1$
                    {
                        urlRoot = DataUtil.trimString(url.getPath());
                    }
                    // for other url protocals, e.g. path in an unpacked
                    // war, or other global urls
                    else {
                        urlRoot = DataUtil.trimString(url.toExternalForm());
                    }
                    if (orginalPath.startsWith(urlRoot)) {
                        realPath = orginalPath;
                    } else {
                        if (urlRoot.endsWith("/") //$NON-NLS-1$
                                || orginalPath.startsWith("/")) //$NON-NLS-1$
                        {
                            realPath = urlRoot + orginalPath;
                        } else {
                            realPath = urlRoot + "/" + orginalPath; //$NON-NLS-1$
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        realPath = path;
    }

    return realPath;
}