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.apache.axis.configuration.EngineConfigurationFactoryServlet.java

/**
 * Get a default server engine configuration in a servlet environment.
 *
 * @param ctx a ServletContext/*from w w w  . jav a  2  s .c  o m*/
 * @return a server EngineConfiguration
 */
private static EngineConfiguration getServerEngineConfig(ServletConfig cfg) {

    ServletContext ctx = cfg.getServletContext();

    // Respect the system property setting for a different config file
    String configFile = cfg.getInitParameter(OPTION_SERVER_CONFIG_FILE);
    if (configFile == null)
        configFile = AxisProperties.getProperty(OPTION_SERVER_CONFIG_FILE);
    if (configFile == null) {
        configFile = SERVER_CONFIG_FILE;
    }

    /**
     * Flow can be confusing.  Here is the logic:
     * 1) Make all attempts to open resource IF it exists
     *    - If it exists as a file, open as file (r/w)
     *    - If not a file, it may still be accessable as a stream (r)
     *    (env will handle security checks).
     * 2) If it doesn't exist, allow it to be opened/created
     * 
     * Now, the way this is done below is:
     * a) If the file does NOT exist, attempt to open as a stream (r)
     * b) Open named file (opens existing file, creates if not avail).
     */

    /*
     * Use the WEB-INF directory
     * (so the config files can't get snooped by a browser)
     */
    String appWebInfPath = "/WEB-INF";

    FileProvider config = null;

    String realWebInfPath = ctx.getRealPath(appWebInfPath);

    /**
     * If path/file doesn't exist, it may still be accessible
     * as a resource-stream (i.e. it may be packaged in a JAR
     * or WAR file).
     */
    if (realWebInfPath == null || !(new File(realWebInfPath, configFile)).exists()) {
        String name = appWebInfPath + "/" + configFile;
        InputStream is = ctx.getResourceAsStream(name);
        if (is != null) {
            // FileProvider assumes responsibility for 'is':
            // do NOT call is.close().
            config = new FileProvider(is);
        }

        if (config == null) {
            log.error(Messages.getMessage("servletEngineWebInfError03", name));
        }
    }

    /**
     * Couldn't get data  OR  file does exist.
     * If we have a path, then attempt to either open
     * the existing file, or create an (empty) file.
     */
    if (config == null && realWebInfPath != null) {
        try {
            config = new FileProvider(realWebInfPath, configFile);
        } catch (ConfigurationException e) {
            log.error(Messages.getMessage("servletEngineWebInfError00"), e);
        }
    }

    /**
     * Fall back to config file packaged with AxisEngine
     */
    if (config == null) {
        log.warn(Messages.getMessage("servletEngineWebInfWarn00"));
        try {
            InputStream is = ClassUtils.getResourceAsStream(AxisServer.class, SERVER_CONFIG_FILE);
            config = new FileProvider(is);
        } catch (Exception e) {
            log.error(Messages.getMessage("servletEngineWebInfError02"), e);
        }
    }

    return config;
}

From source file:org.vulpe.controller.filter.VulpeFilterDispatcher.java

/**
 * Initiate URL Rewrite Filter.//from  w ww.  j  a v a2  s. co m
 *
 * @param filterConfig
 * @throws ServletException
 */
private void initURLRewrite(final FilterConfig filterConfig) throws ServletException {
    URL_REWRITE_FILTER.init(filterConfig);
    final ServletContext context = filterConfig.getServletContext();
    String confPath = filterConfig.getInitParameter("confPath");
    if (StringUtils.isEmpty(confPath)) {
        confPath = UrlRewriteFilter.DEFAULT_WEB_CONF_PATH;
    }
    URL confUrl = null;
    try {
        confUrl = context.getResource(confPath);
    } catch (MalformedURLException e) {
        LOG.debug(e.getMessage());
    }
    String confUrlStr = null;
    if (confUrl != null) {
        confUrlStr = confUrl.toString();
    }
    final InputStream inputStream = context.getResourceAsStream(confPath);
    final Conf conf = new Conf(context, inputStream, confPath, confUrlStr, false);
    URL_REWRITER = new UrlRewriter(conf);
}

