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:net.ontopia.topicmaps.nav2.taglibs.TMvalue.TologQueryTag.java

@Override
public Collection process(Collection tmObjects) throws JspException {
    if (query == null)
        throw new NavigatorCompileException("TologQueryTag: Ambiguous attribute " + "settings.");

    // try to retrieve default value from ContextManager
    ContextTag contextTag = FrameworkUtils.getContextTag(pageContext);

    // Get the ContextManager
    ContextManagerIF ctxtMgr = contextTag.getContextManager();

    // Create a map for the context
    Map argmap = new ContextManagerMapWrapper(ctxtMgr);

    // get topicmap object on which we should compute 
    TopicMapIF topicmap = contextTag.getTopicMap();
    if (topicmap == null)
        throw new NavigatorRuntimeException("TologQueryTag found no topic map.");

    // Get the result from the QueryProcessor
    QueryProcessorIF q_processor = (implementation == null ? QueryUtils.createQueryProcessor(topicmap)
            : QueryUtils.createQueryProcessor(topicmap, Collections
                    .singletonMap("net.ontopia.topicmaps.query.core.QueryProcessorIF", implementation)));

    if (rulesfile != null) {
        ServletContext ctxt = pageContext.getServletContext();
        try {//from  www.j  ava 2  s.  c  o  m
            q_processor.load(new InputStreamReader(ctxt.getResourceAsStream(rulesfile)));
        } catch (IOException e) {
            throw JSPEngineWrapper.getJspException("Problem loading tolog rules file: " + rulesfile, e);
        } catch (InvalidQueryException e) {
            throw JSPEngineWrapper.getJspException("Problem loading tolog rules file: " + rulesfile, e);
        }
    }

    try {
        // produce list of maps
        return getMapCollection(q_processor.execute(query, argmap));
    } catch (InvalidQueryException e) {
        log.debug("Parsing of query '" + query + "' failed with message: " + e);
        throw new NavigatorRuntimeException(e);
    }
}

From source file:org.hyperic.hq.ui.Configurator.java

/**
 * Load the specified properties file and return the properties.
 *
 * @param ctx the <code>ServletContext</code>
 * @param filename the fully qualifed name of the properties file
 * @exception Exception if a problem occurs while loading the file
 *//*from   w  ww  . ja va 2  s .com*/
private Properties loadProperties(ServletContext ctx, String filename) throws Exception {
    Properties props = new Properties();
    InputStream is = ctx.getResourceAsStream(filename);
    if (is != null) {
        props.load(is);
        is.close();
    }

    return props;
}

From source file:com.aimluck.eip.services.social.gadgets.ALGadgetContext.java

protected BlobCrypter loadCrypterFromFile(RunData rundata) throws IOException {
    BufferedReader reader = null;
    byte[] keyBytes = null;
    try {/* w ww .j a  va 2 s. com*/
        ServletContext servletContext = ((JetspeedRunData) rundata).getServletContext();
        InputStream resourceAsStream = servletContext.getResourceAsStream("/WEB-INF/conf/securityTokenKey.txt");
        reader = new BufferedReader(new InputStreamReader(resourceAsStream, Charsets.UTF_8));
        String line = reader.readLine();
        if (line == null) {
            throw new IOException("Unexpectedly empty keyfile: " + SECURITY_TOKEN_KEY);
        }
        line = line.trim();
        keyBytes = CharsetUtil.getUtf8Bytes(line);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            // oh well.
        }
    }
    return new BasicBlobCrypter(keyBytes);
}

From source file:com.liangc.hq.base.web.ConfiguratorListener.java

/**
 * Load the specified properties file and return the properties.
 *
 * @param ctx the <code>ServletContext</code>
 * @param filename the fully qualifed name of the properties file
 * @exception Exception if a problem occurs while loading the file
 *//*  w  w  w  . j a  va 2 s  . c  o m*/
