Example usage for javax.servlet ServletContext getResourceAsStream

List of usage examples for javax.servlet ServletContext getResourceAsStream

Introduction

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

Prototype

public InputStream getResourceAsStream(String path);

Source Link

Document

Returns the resource located at the named path as an InputStream object.

Usage

From source file:catalina.startup.ContextConfig.java

/**
 * Process the application configuration file, if it exists.
 *//*  www.j av a2s.c  om*/
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.jboss.web.tomcat.tc4.SingleSignOnContextConfig.java

/**
 * Process the application configuration file, if it exists.
 *//*from   w w  w.j av  a2 s. com*/
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.intermine.web.struts.InitialiserPlugin.java

/**
 * Read in the webapp configuration properties
 *//* w  ww  . ja v  a2s. c o m*/
private Properties loadWebProperties(ServletContext servletContext) {
    Map<String, String> lastState = new HashMap<String, String>();
    Map<String, List<String>> origins = new TreeMap<String, List<String>>();
    Properties webProperties = new Properties();
    InputStream globalPropertiesStream = servletContext.getResourceAsStream("/WEB-INF/global.web.properties");
    try {
        webProperties.load(globalPropertiesStream);
    } catch (Exception e) {
        LOG.error("Unable to find global.web.properties", e);
        blockingErrorKeys.put("errors.init.globalweb", null);
        return webProperties;
    }
    updateOrigins(lastState, origins, "/WEB-INF/global.web.properties", webProperties);

    LOG.info("Looking for extra property files");
    Pattern pattern = Pattern.compile("/WEB-INF/(?!global)\\w+\\.web\\.properties$");
    ResourceFinder finder = new ResourceFinder(servletContext);

    Collection<String> otherResources = finder.findResourcesMatching(pattern);
    for (String resource : otherResources) {
        LOG.info("Loading extra resources from " + resource);
        InputStream otherResourceStream = servletContext.getResourceAsStream(resource);
        try {
            webProperties.load(otherResourceStream);
        } catch (Exception e) {
            LOG.error("Unable to load " + resource, e);
            blockingErrorKeys.put("errors.init.globalweb", null);
            return webProperties;
        }
        updateOrigins(lastState, origins, resource, webProperties);
    }

    // Load these last, as they always take precedence.
    InputStream modelPropertiesStream = servletContext.getResourceAsStream("/WEB-INF/web.properties");
    if (modelPropertiesStream == null) {
        // there are no model specific properties
    } else {
        try {
            webProperties.load(modelPropertiesStream);
        } catch (Exception e) {
            LOG.error("Unable to load web.properties", e);
            blockingErrorKeys.put("errors.init.webproperties", null);
            return webProperties;
        }
        updateOrigins(lastState, origins, "/WEB-INF/web.properties", webProperties);
    }
    SessionMethods.setPropertiesOrigins(servletContext, origins);
    Properties trimProperties = trimProperties(webProperties);
    SessionMethods.setWebProperties(servletContext, trimProperties);
    MainHelper.loadHelpers(trimProperties);
    return trimProperties;
}

From source file:org.sakaiproject.portal.service.SakaiPortletRegistryListener.java

public List<Tool> getRegistrationsForPortlet(PortletDD pdd, InternalPortletContext portlet,
        ServletContext portalContext) {

    String portletName = pdd.getPortletName();
    String appName = portlet.getApplicationId();

    List<Tool> toolRegs = null;

    // Check sakai.home first
    String homePath = ServerConfigurationService.getSakaiHomePath() + "/portlets/";
    String portletReg = homePath + appName + "/" + portletName + ".xml";

    File toolRegFile = new File(portletReg);
    if (!toolRegFile.canRead()) {
        portletReg = homePath + portletName + ".xml";
    }/*from w w  w . ja  va2s  .co  m*/

    // Attempt to read and parse the registration file
    toolRegs = activeToolManager.parseTools(new File(portletReg));
    if (toolRegs != null) {
        log.info("Found " + toolRegs.size() + " Tool(s) to register from=" + portletReg);
    }

    // If not there - do we have one in the webapp?
    if (toolRegs == null) {
        // See if we have a registration in the portlet itself
        String webappRegPath = "/WEB-INF/sakai/" + portletName + ".xml";
        InputStream is = portalContext.getResourceAsStream(webappRegPath);
        if (is != null) {
            toolRegs = activeToolManager.parseTools(is);
            if (toolRegs != null) {
                log.info("Found " + toolRegs.size() + " Tool(s) to register from=" + webappRegPath);
            }
        }
    }

    return toolRegs;
}

