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.intermine.web.struts.InitialiserPlugin.java

private void loadAspectsConfig(ServletContext servletContext) {
    InputStream xmlInputStream = servletContext.getResourceAsStream("/WEB-INF/aspects.xml");
    InputStream xmlInputStreamForValidate = servletContext.getResourceAsStream("/WEB-INF/aspects.xml");
    if (xmlInputStream == null) {
        LOG.info("Unable to find /WEB-INF/aspects.xml, there will be no aspects");
        SessionMethods.setAspects(servletContext, Collections.EMPTY_MAP);
        SessionMethods.setCategories(servletContext, Collections.EMPTY_SET);
    } else {/*from  w w  w. ja v a 2 s .c om*/
        StringWriter writer = new StringWriter();
        try {
            IOUtils.copy(xmlInputStreamForValidate, writer);
        } catch (IOException ioe) {
            LOG.error("Problems converting xmlInputStream into a String ", ioe);
            blockingErrorKeys.put("errors.init.aspects.generic", ioe.getMessage());
            return;
        }
        String xml = writer.toString();
        String xmlSchemaUrl = "";
        try {
            xmlSchemaUrl = servletContext.getResource("/WEB-INF/aspects.xsd").toString();
        } catch (MalformedURLException mue) {
            LOG.warn("Problems retrieving url fo aspects.xsd ", mue);
        }
        Map<String, Aspect> aspects;
        if (validateXML(xml, xmlSchemaUrl, "errors.init.aspects.validation")) {
            try {
                aspects = AspectBinding.unmarhsal(xmlInputStream);
            } catch (Exception e) {
                LOG.error("problem while reading aspect configuration file", e);
                blockingErrorKeys.put("errors.init.aspects", e.getMessage());
                return;
            }
            SessionMethods.setAspects(servletContext, aspects);
            SessionMethods.setCategories(servletContext, Collections.unmodifiableSet(aspects.keySet()));
        }
    }
}

From source file:org.intermine.web.struts.InitialiserPlugin.java

/**
 * Object and widget display configuration
 *///from  w w  w .  j  av a 2s  . co  m
private WebConfig loadWebConfig(ServletContext servletContext, ObjectStore os) {
    WebConfig retval = null;
    InputStream xmlInputStream = servletContext.getResourceAsStream("/WEB-INF/webconfig-model.xml");
    InputStream xmlInputStreamForValidation = servletContext
            .getResourceAsStream("/WEB-INF/webconfig-model.xml");
    if (xmlInputStream == null) {
        LOG.error("Unable to find /WEB-INF/webconfig-model.xml.");
        blockingErrorKeys.put("errors.init.webconfig.notfound", null);
    } else {
        StringWriter writer = new StringWriter();
        try {
            IOUtils.copy(xmlInputStreamForValidation, writer);
        } catch (IOException ioe) {
            LOG.error("Problems converting xmlInputStream into a String ", ioe);
            blockingErrorKeys.put("errors.init.webconfig.generic", ioe.getMessage());
        }
        String xml = writer.toString();
        String xmlSchemaUrl = "";
        try {
            xmlSchemaUrl = servletContext.getResource("/WEB-INF/webconfig-model.xsd").toString();
        } catch (MalformedURLException mue) {
            LOG.warn("Problems retrieving url fo aspects.xsd ", mue);
        }
        if (validateXML(xml, xmlSchemaUrl, "errors.init.webconfig.validation")) {
            try {
                retval = WebConfig.parse(servletContext, os.getModel());
                String validationMessage = retval.validateWidgetsConfig(os.getModel());
                if (validationMessage.isEmpty()) {
                    SessionMethods.setWebConfig(servletContext, retval);
                } else {
                    blockingErrorKeys.put("errors.init.webconfig.validation", validationMessage);
                }
            } catch (FileNotFoundException fnf) {
                LOG.error("Problem to find the webconfig-model.xml file.", fnf);
                blockingErrorKeys.put("errors.init.webconfig.notfound", null);
            } catch (ClassNotFoundException cnf) {
                LOG.error("Classes mentioned in the webconfig-model.xml" + " file aren't in the Model", cnf);
                blockingErrorKeys.put("errors.init.webconfig.classnotfound", cnf.getMessage());
            } catch (Exception e) {
                LOG.error("Problem to parse the webconfig-model.xml file", e);
                blockingErrorKeys.put("errors.init.webconfig.parsing", e.getMessage());
            }
        }
    }
    return retval;
}

