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:helma.servlet.AbstractServletClient.java

/**
 * Forward the request to a static file. The file must be reachable via
 * the context's protectedStatic resource base.
 */// w  ww. j  av  a  2  s .  co m
void sendForward(HttpServletResponse res, HttpServletRequest req, ResponseTrans hopres) throws IOException {
    String forward = hopres.getForward();
    // Jetty 5.1 bails at forward paths without leading slash, so fix it
    if (!forward.startsWith("/")) {
        forward = "/" + forward;
    }
    ServletContext cx = getServletConfig().getServletContext();
    String path = cx.getRealPath(forward);
    if (path == null) {
        throw new IOException("Resource " + forward + " not found");
    }

    File file = new File(path);
    // check if the client has an up-to-date copy so we can
    // send a not-modified response
    if (checkNotModified(file, req, res)) {
        res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    int length = (int) file.length();
    res.setContentLength(length);
    res.setContentType(hopres.getContentType());

    InputStream in = cx.getResourceAsStream(forward);
    if (in == null) {
        throw new IOException("Can't read " + path);
    }
    try {
        OutputStream out = res.getOutputStream();

        int bufferSize = 4096;
        byte buffer[] = new byte[bufferSize];
        int l;

        while (length > 0) {
            if (length < bufferSize) {
                l = in.read(buffer, 0, length);
            } else {
                l = in.read(buffer, 0, bufferSize);
            }
            if (l == -1) {
                break;
            }

            length -= l;
            out.write(buffer, 0, l);
        }
    } finally {
        in.close();
    }
}

From source file:org.amplafi.jawr.maven.JawrMojo.java

private void setupJawrConfig(ServletConfig config, ServletContext context, final Map<String, Object> attributes,
        final Response respData) {
    expect(config.getServletContext()).andReturn(context).anyTimes();
    expect(config.getServletName()).andReturn("maven-jawr-plugin").anyTimes();

    context.log(isA(String.class));
    expectLastCall().anyTimes();/*from w  w w  .  j a v a 2 s .  c om*/

    expect(context.getResourcePaths(isA(String.class))).andAnswer(new IAnswer<Set>() {

        public Set<String> answer() throws Throwable {
            final Set<String> set = new HashSet<String>();

            // hack to disallow orphan bundles
            Exception e = new Exception();
            for (StackTraceElement trace : e.getStackTrace()) {
                if (trace.getClassName().endsWith("OrphanResourceBundlesMapper")) {
                    return set;
                }
            }

            String path = (String) EasyMock.getCurrentArguments()[0];
            File file = new File(getRootPath() + path);

            if (file.exists() && file.isDirectory()) {
                for (String one : file.list()) {
                    set.add(path + one);
                }
            }

            return set;
        }

    }).anyTimes();

    expect(context.getResourceAsStream(isA(String.class))).andAnswer(new IAnswer<InputStream>() {

        public InputStream answer() throws Throwable {
            String path = (String) EasyMock.getCurrentArguments()[0];
            File file = new File(getRootPath(), path);
            return new FileInputStream(file);
        }

    }).anyTimes();

    expect(context.getAttribute(isA(String.class))).andAnswer(new IAnswer<Object>() {

        public Object answer() throws Throwable {
            return attributes.get(EasyMock.getCurrentArguments()[0]);
        }

    }).anyTimes();

    context.setAttribute(isA(String.class), isA(Object.class));
    expectLastCall().andAnswer(new IAnswer<Object>() {

        public Object answer() throws Throwable {
            String key = (String) EasyMock.getCurrentArguments()[0];
            Object value = EasyMock.getCurrentArguments()[1];
            attributes.put(key, value);
            return null;
        }

    }).anyTimes();

    expect(config.getInitParameterNames()).andReturn(new Enumeration<String>() {

        public boolean hasMoreElements() {
            return false;
        }

        public String nextElement() {
            return null;
        }

    }).anyTimes();

    expect(config.getInitParameter(JawrConstant.TYPE_INIT_PARAMETER)).andAnswer(new IAnswer<String>() {
        public String answer() throws Throwable {
            return respData == null ? null : respData.getType();
        }
    }).anyTimes();

    expect(config.getInitParameter("configLocation")).andReturn(getConfigLocation()).anyTimes();
    expect(config.getInitParameter("configPropertiesSourceClass")).andReturn(null).anyTimes();
}

From source file:org.jahia.ajax.gwt.helper.StubHelper.java

/**
 * Returns a map of code snippets.//from ww w  .  j  a  v a  2  s . com
 * 
 * @param fileType
 *            the type of the file to lookup snippets for, e.g. "jsp"
 * @param snippetType
 *            the snippet type to lookup code snippets for, e.g. "conditionals", "loops" etc.
 * @param nodeTypeName
 *            null or the node type associated with the file
 * @return a map of code snippets
 */
private Map<String, String> getCodeSnippets(String fileType, String snippetType, String nodeTypeName) {
    Map<String, String> stub = new LinkedHashMap<String, String>();
    InputStream is = null;
    try {
        ServletContext servletContext = JahiaContextLoaderListener.getServletContext();
        @SuppressWarnings("unchecked")
        Set<String> resources = servletContext
                .getResourcePaths("/WEB-INF/etc/snippets/" + fileType + "/" + snippetType + "/");
        ExtendedNodeType n = null;
        if (resources != null) {
            for (String resource : resources) {
                String resourceName = StringUtils.substringAfterLast(resource, "/");
                String viewNodeType = getResourceViewNodeType(resourceName);
                if (nodeTypeName != null && viewNodeType != null) {
                    // check if the view node type matches the requested one
                    if (null == n) {
                        try {
                            n = NodeTypeRegistry.getInstance().getNodeType(nodeTypeName);
                        } catch (NoSuchNodeTypeException e) {
                            // node type not found, do nothing
                        }
                    }
                    if (n != null && !n.isNodeType(viewNodeType)) {
                        // we skip that stub as it's node type does not match the requested one
                        continue;
                    }
                }
                is = servletContext.getResourceAsStream(resource);
                try {
                    stub.put(viewNodeType != null ? (resourceName + "/" + viewNodeType) : resourceName,
                            StringUtils.join(IOUtils.readLines(is), "\n"));
                } finally {
                    IOUtils.closeQuietly(is);
                }
            }
        }
    } catch (IOException e) {
        logger.error("Failed to read code snippets from " + fileType + "/" + snippetType, e);
    }
    return stub;
}

From source file:com.kohmiho.mpsr.export.PDFGenerator.java

private Image getEmbeddedImage(ServletContext servletContext, String path)
        throws BadElementException, MalformedURLException, IOException {
    // return Image.getInstance(servletContext.getRealPath(path));
    return Image.getInstance(IOUtils.toByteArray(servletContext.getResourceAsStream(path)));
}

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

private void configureSystemSettings(ServletContext context) {
    LOG.info("configureSystemSettings");
    SystemSettings systemSettings = new SystemSettings();
    try {//  w ww  .  ja  va2s .  co m
        // Load the settings...
        InputStream source = null;
        // Look in build.properties, or use default
        String settingsFile = this.get(SYSTEM_SETTINGS_FILE);
        if (settingsFile != null) {
            LOG.info("SystemSettings path: " + this.get(FILE_LIBRARY_PATH) + settingsFile);
            source = new FileInputStream(this.get(FILE_LIBRARY_PATH) + settingsFile);
        } else {
            LOG.info("SystemSettings path: /WEB-INF/settings.xml");
            source = context.getResourceAsStream("/WEB-INF/settings.xml");
        }
        if (source != null) {
            LOG.info("Loading system settings...");
            XMLUtils xml = new XMLUtils(source);
            systemSettings.initialize(xml.getDocumentElement());
            source.close();
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        LOG.error("System Settings Error", e);
    }
    context.setAttribute(Constants.SYSTEM_SETTINGS, systemSettings);
}

From source file:org.theospi.portfolio.portal.web.XsltPortal.java

protected void processCategoryFiles(ToolCategory toolCategory, ServletContext context) throws IOException {
    File base = new File(categoryBasePath);
    String parentPath = base.getParent();

    Set paths = context.getResourcePaths(parentPath);

    for (Iterator<String> i = paths.iterator(); i.hasNext();) {
        String path = i.next();/*from w w w. j av a 2 s  .  c  o m*/
        if (path.startsWith(categoryBasePath)) {
            path += toolCategory.getHomePagePath();
            if (context.getResource(path) != null) {
                processCategoryFile(toolCategory, path, context.getResourceAsStream(path));
            }
        }
    }
}

From source file:com.jsmartframework.web.manager.BeanHandler.java

private void readJspPageResource(ServletContext context, String path, JspPageBean jspPageBean) {
    InputStream is = context.getResourceAsStream(getForwardPath(path));

    if (is != null) {
        Scanner fileScanner = new Scanner(is);
        Set<String> includes = new LinkedHashSet<>();

        try {//from w ww. j a v  a  2  s.  c  o  m
            String lineScan;
            while ((lineScan = fileScanner.findWithinHorizon(HANDLER_EL_PATTERN, 0)) != null) {

                boolean hasInclude = false;
                Matcher matcher = INCLUDE_PATTERN.matcher(lineScan);

                while (matcher.find()) {
                    hasInclude = true;
                    includes.add(matcher.group(1));
                }

                if (hasInclude) {
                    continue;
                }

                matcher = ExpressionHandler.EL_PATTERN.matcher(lineScan);
                while (matcher.find()) {
                    for (String name : matcher.group(1).split(Constants.SEPARATOR_REGEX)) {
                        if (webBeans.containsKey(name.trim())) {
                            jspPageBean.addBeanName(name.trim());
                        }
                    }
                }

                matcher = ExpressionHandler.JSP_PATTERN.matcher(lineScan);
                while (matcher.find()) {
                    for (String name : matcher.group(1).split(Constants.SEPARATOR_REGEX)) {
                        if (webBeans.containsKey(name.trim())) {
                            jspPageBean.addBeanName(name.trim());
                        }
                    }
                }

                matcher = ExpressionHandler.ID_PATTERN.matcher(lineScan);
                while (matcher.find()) {
                    AnnotatedAction annotatedAction = getAnnotatedAction(matcher.group(1));
                    if (annotatedAction != null) {
                        jspPageBean.addBeanName(annotatedAction.getClassName());
                    }
                }
            }
        } finally {
            fileScanner.close();
        }

        // Read include page resources
        for (String include : includes) {
            String includeOwner = getForwardPath(path);
            includeOwner = includeOwner.substring(0, includeOwner.lastIndexOf(Constants.PATH_SEPARATOR) + 1);

            include = getRelativeIncludePath(includeOwner, include);
            readJspPageResource(context, include, jspPageBean);
        }
    }
}

From source file:org.wise.vle.utils.FileManager.java

/**
 * Retrieves all of the scripts in the scripts array and writes them out in the <code>HttpServletResponse</code>
 * @param context the context to retrieve the files from
 * @param data the script file names//from   w ww .j  a  va  2s  . com
 * @return the contents of the scripts
 * @throws IOException
 */
public static String getScripts(ServletContext context, String data) throws IOException {
    String[] scripts = data.split("~");

    StringBuffer scriptsText = new StringBuffer();

    String out = "";

    for (String script : scripts) {
        InputStream is = context.getResourceAsStream("/" + script);
        if (is != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            while ((out = reader.readLine()) != null) {
                scriptsText.append(out);
                scriptsText.append("\n");
            }
        }
    }

    scriptsText.append(
            "scriptloader.scriptAvailable(scriptloader.baseUrl + \"vle/filemanager.html?command=getScripts&param1="
                    + data + "\");");
    scriptsText.append("\n");

    return scriptsText.toString();
}

From source file:com.haulmont.cuba.core.sys.AbstractWebAppContextLoader.java

protected void initAppProperties(ServletContext sc) {
    // get properties from web.xml
    String appProperties = sc.getInitParameter(APP_PROPS_PARAM);
    if (appProperties != null) {
        StrTokenizer tokenizer = new StrTokenizer(appProperties);
        for (String str : tokenizer.getTokenArray()) {
            int i = str.indexOf("=");
            if (i < 0)
                continue;
            String name = StringUtils.substring(str, 0, i);
            String value = StringUtils.substring(str, i + 1);
            if (!StringUtils.isBlank(name)) {
                AppContext.setProperty(name, value);
            }/* w  w  w.j a  v a  2  s.  co  m*/
        }
    }

    // get properties from a set of app.properties files defined in web.xml
    String propsConfigName = getAppPropertiesConfig(sc);
    if (propsConfigName == null)
        throw new IllegalStateException(APP_PROPS_CONFIG_PARAM + " servlet context parameter not defined");

    final Properties properties = new Properties();

    DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
    StrTokenizer tokenizer = new StrTokenizer(propsConfigName);
    tokenizer.setQuoteChar('"');
    for (String str : tokenizer.getTokenArray()) {
        log.trace("Processing properties location: {}", str);
        str = StrSubstitutor.replaceSystemProperties(str);
        InputStream stream = null;
        try {
            if (ResourceUtils.isUrl(str) || str.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)) {
                Resource resource = resourceLoader.getResource(str);
                if (resource.exists())
                    stream = resource.getInputStream();
            } else {
                stream = sc.getResourceAsStream(str);
            }

            if (stream != null) {
                log.info("Loading app properties from {}", str);
                try (Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
                    properties.load(reader);
                }
            } else {
                log.trace("Resource {} not found, ignore it", str);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    for (Object key : properties.keySet()) {
        AppContext.setProperty((String) key, properties.getProperty((String) key).trim());
    }
}

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
 */// w ww. j a v  a  2 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;
}