From source file:org.jaggeryjs.jaggery.core.listeners.WebAppSessionListener.java

@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    ServletContext ctx = httpSessionEvent.getSession().getServletContext();

    List<Object> jsListeners = (List<Object>) ctx.getAttribute(JaggeryCoreConstants.JS_CREATED_LISTENERS);
    if (jsListeners == null) {
        return;/* w  ww.j a v  a 2  s  .  c  o m*/
    }

    JaggeryContext shared = WebAppManager.sharedJaggeryContext(ctx);
    Context cx = shared.getEngine().enterContext();
    JaggeryContext context = CommonManager.getJaggeryContext();
    if (CommonManager.getJaggeryContext() == null) {
        context = WebAppManager.clonedJaggeryContext(ctx);
        CommonManager.setJaggeryContext(context);
    }
    RhinoEngine engine = context.getEngine();
    ScriptableObject clonedScope = context.getScope();

    JavaScriptProperty session = new JavaScriptProperty("session");
    session.setValue(cx.newObject(clonedScope, "Session", new Object[] { httpSessionEvent.getSession() }));
    session.setAttribute(ScriptableObject.READONLY);
    RhinoEngine.defineProperty(clonedScope, session);

    for (Object jsListener : jsListeners) {
        CommonManager.getCallstack(context).push((String) jsListener);
        try {
            ScriptReader sr = new ScriptReader(ctx.getResourceAsStream((String) jsListener)) {
                @Override
                protected void build() throws IOException {
                    try {
                        sourceReader = new StringReader(HostObjectUtil.streamToString(sourceIn));
                    } catch (ScriptException e) {
                        throw new IOException(e);
                    }
                }
            };
            engine.exec(sr, clonedScope, null);
        } catch (ScriptException e) {
            log.error(e.getMessage(), e);
        } finally {
            CommonManager.getCallstack(context).pop();
        }
    }
    Context.exit();
}

From source file:org.jaggeryjs.jaggery.core.listeners.WebAppSessionListener.java

@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
    ServletContext ctx = httpSessionEvent.getSession().getServletContext();

    List<Object> jsListeners = (List<Object>) ctx.getAttribute(JaggeryCoreConstants.JS_DESTROYED_LISTENERS);
    if (jsListeners == null) {
        return;/*from  w ww . jav  a  2  s .c o m*/
    }

    JaggeryContext shared = WebAppManager.sharedJaggeryContext(ctx);
    Context cx = shared.getEngine().enterContext();
    JaggeryContext context = CommonManager.getJaggeryContext();
    if (CommonManager.getJaggeryContext() == null) {
        context = WebAppManager.clonedJaggeryContext(ctx);
        CommonManager.setJaggeryContext(context);
    }
    RhinoEngine engine = context.getEngine();
    ScriptableObject clonedScope = context.getScope();

    JavaScriptProperty session = new JavaScriptProperty("session");
    session.setValue(cx.newObject(clonedScope, "Session", new Object[] { httpSessionEvent.getSession() }));
    session.setAttribute(ScriptableObject.READONLY);
    RhinoEngine.defineProperty(clonedScope, session);

    for (Object jsListener : jsListeners) {
        CommonManager.getCallstack(context).push((String) jsListener);
        try {
            ScriptReader sr = new ScriptReader(ctx.getResourceAsStream((String) jsListener)) {
                @Override
                protected void build() throws IOException {
                    try {
                        sourceReader = new StringReader(HostObjectUtil.streamToString(sourceIn));
                    } catch (ScriptException e) {
                        throw new IOException(e);
                    }
                }
            };
            engine.exec(sr, clonedScope, null);
        } catch (ScriptException e) {
            log.error(e.getMessage(), e);
        } finally {
            CommonManager.getCallstack(context).pop();
        }
    }
    Context.exit();
}

From source file:org.jbpm.designer.server.Repository.java