From source file:org.jaggeryjs.jaggery.core.manager.JaggeryDeployerManager.java

private static void executeScripts(Context context, JSONArray arr) {
    if (arr != null) {
        try {//from   w ww  . ja v a 2 s  .c om
            JaggeryContext sharedContext = WebAppManager.sharedJaggeryContext(context.getServletContext());
            CommonManager.setJaggeryContext(sharedContext);
            RhinoEngine engine = sharedContext.getEngine();
            org.mozilla.javascript.Context cx = engine.enterContext();
            ServletContext servletContext = (ServletContext) sharedContext
                    .getProperty(org.jaggeryjs.hostobjects.web.Constants.SERVLET_CONTEXT);
            ScriptableObject sharedScope = sharedContext.getScope();

            Object[] scripts = arr.toArray();
            for (Object script : scripts) {
                if (!(script instanceof String)) {
                    log.error("Invalid value for initScripts/destroyScripts in jaggery.conf : " + script);
                    continue;
                }
                String path = (String) script;
                path = path.startsWith("/") ? path : "/" + path;
                Stack<String> callstack = CommonManager.getCallstack(sharedContext);
                callstack.push(path);
                String[] parts = WebAppManager.getKeys(servletContext.getContextPath(), path, path);
                ScriptCachingContext sctx = new ScriptCachingContext(sharedContext.getTenantDomain(), parts[0],
                        parts[1], parts[2]);
                sctx.setSecurityDomain(new JaggerySecurityDomain(path, servletContext));
                engine.exec(new ScriptReader(servletContext.getResourceAsStream(path)) {
                    @Override
                    protected void build() throws IOException {
                        try {
                            sourceReader = new StringReader(HostObjectUtil.streamToString(sourceIn));
                        } catch (ScriptException e) {
                            // throw new IOException(e);
                        }
                    }
                }, sharedScope, sctx);
            }
        } catch (ScriptException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (org.mozilla.javascript.Context.getCurrentContext() != null) {
                RhinoEngine.exitContext();
            }
        }
    }
}

From source file:org.exoplatform.wiki.service.impl.WikiRestServiceImpl.java

/**
 * {@inheritDoc}/* www  .ja  v  a 2 s  . co  m*/
 */
@POST
@Path("/content/")
@Produces(MediaType.TEXT_HTML)
public Response getWikiPageContent(@QueryParam("sessionKey") String sessionKey,
        @QueryParam("wikiContext") String wikiContextKey, @QueryParam("markup") boolean isMarkup,
        @FormParam("html") String data) {
    EnvironmentContext env = EnvironmentContext.getCurrent();
    WikiContext wikiContext = new WikiContext();
    String currentSyntax = Syntax.XWIKI_2_0.toIdString();
    HttpServletRequest request = (HttpServletRequest) env.get(HttpServletRequest.class);
    try {
        if (data == null) {
            if (sessionKey != null && sessionKey.length() > 0) {
                data = (String) request.getSession().getAttribute(sessionKey);
            }
        }
        if (wikiContextKey != null && wikiContextKey.length() > 0) {
            wikiContext = (WikiContext) request.getSession().getAttribute(wikiContextKey);
            currentSyntax = wikiContext.getSyntax();
        }
        Execution ec = ((RenderingServiceImpl) renderingService).getExecution();
        if (ec.getContext() == null) {
            ec.setContext(new ExecutionContext());
        }
        ec.getContext().setProperty(WikiContext.WIKICONTEXT, wikiContext);
        ServletContext wikiServletContext = PortalContainer.getInstance().getPortalContext()
                .getContext("/wiki");
        InputStream is = wikiServletContext
                .getResourceAsStream("/templates/wiki/webui/xwiki/wysiwyginput.html");
        byte[] b = new byte[is.available()];
        is.read(b);
        is.close();

        data = renderingService.render(data, Syntax.XHTML_1_0.toIdString(), currentSyntax, false);
        data = renderingService.render(data, currentSyntax, Syntax.ANNOTATED_XHTML_1_0.toIdString(), false);
        data = new String(b).replace("$content", data);

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return Response.serverError().entity(e.getMessage()).cacheControl(cc).build();
    }
    return Response.ok(data, MediaType.TEXT_HTML).cacheControl(cc).build();
}