private Properties loadProperties(ServletContext ctx, String filename) throws Exception {
    Properties props = new Properties();
    InputStream is = ctx.getResourceAsStream(filename);
    if (is == null) {
        filename = filename.substring(filename.lastIndexOf("/"));
        is = this.getClass().getResourceAsStream(filename);
    }
    if (is != null) {
        props.load(is);
        is.close();
    }

    return props;
}

From source file:org.openflamingo.web.util.VersionConfigurer.java

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    Log4jWebConfigurer.initLogging(servletContextEvent.getServletContext());

    Properties properties = new Properties();
    ServletContext context = servletContextEvent.getServletContext();
    InputStream inputStream = null;
    try {/*from w w w . ja  va 2s  . co m*/
        inputStream = context.getResourceAsStream("/WEB-INF/version.properties");
        properties.load(inputStream);
    } catch (Exception ex) {
        throw new IllegalArgumentException("Cannot load a '/WEB/INF/version.properties' file.", ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }

    StringBuilder builder = new StringBuilder();

    printHeader(builder, "Application Information");
    Properties appProps = new Properties();
    appProps.put("Application", "Flamingo Workflow Engine");
    appProps.put("Version", properties.get("version"));
    appProps.put("Build Date", properties.get("build.timestamp"));
    appProps.put("Build Number", properties.get("build.number"));
    appProps.put("Revision Number", properties.get("revision.number"));
    appProps.put("Build Key", properties.get("build.key"));

    if (context != null) {
        appProps.put("Application Server", context.getServerInfo() + " - Servlet API "
                + context.getMajorVersion() + "." + context.getMinorVersion());
    }

    Properties systemProperties = System.getProperties();
    appProps.put("Java Version", systemProperties.getProperty("java.version", UNKNOWN) + " - "
            + systemProperties.getProperty("java.vendor", UNKNOWN));
    appProps.put("Current Working Directory", systemProperties.getProperty("user.dir", UNKNOWN));

    print(builder, appProps);

    Properties memPros = new Properties();
    final Runtime rt = Runtime.getRuntime();
    final long maxMemory = rt.maxMemory() / MEGA_BYTES;
    final long totalMemory = rt.totalMemory() / MEGA_BYTES;
    final long freeMemory = rt.freeMemory() / MEGA_BYTES;
    final long usedMemory = totalMemory - freeMemory;

    memPros.put("Maximum Allowable Memory", maxMemory + "MB");
    memPros.put("Total Memory", totalMemory + "MB");
    memPros.put("Free Memory", freeMemory + "MB");
    memPros.put("Used Memory", usedMemory + "MB");

    print(builder, memPros);

    printHeader(builder, "Java System Properties");
    Properties sysProps = new Properties();
    for (final Map.Entry<Object, Object> entry : systemProperties.entrySet()) {
        sysProps.put(entry.getKey(), entry.getValue());
    }

    print(builder, sysProps);

    printHeader(builder, "System Environments");
    Map<String, String> getenv = System.getenv();
    Properties envProps = new Properties();
    Set<String> strings = getenv.keySet();
    for (String key : strings) {
        String message = getenv.get(key);
        envProps.put(key, message);
    }

    print(builder, envProps);

    logger.info("=================================================");
    logger.info(" Flamingo Web Services starting...");
    logger.info("=================================================\n{}", builder.toString());
}

From source file:org.pepstock.jem.gwt.server.listeners.StartUp.java

/**
 * Set the jem Version// w w w  . j  a v  a  2s  .  c o  m
 * 
 * @param contextPath
 */
