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:org.intermine.web.logic.config.WebConfig.java

/**
 * Parse a WebConfig XML file// w  w  w .j  ava  2s  . co m
 *
 * @param context The servlet context we are in.
 * @param model the Model to use when reading - used for checking class names and for finding
 * sub and super classes
 * @return a WebConfig object
 * @throws SAXException if there is an error in the XML file
 * @throws IOException if there is an error reading the XML file
 * @throws ClassNotFoundException if a class is mentioned in the XML that isn't in the model
 */
public static WebConfig parse(final ServletContext context, final Model model)
        throws IOException, SAXException, ClassNotFoundException {

    BasicConfigurator.configure();

    final InputStream webconfXML = context.getResourceAsStream("/WEB-INF/webconfig-model.xml");
    if (webconfXML == null) {
        throw new FileNotFoundException("Could not find webconfig-model.xml");
    }

    final Digester digester = new Digester();
    digester.setValidating(false);

    digester.addObjectCreate("webconfig", WebConfig.class);

    digester.addObjectCreate("webconfig/class", Type.class);
    digester.addSetProperties("webconfig/class", "className", "className");
    digester.addSetProperties("webconfig/class", "fieldName", "fieldName");

    /* configure how the "title" of an object is displayed on Type */
    digester.addObjectCreate("webconfig/class/headerconfig/titles", HeaderConfigTitle.class);
    digester.addSetProperties("webconfig/class/headerconfig/titles/title", "mainTitles", "mainTitles");
    digester.addSetProperties("webconfig/class/headerconfig/titles/title", "subTitles", "subTitles");
    digester.addSetProperties("webconfig/class/headerconfig/titles/title", "numberOfMainTitlesToShow",
            "numberOfMainTitlesToShow");
    digester.addSetProperties("webconfig/class/headerconfig/titles/title", "appendConfig", "appendConfig");
    digester.addSetNext("webconfig/class/headerconfig/titles", "addHeaderConfigTitle");

    digester.addObjectCreate("webconfig/class/headerconfig/customlinks", HeaderConfigLink.class);
    digester.addSetProperties("webconfig/class/headerconfig/customlinks/customlink", "url", "url");
    digester.addSetProperties("webconfig/class/headerconfig/customlinks/customlink", "text", "text");
    digester.addSetProperties("webconfig/class/headerconfig/customlinks/customlink", "image", "image");
    digester.addSetNext("webconfig/class/headerconfig/customlinks", "addHeaderConfigLink");

    digester.addObjectCreate("webconfig/class/tabledisplayer", Displayer.class);
    digester.addSetProperties("webconfig/class/tabledisplayer", "src", "src");
    digester.addSetNext("webconfig/class/tabledisplayer", "setTableDisplayer");

    digester.addCallMethod("webconfig/class/tabledisplayer/param", "addParam", 2);
    digester.addCallParam("webconfig/class/tabledisplayer/param", 0, "name");
    digester.addCallParam("webconfig/class/tabledisplayer/param", 1, "value");

    digester.addObjectCreate("webconfig/class/fields/fieldconfig", FieldConfig.class);
    digester.addSetProperties("webconfig/class/fields/fieldconfig", "fieldExpr", "fieldExpr");
    digester.addSetProperties("webconfig/class/fields/fieldconfig", "name", "name");
    digester.addSetProperties("webconfig/class/fields/fieldconfig", "displayer", "displayer");
    digester.addSetProperties("webconfig/class/fields/fieldconfig", "showInListAnalysisPreviewTable",
            "showInListAnalysisPreviewTable");
    digester.addSetNext("webconfig/class/fields/fieldconfig", "addFieldConfig");

    digester.addObjectCreate("webconfig/class/longdisplayers/displayer", Displayer.class);
    digester.addSetProperties("webconfig/class/longdisplayers/displayer");
    digester.addSetNext("webconfig/class/longdisplayers/displayer", "addLongDisplayer");

    digester.addCallMethod("webconfig/class/longdisplayers/displayer/param", "addParam", 2);
    digester.addCallParam("webconfig/class/longdisplayers/displayer/param", 0, "name");
    digester.addCallParam("webconfig/class/longdisplayers/displayer/param", 1, "value");

    /* display inline tables as inline lists instead */
    digester.addObjectCreate("webconfig/class/inlinelist/table", InlineListConfig.class);
    digester.addSetProperties("webconfig/class/inlinelist/table");
    digester.addSetNext("webconfig/class/inlinelist/table", "addInlineList");
    digester.addSetProperties("webconfig/class/inlinelist/table", "path", "path");
    digester.addSetProperties("webconfig/class/inlinelist/table", "showLinksToObjects", "showLinksToObjects");
    digester.addSetProperties("webconfig/class/inlinelist/table", "showInHeader", "showInHeader");
    digester.addSetProperties("webconfig/class/inlinelist/table", "lineLength", "lineLength");

    digester.addObjectCreate("webconfig/class/bagdisplayers/displayer", Displayer.class);
    digester.addSetProperties("webconfig/class/bagdisplayers/displayer");
    digester.addSetNext("webconfig/class/bagdisplayers/displayer", "addBagDisplayer");

    digester.addCallMethod("webconfig/class/bagdisplayers/displayer/param", "addParam", 2);
    digester.addCallParam("webconfig/class/bagdisplayers/displayer/param", 0, "name");
    digester.addCallParam("webconfig/class/bagdisplayers/displayer/param", 1, "value");

    digester.addObjectCreate("webconfig/widgets/graphdisplayer", GraphWidgetConfig.class);
    digester.addSetProperties("webconfig/widgets/graphdisplayer");
    digester.addSetNext("webconfig/widgets/graphdisplayer", "addWidget");

    digester.addObjectCreate("webconfig/widgets/enrichmentwidgetdisplayer", EnrichmentWidgetConfig.class);
    digester.addSetProperties("webconfig/widgets/enrichmentwidgetdisplayer");
    digester.addSetNext("webconfig/widgets/enrichmentwidgetdisplayer", "addWidget");

    digester.addObjectCreate("webconfig/widgets/bagtabledisplayer", TableWidgetConfig.class);
    digester.addSetProperties("webconfig/widgets/bagtabledisplayer");
    digester.addSetNext("webconfig/widgets/bagtabledisplayer", "addWidget");

    digester.addObjectCreate("webconfig/widgets/htmldisplayer", HTMLWidgetConfig.class);
    digester.addSetProperties("webconfig/widgets/htmldisplayer");
    digester.addSetNext("webconfig/widgets/htmldisplayer", "addWidget");

    digester.addSetNext("webconfig/class", "addType");

    digester.addObjectCreate("webconfig/tableExportConfig", TableExportConfig.class);
    digester.addSetProperties("webconfig/tableExportConfig", "id", "id");
    digester.addSetProperties("webconfig/tableExportConfig", "className", "className");

    digester.addSetNext("webconfig/tableExportConfig", "addTableExportConfig");

    digester.addObjectCreate("webconfig/reportdisplayers/reportdisplayer", ReportDisplayerConfig.class);
    digester.addSetProperties("webconfig/reportdisplayers/reportdisplayer");
    digester.addSetNext("webconfig/reportdisplayers/reportdisplayer", "addReportDisplayer");

    final WebConfig webConfig = (WebConfig) digester.parse(webconfXML);

    webConfig.validate(model);

    webConfig.setSubClassConfig(model);

    webConfig.loadLabelsFromMappingsFile(context, model);

    return webConfig;
}