From source file:org.iterx.miru.support.servlet.dispatcher.context.BootstrapServletContextListener.java

public void contextInitialized(ServletContextEvent servletContextEvent) {

    try {/*from  w  w  w .  j  a v  a  2s .  c o  m*/
        DispatcherApplicationContext applicationContext;
        ApplicationContext parentApplicationContext;
        ServletContext servletContext;
        String parameter;
        String path;
        int next;

        parentApplicationContext = null;
        servletContext = servletContextEvent.getServletContext();

        path = resolveContextPath(servletContext);
        next = path.length();
        while ((next = path.lastIndexOf('/', next - 1)) > -1) {
            if ((parentApplicationContext = (ApplicationContext) contexts.get(path.substring(0, next))) != null)
                break;
        }

        applicationContext = ((parentApplicationContext != null)
                ? new ServletDispatcherApplicationContext(parentApplicationContext, servletContext)
                : new ServletDispatcherApplicationContext(servletContext));

        if ((parameter = servletContext.getInitParameter(ServletDispatcherApplicationContext.BEANS)) != null
                && applicationContext instanceof Loadable) {
            URL url;

            if ((url = (servletContext.getResource(parameter))) != null)
                ((Loadable) applicationContext).load(new UriStreamResource(url.toURI()));
            else
                throw new IOException("Invalid stream [" + parameter + "]");

        }
        if (inheritable) {
            synchronized (contexts) {
                contexts.put(path, applicationContext);
            }
        }

        servletContext.setAttribute((DispatcherApplicationContext.class).getName(), applicationContext);
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.error("Initialisation failed.", e);
        throw new RuntimeException("Initialisation failed.", e);
    }

}

From source file:org.iterx.miru.support.servlet.HttpDispatcherServlet.java

public void init(ServletConfig servletConfig) throws ServletException {

    try {/*from   ww w .j  a v  a  2s.  c  o  m*/
        DispatcherApplicationContext applicationContext;
        ApplicationContext parentApplicationContext;
        HandlerChainFactory handlerChainFactory;
        ServletContext servletContext;
        String parameter;

        servletContext = servletConfig.getServletContext();

        parentApplicationContext = (ApplicationContext) servletContext
                .getAttribute((DispatcherApplicationContext.class).getName());
        applicationContext = ((parentApplicationContext != null)
                ? new ServletDispatcherApplicationContext(parentApplicationContext, servletContext)
                : new ServletDispatcherApplicationContext(servletContext));

        if ((parameter = servletConfig.getInitParameter(ServletDispatcherApplicationContext.BEANS)) != null
                && applicationContext instanceof Loadable) {
            URL url;

            if ((url = (servletContext.getResource(parameter))) != null)
                ((Loadable) applicationContext).load(new UriStreamResource(url.toURI()));
            else
                throw new IOException("Invalid stream [" + parameter + "]");
        }

        handlerChainFactory = applicationContext.getHandlerChainFactory();
        if ((parameter = servletConfig.getInitParameter(ServletDispatcherApplicationContext.CHAINS)) != null
                && handlerChainFactory instanceof Loadable) {
            URL url;

            if ((url = (servletContext.getResource(parameter))) != null)
                ((Loadable) handlerChainFactory).load(new UriStreamResource(url.toURI()));
            else
                throw new IOException("Invalid stream [" + parameter + "]");
        }

        if (dispatcher == null
                && (dispatcher = (Dispatcher<HttpServletRequestContext, HttpServletResponseContext>) applicationContext
                        .getBeanOfType(Dispatcher.class)) == null)
            dispatcher = new Dispatcher<HttpServletRequestContext, HttpServletResponseContext>();

        dispatcher.setHandlerChainMap(handlerChainFactory.getHandlerChains());
        processingContextFactory = applicationContext.getProcessingContextFactory();
    } catch (Exception e) {
        LOGGER.error("Initialisation failed.", e);
        throw new ServletException("Initialisation failed.", e);
    }
}