From source file:com.dhcc.framework.web.context.DhccContextLoader.java

private boolean isMicrokernelStart(ServletContext sc) {
    Log logger = LogFactory.getLog(DhccContextLoader.class);
    Properties prp = new Properties();
    Connection connection = null;
    String setupFlg = null;/*from  ww  w.j a  va2  s  .com*/
    String microKerne = null;
    try {
        prp.load(sc.getResourceAsStream("WEB-INF/classes/application.properties"));
        setupFlg = prp.getProperty("conf.auto.microKerne.disabled");
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    if ("true".equals(microKerne)) {
        prp = null;
        return false;
    }
    try {
        prp.load(sc.getResourceAsStream("WEB-INF/classes/hibernate.properties"));
        String url = prp.getProperty("jdbc.url");
        String driver = prp.getProperty("jdbc.driver");
        String username = prp.getProperty("jdbc.username");
        String password = prp.getProperty("jdbc.password");
        Class.forName(driver);
        connection = DriverManager.getConnection(url, username, password);
        setupFlg = "1";
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    } catch (ClassNotFoundException e) {
        logger.error(e.getMessage(), e);
    } catch (SQLException e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    if ("1".equals(setupFlg)) {
        prp = null;
        return false;
    }

    prp = null;
    return true;
}

From source file:com.blackducksoftware.integration.hub.jenkins.site.BlackDuckHubUpdateSite.java

/**
 * Verifies the signature in the update center data file.
 *///from   www .ja v a2s. c  om
private FormValidation verifySignature(final JSONObject o) throws IOException {
    try {
        FormValidation warning = null;

        final JSONObject signature = o.getJSONObject("signature");
        if (signature.isNullObject()) {
            return FormValidation.error("No signature block found in update center '" + getId() + "'");
        }
        o.remove("signature");

        final List<X509Certificate> certs = new ArrayList<X509Certificate>();
        {// load and verify certificates
            final CertificateFactory cf = CertificateFactory.getInstance("X509");
            for (final Object cert : signature.getJSONArray("certificates")) {
                final X509Certificate c = (X509Certificate) cf.generateCertificate(
                        new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
                try {
                    c.checkValidity();
                } catch (final CertificateExpiredException e) { // even if the certificate isn't valid yet,
                    // we'll proceed it anyway
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s has expired in update center '%s'", cert.toString(), getId()));
                } catch (final CertificateNotYetValidException e) {
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s is not yet valid in update center '%s'", cert.toString(), getId()));
                }
                certs.add(c);
            }

            // all default root CAs in JVM are trusted, plus certs bundled in Jenkins
            final Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); // CertificateUtil.getDefaultRootCAs();
            final ServletContext context = Jenkins.getInstance().servletContext;
            anchors.add(new TrustAnchor(loadLicenseCaCertificate(), null));
            for (final String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) {
                if (cert.endsWith(".txt")) {
                    continue; // skip text files that are meant to be documentation
                }
                final InputStream stream = context.getResourceAsStream(cert);
                if (stream != null) {
                    try {
                        anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(stream), null));
                    } finally {
                        IOUtils.closeQuietly(stream);
                    }
                }
            }
            CertificateUtil.validatePath(certs, anchors);
        }

        // this is for computing a digest to check sanity
        final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        final DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);

        // this is for computing a signature
        final Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(certs.get(0));
        final SignatureOutputStream sos = new SignatureOutputStream(sig);

        // until JENKINS-11110 fix, UC used to serve invalid digest (and therefore unverifiable signature)
        // that only covers the earlier portion of the file. This was caused by the lack of close() call
        // in the canonical writing, which apparently leave some bytes somewhere that's not flushed to
        // the digest output stream. This affects Jenkins [1.424,1,431].
        // Jenkins 1.432 shipped with the "fix" (1eb0c64abb3794edce29cbb1de50c93fa03a8229) that made it
        // compute the correct digest, but it breaks all the existing UC json metadata out there. We then
        // quickly discovered ourselves in the catch-22 situation. If we generate UC with the correct signature,
        // it'll cut off [1.424,1.431] from the UC. But if we don't, we'll cut off [1.432,*).
        //
        // In 1.433, we revisited 1eb0c64abb3794edce29cbb1de50c93fa03a8229 so that the original "digest"/"signature"
        // pair continues to be generated in a buggy form, while "correct_digest"/"correct_signature" are generated
        // correctly.
        //
        // Jenkins should ignore "digest"/"signature" pair. Accepting it creates a vulnerability that allows
        // the attacker to inject a fragment at the end of the json.
        o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8")).close();

        // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n
        // (which is more likely than someone tampering with update center), we can tell
        final String computedDigest = new String(Base64.encode(sha1.digest()));
        final String providedDigest = signature.optString("correct_digest");
        if (providedDigest == null) {
            return FormValidation.error("No correct_digest parameter in update center '" + getId()
                    + "'. This metadata appears to be old.");
        }
        if (!computedDigest.equalsIgnoreCase(providedDigest)) {
            return FormValidation.error("Digest mismatch: " + computedDigest + " vs " + providedDigest
                    + " in update center '" + getId() + "'");
        }

        final String providedSignature = signature.getString("correct_signature");
        if (!sig.verify(Base64.decode(providedSignature.toCharArray()))) {
            return FormValidation.error(
                    "Signature in the update center doesn't match with the certificate in update center '"
                            + getId() + "'");
        }

        if (warning != null) {
            return warning;
        }
        return FormValidation.ok();
    } catch (final GeneralSecurityException e) {
        return FormValidation.error(e, "Signature verification failed in the update center '" + getId() + "'");
    }
}