From source file:org.ejbca.ui.web.RequestHelper.java

/**
 * Reads template and inserts cert to send back to IE for installation of cert
 *
 * @param b64cert cert to be installed in IE-client
 * @param out utput stream to send to/*from  ww w  . j ava2  s. c  o m*/
 * @param sc serveltcontext
 * @param responseTemplate path to responseTemplate
 * @param classid replace
 *
 * @throws Exception on error
 */
public static void sendNewCertToIEClient(byte[] b64cert, OutputStream out, ServletContext sc,
        String responseTemplate, String classid) throws Exception {
    if (b64cert.length == 0) {
        log.error("0 length certificate can not be sent to IE client!");
        return;
    }

    PrintStream ps = new PrintStream(out);
    if (log.isDebugEnabled()) {
        log.debug("Response template is: " + responseTemplate);
    }
    InputStream is = sc.getResourceAsStream(responseTemplate);
    if (is == null) {
        // Some app servers (oracle) require a / first...
        if (log.isDebugEnabled()) {
            log.debug("Trying to read responseTemplate with / first");
        }
        is = sc.getResourceAsStream("/" + responseTemplate);
    }
    if (is == null) {
        throw new IOException("Template '(/)" + responseTemplate + "' can not be found or read.");
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    while (true) {
        String line = br.readLine();

        if (line == null) {
            break;
        }

        if (line.indexOf("cert =") < 0) {
            ps.println(CLASSID.matcher(line).replaceFirst(classid));
        } else {
            RequestHelper.ieCertFormat(b64cert, ps);
        }
    }

    ps.close();
    if (log.isDebugEnabled()) {
        log.debug("Sent reply to IE client");
        log.debug(new String(b64cert));
    }
}

From source file:org.apache.velocity.tools.view.servlet.ServletToolboxManager.java

/**
 * ServletToolboxManager factory method.
 * This method will ensure there is exactly one ServletToolboxManager
 * per xml toolbox configuration file.//from   w  ww .jav  a  2s  .co m
 */
public static synchronized ServletToolboxManager getInstance(ServletContext servletContext,
        String toolboxFile) {
    // little fix up
    if (!toolboxFile.startsWith("/")) {
        toolboxFile = "/" + toolboxFile;
    }

    // get config file pathname
    String pathname = servletContext.getRealPath(toolboxFile);

    // check if a previous instance exists
    ServletToolboxManager toolboxManager = (ServletToolboxManager) managersMap.get(pathname);

    if (toolboxManager == null) {
        // if not, build one
        InputStream is = null;
        try {
            // get the bits
            is = servletContext.getResourceAsStream(toolboxFile);

            if (is != null) {
                LOG.info("Using config file '" + toolboxFile + "'");

                toolboxManager = new ServletToolboxManager(servletContext);
                toolboxManager.load(is);

                // remember it
                managersMap.put(pathname, toolboxManager);

                LOG.info("Toolbox setup complete.");
            }
        } catch (Exception e) {
            LOG.error("Problem loading toolbox '" + toolboxFile + "' : " + e);

            // if this happens, it probably deserves
            // to have the stack trace logged
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            LOG.error(sw.toString());
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Exception ee) {
            }
        }
    }
    return toolboxManager;
}