From source file:org.jasig.resourceserver.utils.aggr.ResourcesElementsProviderImpl.java

/**
 * If the resource serving servlet context is available and the resource
 * is available in the context, create a URL to the resource in that context.
 * If not, create a local URL for the requested resource.
 *//*from   ww  w . j  ava 2 s .  c  o m*/
protected String resolveResourceContextPath(HttpServletRequest request, String resource) {
    final String resourceContextPath = this.getResourceServerContextPath();

    this.logger.debug("Attempting to locate resource serving webapp with context path: {}",
            resourceContextPath);

    //Try to resolve the 
    final ServletContext resourceContext = this.servletContext.getContext(resourceContextPath);
    if (resourceContext == null || !resourceContextPath.equals(resourceContext.getContextPath())) {
        this.logger.warn(
                "Could not find resource serving webapp under context path {} ensure the resource server is deployed and cross context dispatching is enable for this web application",
                resourceContextPath);
        return request.getContextPath();
    }

    this.logger.debug("Found resource serving webapp at: {}", resourceContextPath);

    URL url = null;
    try {
        url = resourceContext.getResource(resource);
    } catch (MalformedURLException e) {
        //Ignore
    }

    if (url == null) {
        this.logger.debug(
                "Resource serving webapp {} doesn't contain resource {} Falling back to the local resource.",
                resourceContextPath, resource);
        return request.getContextPath();
    }

    this.logger.debug("Resource serving webapp {} contains resource {} Using resource server.",
            resourceContextPath, resource);
    return resourceContextPath;
}

From source file:org.jboss.web.tomcat.tc4.SingleSignOnContextConfig.java

/**
 * Process the application configuration file, if it exists.
 *//*w  w  w.ja v  a  2 s.c o  m*/
private void applicationConfig() {

    // Open the application web.xml file, if it exists
    InputStream stream = null;
    ServletContext servletContext = context.getServletContext();
    if (servletContext != null)
        stream = servletContext.getResourceAsStream(Constants.ApplicationWebXml);
    if (stream == null) {
        log(sm.getString("contextConfig.applicationMissing"));
        return;
    }

    // Process the application web.xml file
    synchronized (webDigester) {
        try {
            URL url = servletContext.getResource(Constants.ApplicationWebXml);
            InputSource is = new InputSource(url.toExternalForm());
            is.setByteStream(stream);
            webDigester.setDebug(getDebug());
            if (context instanceof StandardContext) {
                ((StandardContext) context).setReplaceWelcomeFiles(true);
            }
            webDigester.clear();
            webDigester.push(context);
            webDigester.parse(is);
        } catch (SAXParseException e) {
            log(sm.getString("contextConfig.applicationParse"), e);
            log(sm.getString("contextConfig.applicationPosition", "" + e.getLineNumber(),
                    "" + e.getColumnNumber()));
            ok = false;
        } catch (Exception e) {
            log(sm.getString("contextConfig.applicationParse"), e);
            ok = false;
        } finally {
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
                log(sm.getString("contextConfig.applicationClose"), e);
            }
        }
    }

}

From source file:org.mifos.framework.ApplicationInitializer.java