protected String erdfToRdf(String erdf, ServletContext context) throws TransformerException {
    String serializedDOM = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
            + "<html xmlns=\"http://www.w3.org/1999/xhtml\" " + "xmlns:b3mn=\"http://b3mn.org/2007/b3mn\" "
            + "xmlns:ext=\"http://b3mn.org/2007/ext\" "
            + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" "
            + "xmlns:atom=\"http://b3mn.org/2007/atom+xhtml\">"
            + "<head profile=\"http://purl.org/NET/erdf/profile\">"
            + "<link rel=\"schema.dc\" href=\"http://purl.org/dc/elements/1.1/\" />"
            + "<link rel=\"schema.dcTerms\" href=\"http://purl.org/dc/terms/ \" />"
            + "<link rel=\"schema.b3mn\" href=\"http://b3mn.org\" />"
            + "<link rel=\"schema.oryx\" href=\"http://oryx-editor.org/\" />"
            + "<link rel=\"schema.raziel\" href=\"http://raziel.org/\" />" + "</head><body>" + erdf
            + "</body></html>";

    InputStream xsltStream = context.getResourceAsStream("/WEB-INF/lib/extract-rdf.xsl");
    Source xsltSource = new StreamSource(xsltStream);
    Source erdfSource = new StreamSource(new StringReader(serializedDOM));

    TransformerFactory transFact = TransformerFactory.newInstance();
    Transformer trans = transFact.newTransformer(xsltSource);
    StringWriter output = new StringWriter();
    trans.transform(erdfSource, new StreamResult(output));
    return output.toString();
}

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

/**
 * Initializes preferences//from  w w w.ja  va2s.  c  o m
 *
 * @param context ServletContext
 */
public void initializePrefs(ServletContext context) {
    LOG.info("Initializing...");
    // Load the application node name, if any
    try {
        Properties instanceProperties = new Properties();
        instanceProperties.load(context.getResourceAsStream("/WEB-INF/instance.property"));
        node = instanceProperties.getProperty("node", DEFAULT_NODE);
        LOG.info("Node: " + node);
    } catch (Exception e) {
        LOG.info("Default Node: " + DEFAULT_NODE);
        node = DEFAULT_NODE;
    }
    // Determine the file library
    String fileLibrary = retrieveFileLibraryLocation(context);
    if (fileLibrary != null) {
        loadProperties(fileLibrary);
        this.add(FILE_LIBRARY_PATH, fileLibrary);
        configureDebug();
        verifyKey(context, fileLibrary);
        configureConnectionPool(context);
        configureFreemarker(context);
        configureWebdavManager(context);
        configureSystemSettings(context);
        configureCache(context);
        if (isConfigured()) {
            if (ApplicationVersion.isOutOfDate(this)) {
                LOG.info("Upgrade triggered... obtaining lock to continue");
                // Use a lock file to to start upgrading
                File upgradeLockFile = new File(fileLibrary + "upgrade.lock");
                FileChannel fileChannel = null;
                FileLock fileLock = null;
                try {
                    // Configure the file for locking
                    fileChannel = new RandomAccessFile(upgradeLockFile, "rw").getChannel();
                    // Use fileChannel.lock which blocks until the lock is obtained
                    fileLock = fileChannel.lock();
                    // Reload the prefs to make sure the upgrade isn't already complete
                    loadProperties(fileLibrary);
                    if (ApplicationVersion.isOutOfDate(this)) {
                        // The application needs an update
                        LOG.info("Installed version " + ApplicationVersion.getInstalledVersion(this)
                                + " will be upgraded to " + ApplicationVersion.VERSION);
                        performUpgrade(context);
                    }
                } catch (Exception e) {
                    LOG.error("initializePrefs-> performUpgrade", e);
                } finally {
                    try {
                        if (fileLock != null) {
                            fileLock.release();
                        }
                        if (fileChannel != null) {
                            fileChannel.close();
                        }
                    } catch (Exception eclose) {
                        LOG.error("initializePrefs-> lock", eclose);
                    }
                }
            }
            if (!ApplicationVersion.isOutOfDate(this)) {
                // Start the services now that everything is ready
                initializeServices(context);
            }
        }
    }
    configureDefaultBehavior(context);
    loadApplicationDictionaries(context);
}

From source file:org.apache.click.util.ErrorReport.java

/**
 * Create a ErrorReport instance from the given error and page.
 *
 * @param error the cause of the error//  w w  w.j av  a 2  s  .  co  m
 * @param pageClass the Page class which caused the error
 * @param isProductionMode the application is in "production" mode
 * @param request the page request
 * @param servletContext the servlet context
 */