From source file:org.seasar.velocity.tools.S2ServletToolboxManager.java

/**
 * ServletToolboxManager factory method.
 * This method will ensure there is exactly one ServletToolboxManager
 * per xml toolbox configuration file.//from w w w.  j a v  a2 s . com
 */
public static synchronized S2ServletToolboxManager getInstance(ServletContext servletContext,
        String toolboxFile) {
    // little fix up
    if (!toolboxFile.startsWith("/")) {
        toolboxFile = "/" + toolboxFile;
    }

    // get the unique key for this toolbox file in this servlet context
    String uniqueKey = servletContext.hashCode() + ':' + toolboxFile;

    // check if a previous instance exists
    S2ServletToolboxManager toolboxManager = (S2ServletToolboxManager) managersMap.get(uniqueKey);

    if (toolboxManager == null) {
        // if not, build one
        InputStream is = null;
        try {
            // get the bits
            is = servletContext.getResourceAsStream(toolboxFile);

            if (is != null) {
                LOG.info("Using config file '" + toolboxFile + "'");

                toolboxManager = new S2ServletToolboxManager(servletContext);
                toolboxManager.load(is);

                // remember it
                managersMap.put(uniqueKey, toolboxManager);

                LOG.debug("Toolbox setup complete.");
            } else {
                LOG.debug("No toolbox was found at '" + toolboxFile + "'");
            }
        } catch (Exception e) {
            LOG.error("Problem loading toolbox '" + toolboxFile + "'", e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Exception ee) {
            }
        }
    }
    return toolboxManager;
}

From source file:org.intermine.web.logic.config.WebConfig.java

/**
 * Load a set of files into a single merged properties file. These files should all be
 * located in the WEB-INF directory of the webapp war.
 *
 * @param fileNames The file names to load.
 * @throws FileNotFoundException If a file is listed but does not exist in WEB-INF.
 * @throws IllegalStateException If two files configure the same key.
 * @throws IOException if the properties cannot be loaded.
 *//*from   w w w.j  a  va2s .  c  o  m*/
private static Properties loadMergedProperties(final List<String> fileNames, final ServletContext context)
        throws IOException {
    final Properties props = new Properties();
    for (final String fileName : fileNames) {
        LOG.info("Loading properties from " + fileName);
        final Properties theseProps = new Properties();
        final InputStream is = context.getResourceAsStream("/WEB-INF/" + fileName);
        if (is == null) {
            throw new FileNotFoundException("Could not find mappings file: " + fileName);
        }
        try {
            theseProps.load(is);
        } catch (final IOException e) {
            throw new Error("Problem reading from " + fileName, e);
        }
        if (!props.isEmpty()) {
            for (@SuppressWarnings("rawtypes")
            final Enumeration e = props.propertyNames(); e.hasMoreElements();) {
                final String key = (String) e.nextElement();
                if (theseProps.containsKey(key)) {
                    throw new IllegalStateException("Duplicate label found for " + key + " in " + fileName);
                }
            }
        }
        if (theseProps.isEmpty()) {
            LOG.info("No properties loaded from " + fileName);
        } else {
            LOG.info("Merging in " + theseProps.size() + " mappings from " + fileName);
            props.putAll(theseProps);
        }
    }
    return props;
}