private void copyResources(ServletContext sc) throws IOException {
    URL protocol = ETLReportDWHelper.class.getClassLoader().getResource("sql/release-upgrades.txt");
    ConfigurationLocator configurationLocator = new ConfigurationLocator();
    String configPath = configurationLocator.getConfigurationDirectory();
    try {/*from www .j  a va2s . c  om*/
        if (protocol.getProtocol().equals("jar")) {
            String destinationDirectoryForJobs = configPath + "/ETL/MifosDataWarehouseETL";
            String destinationDirectoryForJar = configPath + "/ETL/mifos-etl-plugin-1.0-SNAPSHOT.one-jar.jar";
            String pathFromJar = "/WEB-INF/mifos-etl-plugin-1.0-SNAPSHOT.one-jar.jar";
            String pathFromJobs = "/WEB-INF/MifosDataWarehouseETL/";
            if (File.separatorChar == '\\') {
                destinationDirectoryForJobs = destinationDirectoryForJobs.replaceAll("/", "\\\\");
                destinationDirectoryForJar = destinationDirectoryForJar.replaceAll("/", "\\\\");
            }
            File directory = new File(destinationDirectoryForJobs);
            directory.mkdirs();
            FileUtils.cleanDirectory(directory);
            File jarDest = new File(destinationDirectoryForJar);
            URL fullPath = sc.getResource(pathFromJar);
            File f = new File(sc.getResource(pathFromJobs).toString().replace("file:", ""));
            for (File fileEntry : f.listFiles()) {
                FileUtils.copyFileToDirectory(fileEntry, directory);
                logger.info("Copy file: " + fileEntry.getName() + " to: " + directory);
            }
            FileUtils.copyURLToFile(fullPath, jarDest);
            logger.info("Copy file: " + fullPath + " to: " + directory);
        }
    } catch (NullPointerException e) {
        String destinationDirectoryForJobs = configPath + "/ETL/MifosDataWarehouseETL";
        String destinationDirectoryForJar = configPath + "/ETL/";
        String pathFromJar = sc.getRealPath("/") + "/WEB-INF/mifos-etl-plugin-1.0-SNAPSHOT.one-jar.jar";
        String pathFromJobs = sc.getRealPath("/") + "/WEB-INF/MifosDataWarehouseETL/";
        if (File.separatorChar == '\\') {
            destinationDirectoryForJobs = destinationDirectoryForJobs.replaceAll("/", "\\\\");
            destinationDirectoryForJar = destinationDirectoryForJar.replaceAll("/", "\\\\");
        }
        File directory = new File(destinationDirectoryForJobs);
        directory.mkdirs();
        FileUtils.cleanDirectory(directory);
        logger.info(System.getProperty("user.dir"));
        File jarDest = new File(destinationDirectoryForJar);
        URL fullPath = sc.getResource(pathFromJar);
        File f = new File(pathFromJobs);
        for (File fileEntry : f.listFiles()) {
            FileUtils.copyFileToDirectory(fileEntry, directory);
            logger.info("Copy file: " + fileEntry.getName() + " to: " + directory);
        }
        FileUtils.copyFileToDirectory(new File(pathFromJar), jarDest);
        logger.info("Copy file: " + fullPath + " to: " + directory);
    }
}

From source file:org.openanzo.servlet.WelcomeFilesFilter.java

/**
 * Serves the welcome files if request path ends with "/".
 * //from w w  w .  jav a 2 s . c  o m
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    LOG.debug("Apply welcome files filter...");
    if (m_welcomeFiles.length > 0 && request instanceof HttpServletRequest) {
        String servletPath = (((HttpServletRequest) request).getServletPath());
        String pathInfo = ((HttpServletRequest) request).getPathInfo();

        LOG.debug("Servlet path: " + servletPath);
        LOG.debug("Path info: " + pathInfo);

        if ((pathInfo != null && pathInfo.endsWith("/"))
                || (servletPath != null && servletPath.endsWith("/"))) {
            final ServletContext servletContext = m_filterConfig.getServletContext();
            for (String welcomeFile : m_welcomeFiles) {
                final String welcomePath = URIUtil.addPaths(servletPath,
                        URIUtil.addPaths(pathInfo, welcomeFile));
                final String welcomeResource = URIUtil.addPaths(pathInfo, welcomeFile);
                final URL welcomeFileUrl = servletContext.getResource(welcomeResource);
                if (welcomeFileUrl != null) {
                    if (m_redirect && response instanceof HttpServletResponse) {
                        ((HttpServletResponse) response).sendRedirect(welcomeFile);
                        return;
                    } else {
                        final RequestDispatcher requestDispatcher = request.getRequestDispatcher(welcomePath);
                        if (requestDispatcher != null) {
                            requestDispatcher.forward(request, response);
                            return;
                        }
                    }
                }
            }
        } else if ((pathInfo == null || pathInfo.length() == 0)
                && (servletPath != null && paths.contains(servletPath))) {
            final ServletContext servletContext = m_filterConfig.getServletContext();
            for (String welcomeFile : m_welcomeFiles) {
                final String welcomePath = URIUtil.addPaths(servletPath, welcomeFile);
                final String welcomeResource = welcomeFile;
                final URL welcomeFileUrl = servletContext.getResource(welcomeResource);
                if (welcomeFileUrl != null) {
                    if (m_redirect && response instanceof HttpServletResponse) {
                        ((HttpServletResponse) response).sendRedirect(welcomePath);
                        return;
                    } else {
                        final RequestDispatcher requestDispatcher = request.getRequestDispatcher(welcomePath);
                        if (requestDispatcher != null) {
                            requestDispatcher.forward(request, response);
                            return;
                        }
                    }
                }
            }
        }
    } else {
        if (m_welcomeFiles.length == 0) {
            LOG.debug("Welcome filter not applied as there are no welcome files configured.");
        }
        if (!(request instanceof HttpServletRequest)) {
            LOG.debug("Welcome filter not applied as the request is not an "
                    + HttpServletRequest.class.getSimpleName());
        }
    }
    // if we are here means that the request was not handled by welcome files filter so, go on
    chain.doFilter(request, response);
}

From source file:org.opencms.main.CmsServletContainerSettings.java

/**
 * Creates a new object.<p>/*from   w  w  w .  ja  v  a2s  .com*/
 * 
 * @param context used to find out specifics of the servlet container
 */