public ErrorReport(Throwable error, Class<? extends Page> pageClass, boolean isProductionMode,
        HttpServletRequest request, ServletContext servletContext) {

    this.error = error;
    this.pageClass = pageClass;
    this.isProductionMode = isProductionMode;
    this.request = request;
    this.servletContext = servletContext;

    if (error instanceof TemplateException && ((TemplateException) error).isParseError()) {

        TemplateException te = (TemplateException) error;

        if (te.getTemplateName().charAt(0) == '/') {
            sourceName = te.getTemplateName();
        } else {
            sourceName = '/' + te.getTemplateName();
        }
        lineNumber = te.getLineNumber();
        columnNumber = te.getColumnNumber();

        InputStream is = servletContext.getResourceAsStream(sourceName);

        sourceReader = new LineNumberReader(new InputStreamReader(is));
        isParseError = true;

    } else {
        isParseError = false;
        sourceName = null;
        columnNumber = -1;

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        getCause().printStackTrace(pw);

        StringTokenizer tokenizer = new StringTokenizer(sw.toString(), "\n");

        try {
            tokenizer.nextToken();
            String line = tokenizer.nextToken();
            if (getCause() instanceof IllegalArgumentException) {
                line = tokenizer.nextToken();

                if (line.indexOf("org.apache.commons.lang.Validate") != -1) {
                    line = tokenizer.nextToken();
                }
            }

            int nameStart = line.indexOf("at ");
            int nameEnd = line.indexOf("(");
            nameEnd = line.lastIndexOf(".", nameEnd);
            if (line.indexOf("$") != -1) {
                nameEnd = line.indexOf("$");
            }

            if (nameStart != -1 && nameEnd != -1) {
                String classname = line.substring(nameStart + 3, nameEnd);

                int lineStart = line.indexOf(":");
                if (lineStart != -1) {
                    int lineEnd = line.indexOf(")");
                    String lineNumber = line.substring(lineStart + 1, lineEnd);

                    this.lineNumber = Integer.parseInt(lineNumber);

                    String filename = "/" + classname.replace('.', '/') + ".java";

                    sourceReader = getJavaSourceReader(filename);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.liferay.portal.plugin.PluginPackageUtil.java

private PluginPackage _readPluginPackageServletManifest(ServletContext servletContext) throws IOException {
    Attributes attributes = null;

    String servletContextName = servletContext.getServletContextName();

    InputStream inputStream = servletContext.getResourceAsStream("/META-INF/MANIFEST.MF");

    if (inputStream != null) {
        Manifest manifest = new Manifest(inputStream);

        attributes = manifest.getMainAttributes();
    } else {//from w  ww .  ja  va 2  s  .  c o m
        attributes = new Attributes();
    }

    String artifactGroupId = attributes.getValue("Implementation-Vendor-Id");

    if (Validator.isNull(artifactGroupId)) {
        artifactGroupId = attributes.getValue("Implementation-Vendor");
    }

    if (Validator.isNull(artifactGroupId)) {
        artifactGroupId = GetterUtil.getString(attributes.getValue("Bundle-Vendor"), servletContextName);
    }

    String artifactId = attributes.getValue("Implementation-Title");

    if (Validator.isNull(artifactId)) {
        artifactId = GetterUtil.getString(attributes.getValue("Bundle-Name"), servletContextName);
    }

    String version = attributes.getValue("Implementation-Version");

    if (Validator.isNull(version)) {
        version = GetterUtil.getString(attributes.getValue("Bundle-Version"), Version.UNKNOWN);
    }

    if (version.equals(Version.UNKNOWN) && _log.isWarnEnabled()) {
        _log.warn("Plugin package on context " + servletContextName
                + " cannot be tracked because this WAR does not contain a "
                + "liferay-plugin-package.xml file");
    }

    PluginPackage pluginPackage = new PluginPackageImpl(artifactGroupId + StringPool.SLASH + artifactId
            + StringPool.SLASH + version + StringPool.SLASH + "war");

    pluginPackage.setName(artifactId);

    String shortDescription = attributes.getValue("Bundle-Description");

    if (Validator.isNotNull(shortDescription)) {
        pluginPackage.setShortDescription(shortDescription);
    }

    String pageURL = attributes.getValue("Bundle-DocURL");

    if (Validator.isNotNull(pageURL)) {
        pluginPackage.setPageURL(pageURL);
    }

    return pluginPackage;
}