From source file:com.sonymobile.backlogtool.ApplicationVersion.java

@Autowired
public ApplicationVersion(ServletContext context) throws IOException {
    InputStream in = context.getResourceAsStream("META-INF/maven/com.sonymobile/backlogtool/pom.properties");
    Properties props = new Properties();
    props.load(in);/*www  .j av a  2  s  .  com*/
    version = (String) props.get("version");
}

From source file:org.apache.pluto.driver.services.impl.resource.PropertyConfigServiceImpl.java

/**
 * Initialization Lifecycle Method/* w w w.j a v a2  s . c  om*/
 * @param ctx
 */
public void init(ServletContext ctx) {
    try {
        InputStream in = ctx.getResourceAsStream(ResourceConfigReader.CONFIG_FILE);
        config = ResourceConfigReader.getFactory().parse(in);
    } catch (Exception e) {
        LOG.error("Unable to parse resource config " + e.getMessage(), e);
        throw new DriverConfigurationException(e);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.application.BuildProperties.java

public BuildProperties(ServletContext ctx) {
    Map<String, String> map = new HashMap<>();

    try (InputStream stream = ctx.getResourceAsStream(WEBAPP_PATH_BUILD_PROPERTIES)) {
        if (stream == null) {
            log.debug("Didn't find a resource at '" + WEBAPP_PATH_BUILD_PROPERTIES + "'.");
        } else {//from w  w  w  .j av  a  2 s.  c o  m
            Properties props = new Properties();
            props.load(stream);
            for (String key : props.stringPropertyNames()) {
                map.put(key, props.getProperty(key));
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to load from '" + WEBAPP_PATH_BUILD_PROPERTIES + "'.", e);
    }
    propertyMap = Collections.unmodifiableMap(map);
}

From source file:org.openlegacy.mvc.ViewSourceController.java

@RequestMapping(method = RequestMethod.GET)
public void viewSource(@RequestParam("file") String file, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    if (!enabled) {
        throw (new OpenLegacyRuntimeException("View source controller is not enabled"));
    }//from  w  w w.  j  a  va  2  s  . c o  m

    ServletContext servletContext = request.getSession().getServletContext();

    InputStream resource = servletContext.getResourceAsStream(file);
    if (resource == null) {
        throw (new OpenLegacyRuntimeException("Specified resource doesn''t exists"));
    }
    String content = IOUtils.toString(resource);
    content = HtmlUtils.htmlEscape(content);
    response.getWriter().write(MessageFormat.format(htmlOutput, content));
}

From source file:org.energyos.espi.datacustodian.web.VersionRESTController.java

/**
 * Handling GET request to retrieve details from MANIFEST.MF file
 * // w w w  .  jav a  2 s. co m
 * @return implementation details
 */
@RequestMapping(value = "/about-version", method = RequestMethod.GET)
public String getBuildNumber(HttpServletRequest request, ModelMap model) throws IOException {

    ServletContext context = request.getSession().getServletContext();
    InputStream manifestStream = context.getResourceAsStream("/META-INF/MANIFEST.MF");
    Manifest manifest = new Manifest(manifestStream);

    Map<String, String> aboutInfo = new HashMap<>();
    aboutInfo.put("Implementation-Vendor", manifest.getMainAttributes().getValue("Implementation-Vendor"));
    aboutInfo.put("Implementation-Title", manifest.getMainAttributes().getValue("Implementation-Title"));
    aboutInfo.put("Implementation-Version", manifest.getMainAttributes().getValue("Implementation-Version"));
    aboutInfo.put("Implementation-Jdk", manifest.getMainAttributes().getValue("Build-Jdk"));
    aboutInfo.put("Implementation-Build", manifest.getMainAttributes().getValue("Implementation-Build"));
    aboutInfo.put("Implementation-Build-Time",
            manifest.getMainAttributes().getValue("Implementation-Build-Time"));

    model.put("aboutInfo", aboutInfo);
    return "/about";

}