public CmsServletContainerSettings(ServletContext context) {

    // CmsSystemInfo<init> has to call this with null (for setup)
    if (context != null) {
        // check for OpenCms home (base) directory path
        String webInfRfsPath = context.getInitParameter(OpenCmsServlet.SERVLET_PARAM_OPEN_CMS_HOME);
        if (CmsStringUtil.isEmpty(webInfRfsPath)) {
            webInfRfsPath = CmsFileUtil.searchWebInfFolder(context.getRealPath("/"));
            if (CmsStringUtil.isEmpty(webInfRfsPath)) {
                throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_FOLDER_0));
            }
        }

        // set the default web application name
        // read the the default name from the servlet context parameters
        String defaultWebApplication = context.getInitParameter("DefaultWebApplication");

        // read the the OpenCms servlet mapping from the servlet context parameters
        String servletMapping = context.getInitParameter(OpenCmsServlet.SERVLET_PARAM_OPEN_CMS_SERVLET);
        if (servletMapping == null) {
            throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_SERVLET_0));
        }

        // read the servlet container name
        String servletContainerName = context.getServerInfo();

        // web application context: 
        // read it from the servlet context parameters
        //      this is needed in case an application server specific deployment descriptor is used to changed the webapp context
        String webApplicationContext = context
                .getInitParameter(OpenCmsServlet.SERVLET_PARAM_WEB_APPLICATION_CONTEXT);
        if (CmsStringUtil.isEmptyOrWhitespaceOnly(webApplicationContext)) {
            try {
                URL contextRelativeUrl = context.getResource("/");
                webApplicationContext = contextRelativeUrl.getPath();
                String[] pathTokens = CmsStringUtil.splitAsArray(webApplicationContext, '/');
                if (pathTokens.length == 1) {
                    /*
                     * There may be a "" context configured (e.g. in GlassFish).
                     */
                    webApplicationContext = "";
                } else {

                    webApplicationContext = pathTokens[pathTokens.length - 1];
                }
            } catch (MalformedURLException e) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_INIT_CONTEXTNAME_0), e);
            }

        }
        // init values: 
        init(webInfRfsPath, defaultWebApplication, servletMapping, servletContainerName, webApplicationContext);
        // finally care for the speciality of different servlet containers: 
        initContainerSpecifics(context);
    }
}

From source file:org.openfaces.demo.services.Rules.java

public static void buildSiteRules(ServletContext context) {
    try {/*from  www . j a  v  a  2  s.co m*/
        Digester digester = new Digester();
        digester.setValidating(false);
        digester.addObjectCreate("menu", ArrayList.class);
        digester.addObjectCreate("menu/menuItem", RuleItem.class);

        digester.addSetNext("menu/menuItem", "add");

        digester.addCallMethod("*/menuItem/url", "setUrl", 0);
        digester.addCallMethod("*/menuItem/shortPath", "setShortPath", 0);

        InputStream is = context.getResource("/WEB-INF/menu.xml").openStream();
        rules = (List<RuleItem>) digester.parse(is);

    } catch (IOException e) {
        Log.log(e.getMessage(), e);
    } catch (SAXException ex) {
        Log.log(ex.getMessage(), ex);
    }
}