private void setJemVersion(ServletContext context) {
    // reads manifest file for searching version of JEM
    InputStream fis = null;
    try {
        fis = context.getResourceAsStream(MANIFEST_FILE);
        if (fis == null) {
            throw new FileNotFoundException(MANIFEST_FILE);
        }
        Manifest manifest = new Manifest(fis);
        // gets JEM vrsion
        Attributes at = manifest.getAttributes(ConfigKeys.JEM_MANIFEST_SECTION);
        String jemVersion = at.getValue(ConfigKeys.JEM_MANIFEST_VERSION);
        // saves JEM version
        if (jemVersion != null) {
            SharedObjects.getInstance().setJemVersion(jemVersion);
        }
    } catch (FileNotFoundException e) {
        // to ignore stack trace
        LogAppl.getInstance().ignore(e.getMessage(), e);
        LogAppl.getInstance().emit(NodeMessage.JEMC184W);
    } catch (IOException e) {
        // to ignore stack trace
        LogAppl.getInstance().ignore(e.getMessage(), e);
        LogAppl.getInstance().emit(NodeMessage.JEMC184W);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (Exception e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }

}

From source file:org.seasar.s2click.example.page.SourceViewerPage.java

private void loadFilename(String filename) {
    ServletContext context = getContext().getServletContext();

    // Orion server requires '/' prefix to find resources
    String resourceFilename = (filename.charAt(0) != '/') ? "/" + filename : filename;

    InputStream in = null;/*from   w w w .j a  v a2 s  .co  m*/
    try {
        in = context.getResourceAsStream(resourceFilename);

        if (in == null && filename.endsWith(".htm")) {
            resourceFilename = resourceFilename.substring(0, resourceFilename.length() - 4) + ".jsp";

            in = context.getResourceAsStream(resourceFilename);
        }

        if (in != null) {
            String lang = filename.endsWith(".java") ? CodePrettify.LANG_JAVA : CodePrettify.LANG_HTML;

            String code = IOUtils.toString(in, "UTF-8");
            CodePrettify codePrettify = new CodePrettify("codePrettify");
            codePrettify.setCode(code);
            codePrettify.setLang(lang);
            addControl(codePrettify);

        } else {
            addModel("error", "File " + resourceFilename + " not found");
        }

    } catch (IOException e) {
        addModel("error", "Could not read " + resourceFilename);

    } finally {
        ClickUtils.close(in);
    }
}

From source file:wicket.protocol.http.request.WebExternalResourceRequestTarget.java

/**
 * Respond by trying to delegate getting the resource from the
 * {@link ServletContext} object and stream that to the client. If such a
 * resource is not found, a warning will be logged, and a 404 will be
 * issued.//from  www .j  a va 2s .com
 * 
 * @see wicket.IRequestTarget#respond(wicket.RequestCycle)
 */
public void respond(RequestCycle requestCycle) {
    try {
        WebResponse webResponse = ((WebRequestCycle) requestCycle).getWebResponse();
        final ServletContext context = ((WebApplication) requestCycle.getApplication()).getServletContext();

        // Set content type
        webResponse.setContentType(context.getMimeType(url));
        final InputStream in = context.getResourceAsStream(url);
        if (in != null) {
            try {
                // Copy resource input stream to servlet output stream
                Streams.copy(in, webResponse.getHttpServletResponse().getOutputStream());
            } finally {
                // NOTE: We only close the InputStream. The servlet
                // container should close the output stream.
                in.close();
            }
        } else {
            log.warn("the resource requested by request " + requestCycle.getRequest() + " was not found");
            HttpServletResponse httpServletResponse = webResponse.getHttpServletResponse();
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (IOException e) {
        throw new WicketRuntimeException("Cannot load static content for request " + requestCycle.getRequest(),
                e);
    }
}

From source file:org.exem.flamingo.web.util.ApplicationInformationDisplayContextListener.java

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    System.setProperty("PID", SystemUtils.getPid());

    Properties properties = new Properties();
    ServletContext context = servletContextEvent.getServletContext();
    InputStream inputStream = null;
    try {/*from   w  w w .j a va 2 s .com*/
        inputStream = context.getResourceAsStream("/WEB-INF/app.properties");
        properties.load(inputStream);
    } catch (Exception ex) {
        throw new IllegalArgumentException("Cannot load a '/WEB/INF/app.properties' file.", ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }

    // See : http://patorjk.com/software/taag/#p=display&f=Slant&t=Flamingo
    StringBuilder builder = new StringBuilder();
    builder.append("    ________                _                 \n"
            + "   / ____/ /___ _____ ___  (_)___  ____ _____ \n"
            + "  / /_  / / __ `/ __ `__ \\/ / __ \\/ __ `/ __ \\\n"
            + " / __/ / / /_/ / / / / / / / / / / /_/ / /_/ /\n"
            + "/_/   /_/\\__,_/_/ /_/ /_/_/_/ /_/\\__, /\\____/ \n"
            + "                                /____/        ");

    printHeader(builder, "Application Information");
    Properties appProps = new Properties();
    appProps.put("Instance", StringUtils.isEmpty(System.getProperty("instance")) ? "** UNKNOWN **"
            : System.getProperty("instance"));
    appProps.put("Version", properties.get("version"));
    appProps.put("Build Date", properties.get("build.timestamp"));
    appProps.put("Build Number", properties.get("build.number"));
    appProps.put("Revision Number", properties.get("revision.number"));
    appProps.put("Organization", properties.get("organization"));
    appProps.put("Homepage", properties.get("homepage"));

    if (context != null) {
        appProps.put("Application Server", context.getServerInfo() + " - Servlet API "
                + context.getMajorVersion() + "." + context.getMinorVersion());
    }

    Properties systemProperties = System.getProperties();
    appProps.put("Java Version", systemProperties.getProperty("java.version", UNKNOWN) + " - "
            + systemProperties.getProperty("java.vendor", UNKNOWN));
    appProps.put("Current Working Directory", systemProperties.getProperty("user.dir", UNKNOWN));

    print(builder, appProps);

    Properties memPros = new Properties();
    final Runtime rt = Runtime.getRuntime();
    final long maxMemory = rt.maxMemory() / MEGA_BYTES;
    final long totalMemory = rt.totalMemory() / MEGA_BYTES;
    final long freeMemory = rt.freeMemory() / MEGA_BYTES;
    final long usedMemory = totalMemory - freeMemory;

    memPros.put("Maximum Allowable Memory", maxMemory + "MB");
    memPros.put("Total Memory", totalMemory + "MB");
    memPros.put("Free Memory", freeMemory + "MB");
    memPros.put("Used Memory", usedMemory + "MB");

    print(builder, memPros);

    printHeader(builder, "Java System Properties");
    Properties sysProps = new Properties();
    for (final Map.Entry<Object, Object> entry : systemProperties.entrySet()) {
        sysProps.put(entry.getKey(), entry.getValue());
    }

    print(builder, sysProps);

    printHeader(builder, "System Environments");
    Map<String, String> envs = System.getenv();
    Properties envProps = new Properties();
    Set<String> strings = envs.keySet();
    for (String key : strings) {
        String message = envs.get(key);
        envProps.put(key, message);
    }

    print(builder, envProps);

    WebLogbackConfigurer.initLogging(servletContextEvent.getServletContext());

    System.out.println(builder.toString());

    logger.info("============================================================");
    logger.info(" Now starting ..... PID: " + SystemUtils.getPid());
    logger.info("============================================================");
}

From source file:com.videobox.web.util.dwr.AutoAnnotationDiscoveryContainer.java

private StringBuilder scanContextPath(ServletContext ctx, StringBuilder sb, String pathName)
        throws IOException {
    if (pathName.endsWith(".class")) {
        InputStream istream = ctx.getResourceAsStream(pathName);
        handleClass(istream, sb);// www . j  a v a2  s  .  c om
    } else if (pathName.endsWith("/")) {
        // log.info( "PATH: " + pathName );
        Set<String> set = ctx.getResourcePaths(pathName);
        for (String className : set) {
            sb = scanContextPath(ctx, sb, className);
        }
    }
    Converter c = null;
    return sb;
}