From source file:com.cloudbees.jenkins.plugins.enterpriseplugins.CloudBeesUpdateSite.java

/**
 * Verifies the signature in the update center data file.
 *///from   w ww  . j av a2  s. com
private FormValidation verifySignature(JSONObject o) throws IOException {
    try {
        FormValidation warning = null;

        JSONObject signature = o.getJSONObject("signature");
        if (signature.isNullObject()) {
            return FormValidation.error("No signature block found in update center '" + getId() + "'");
        }
        o.remove("signature");

        List<X509Certificate> certs = new ArrayList<X509Certificate>();
        {// load and verify certificates
            CertificateFactory cf = CertificateFactory.getInstance("X509");
            for (Object cert : signature.getJSONArray("certificates")) {
                X509Certificate c = (X509Certificate) cf.generateCertificate(
                        new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
                try {
                    c.checkValidity();
                } catch (CertificateExpiredException e) { // even if the certificate isn't valid yet,
                    // we'll proceed it anyway
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s has expired in update center '%s'", cert.toString(), getId()));
                } catch (CertificateNotYetValidException e) {
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s is not yet valid in update center '%s'", cert.toString(), getId()));
                }
                certs.add(c);
            }

            // all default root CAs in JVM are trusted, plus certs bundled in Jenkins
            Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); // CertificateUtil.getDefaultRootCAs();
            ServletContext context = Hudson.getInstance().servletContext;
            anchors.add(new TrustAnchor(loadLicenseCaCertificate(), null));
            for (String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) {
                if (cert.endsWith(".txt")) {
                    continue; // skip text files that are meant to be documentation
                }
                InputStream stream = context.getResourceAsStream(cert);
                if (stream != null) {
                    try {
                        anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(stream), null));
                    } finally {
                        IOUtils.closeQuietly(stream);
                    }
                }
            }
            CertificateUtil.validatePath(certs, anchors);
        }

        // this is for computing a digest to check sanity
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);

        // this is for computing a signature
        Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(certs.get(0));
        SignatureOutputStream sos = new SignatureOutputStream(sig);

        // until JENKINS-11110 fix, UC used to serve invalid digest (and therefore unverifiable signature)
        // that only covers the earlier portion of the file. This was caused by the lack of close() call
        // in the canonical writing, which apparently leave some bytes somewhere that's not flushed to
        // the digest output stream. This affects Jenkins [1.424,1,431].
        // Jenkins 1.432 shipped with the "fix" (1eb0c64abb3794edce29cbb1de50c93fa03a8229) that made it
        // compute the correct digest, but it breaks all the existing UC json metadata out there. We then
        // quickly discovered ourselves in the catch-22 situation. If we generate UC with the correct signature,
        // it'll cut off [1.424,1.431] from the UC. But if we don't, we'll cut off [1.432,*).
        //
        // In 1.433, we revisited 1eb0c64abb3794edce29cbb1de50c93fa03a8229 so that the original "digest"/"signature"
        // pair continues to be generated in a buggy form, while "correct_digest"/"correct_signature" are generated
        // correctly.
        //
        // Jenkins should ignore "digest"/"signature" pair. Accepting it creates a vulnerability that allows
        // the attacker to inject a fragment at the end of the json.
        o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8")).close();

        // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n
        // (which is more likely than someone tampering with update center), we can tell
        String computedDigest = new String(Base64.encode(sha1.digest()));
        String providedDigest = signature.optString("correct_digest");
        if (providedDigest == null) {
            return FormValidation.error("No correct_digest parameter in update center '" + getId()
                    + "'. This metadata appears to be old.");
        }
        if (!computedDigest.equalsIgnoreCase(providedDigest)) {
            return FormValidation.error("Digest mismatch: " + computedDigest + " vs " + providedDigest
                    + " in update center '" + getId() + "'");
        }

        String providedSignature = signature.getString("correct_signature");
        if (!sig.verify(Base64.decode(providedSignature.toCharArray()))) {
            return FormValidation.error(
                    "Signature in the update center doesn't match with the certificate in update center '"
                            + getId() + "'");
        }

        if (warning != null) {
            return warning;
        }
        return FormValidation.ok();
    } catch (GeneralSecurityException e) {
        return FormValidation.error(e, "Signature verification failed in the update center '" + getId() + "'");
    }
}

From source file:org.jaggeryjs.jaggery.app.mgt.TomcatJaggeryWebappsDeployer.java

private static void executeScripts(Context context, JSONArray arr) {
    if (arr != null) {
        try {//from w  w w .j  a  va  2  s . co m
            JaggeryContext sharedContext = WebAppManager.sharedJaggeryContext(context.getServletContext());
            CommonManager.setJaggeryContext(sharedContext);
            RhinoEngine engine = sharedContext.getEngine();
            org.mozilla.javascript.Context cx = engine.enterContext();
            ServletContext servletContext = (ServletContext) sharedContext
                    .getProperty(org.jaggeryjs.hostobjects.web.Constants.SERVLET_CONTEXT);
            ScriptableObject sharedScope = sharedContext.getScope();

            Object[] scripts = arr.toArray();
            for (Object script : scripts) {
                if (!(script instanceof String)) {
                    log.error("Invalid value for initScripts/destroyScripts in jaggery.conf : " + script);
                    continue;
                }
                String path = (String) script;
                path = path.startsWith("/") ? path : "/" + path;
                Stack<String> callstack = CommonManager.getCallstack(sharedContext);
                callstack.push(path);
                String[] parts = WebAppManager.getKeys(servletContext.getContextPath(), path, path);
                ScriptCachingContext sctx = new ScriptCachingContext(sharedContext.getTenantId(), parts[0],
                        parts[1], parts[2]);
                sctx.setSecurityDomain(new JaggerySecurityDomain(path, servletContext));
                engine.exec(new ScriptReader(servletContext.getResourceAsStream(path)) {
                    @Override
                    protected void build() throws IOException {
                        try {
                            sourceReader = new StringReader(HostObjectUtil.streamToString(sourceIn));
                        } catch (ScriptException e) {
                            throw new IOException(e);
                        }
                    }
                }, sharedScope, sctx);
            }
        } catch (ScriptException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (org.mozilla.javascript.Context.getCurrentContext() != null) {
                RhinoEngine.exitContext();
            }
        }
    }
}

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 ww.j  av a2  s  .  com*/
        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()));
        }
    }
}