List of usage examples for javax.servlet ServletContext getResourcePaths
public Set<String> getResourcePaths(String path);
From source file:com.videobox.web.util.dwr.AutoAnnotationDiscoveryContainer.java
private StringBuilder scanContext(ServletContext ctx, StringBuilder sb, String pkg) throws IOException { String path = pkg.replaceAll("\\.", "/"); Set<String> set = ctx.getResourcePaths("/WEB-INF/classes/" + path); if (set == null) { return null; }// w w w . jav a2 s. co m for (String className : set) { scanContextPath(ctx, sb, className); } return sb; }
From source file:de.appsolve.padelcampus.utils.HtmlResourceUtil.java
private void copyResources(ServletContext context, String sourceFolder, File destinationFolder) throws MalformedURLException, IOException { Set<String> resourcePaths = context.getResourcePaths(sourceFolder); if (resourcePaths == null) { LOG.warn(String.format("Unable to find folder %s", sourceFolder)); } else {/* w w w .ja v a 2 s. co m*/ for (String resourcePath : resourcePaths) { if (resourcePath.endsWith("/")) { //must be a directory copyResources(context, resourcePath, destinationFolder); } else { URL resource = context.getResource(resourcePath); FileUtils.copyURLToFile(resource, new File(destinationFolder, resourcePath)); } } } }
From source file:org.motechproject.server.osgi.OsgiFrameworkService.java
/** * Find built-in/mandatory bundles//from www.j a v a 2s . c om * * @param servletContext * @return * @throws Exception */ private List<URL> findInternalBundles(ServletContext servletContext) throws Exception { List<URL> list = new ArrayList<URL>(); if (StringUtils.isNotBlank(internalBundleFolder)) { @SuppressWarnings("unchecked") Set<String> paths = servletContext.getResourcePaths(internalBundleFolder); if (paths != null) { for (String path : paths) { if (path.endsWith(".jar")) { URL url = servletContext.getResource(path); if (url != null) { list.add(url); } } } } } return list; }
From source file:com.googlecode.psiprobe.AbstractTomcatContainer.java
/** * Lists and optionally compiles a directory recursively. * * @param jspName name of JSP file or directory to be listed and compiled. * @param opt// www .j ava 2 s .c o m * @param ctx * @param jrctx * @param summary * @param classLoader * @param level * @param compile */ protected void compileItem(String jspName, Options opt, Context ctx, JspRuntimeContext jrctx, Summary summary, URLClassLoader classLoader, int level, boolean compile) { ServletContext sctx = ctx.getServletContext(); Set paths = sctx.getResourcePaths(jspName); if (paths != null) { for (Iterator it = paths.iterator(); it.hasNext();) { String name = (String) it.next(); boolean isJsp = false; try { isJsp = name.endsWith(".jsp") || name.endsWith(".jspx") || opt.getJspConfig().isJspPage(name); } catch (JasperException e) { logger.info("isJspPage() thrown an error for " + name, e); } if (isJsp) { JspCompilationContext jcctx = createJspCompilationContext(name, false, opt, sctx, jrctx, classLoader); ClassLoader prevCl = ClassUtils.overrideThreadContextClassLoader(classLoader); try { Item item = (Item) summary.getItems().get(name); if (item == null) { item = new Item(); item.setName(name); } item.setLevel(level); item.setCompileTime(-1); Long objects[] = this.getResourceAttributes(name, ctx); item.setSize(objects[0].longValue()); item.setLastModified(objects[1].longValue()); // } catch (NamingException e) { // logger.error("Cannot lookup attributes for " + name); // } long time = System.currentTimeMillis(); try { org.apache.jasper.compiler.Compiler c = jcctx.createCompiler(); if (compile) { c.compile(); item.setState(Item.STATE_READY); item.setException(null); } else { if (!c.isOutDated()) { item.setState(Item.STATE_READY); item.setException(null); } else if (item.getState() != Item.STATE_FAILED) { item.setState(Item.STATE_OOD); item.setException(null); } } logger.info("Compiled " + name + ": OK"); } catch (Exception e) { item.setState(Item.STATE_FAILED); item.setException(e); logger.info("Compiled " + name + ": FAILED", e); } if (compile) { item.setCompileTime(System.currentTimeMillis() - time); } item.setMissing(false); summary.getItems().put(name, item); } finally { ClassUtils.overrideThreadContextClassLoader(prevCl); } } else { compileItem(name, opt, ctx, jrctx, summary, classLoader, level + 1, compile); } } } else { logger.debug("getResourcePaths() is null for " + jspName + ". Empty dir? Or Tomcat bug?"); } }
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);/*from ww w. j av a2s .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; }
From source file:net.testdriven.psiprobe.AbstractTomcatContainer.java
/** * Lists and optionally compiles a directory recursively. * * @param jspName name of JSP file or directory to be listed and compiled. * @param opt/* www. j av a 2s .c o m*/ * @param ctx * @param jrctx * @param summary * @param classLoader * @param level * @param compile */ protected void compileItem(String jspName, Options opt, Context ctx, JspRuntimeContext jrctx, Summary summary, URLClassLoader classLoader, int level, boolean compile) { ServletContext sctx = ctx.getServletContext(); Set paths = sctx.getResourcePaths(jspName); if (paths != null) { for (Iterator it = paths.iterator(); it.hasNext();) { String name = (String) it.next(); boolean isJsp = false; try { isJsp = name.endsWith(".jsp") || name.endsWith(".jspx") || opt.getJspConfig().isJspPage(name); } catch (JasperException e) { logger.info("isJspPage() thrown an error for " + name, e); } if (isJsp) { JspCompilationContext jcctx = createJspCompilationContext(name, false, opt, sctx, jrctx, classLoader); ClassLoader prevCl = ClassUtils.overrideThreadContextClassLoader(classLoader); try { Item item = (Item) summary.getItems().get(name); if (item == null) { item = new Item(); item.setName(name); } item.setLevel(level); item.setCompileTime(-1); try { ResourceAttributes jspAttributes = (ResourceAttributes) ctx.getResources() .getAttributes(name); item.setSize(jspAttributes.getContentLength()); item.setLastModified(jspAttributes.getLastModified()); } catch (NamingException e) { logger.error("Cannot lookup attributes for " + name); } long time = System.currentTimeMillis(); try { org.apache.jasper.compiler.Compiler c = jcctx.createCompiler(); if (compile) { c.compile(); item.setState(Item.STATE_READY); item.setException(null); } else { if (!c.isOutDated()) { item.setState(Item.STATE_READY); item.setException(null); } else if (item.getState() != Item.STATE_FAILED) { item.setState(Item.STATE_OOD); item.setException(null); } } logger.info("Compiled " + name + ": OK"); } catch (Exception e) { item.setState(Item.STATE_FAILED); item.setException(e); logger.info("Compiled " + name + ": FAILED", e); } if (compile) { item.setCompileTime(System.currentTimeMillis() - time); } item.setMissing(false); summary.getItems().put(name, item); } finally { ClassUtils.overrideThreadContextClassLoader(prevCl); } } else { compileItem(name, opt, ctx, jrctx, summary, classLoader, level + 1, compile); } } } else { logger.debug("getResourcePaths() is null for " + jspName + ". Empty dir? Or Tomcat bug?"); } }
From source file:com.blackducksoftware.integration.hub.jenkins.site.BlackDuckHubUpdateSite.java
/** * Verifies the signature in the update center data file. *///w w w . j ava2 s . c o m 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:edu.cornell.mannlib.vitro.webapp.servlet.setup.RunSparqlConstructs.java
public void contextInitialized(ServletContextEvent sce) { try {//from ww w .java2s. c o m ServletContext ctx = sce.getServletContext(); WebappDaoFactory wadf = ModelAccess.on(ctx).getWebappDaoFactory(); String namespace = (wadf != null && wadf.getDefaultNamespace() != null) ? wadf.getDefaultNamespace() : DEFAULT_DEFAULT_NAMESPACE; OntModel baseOntModel = ModelAccess.on(ctx).getOntModel(FULL_ASSERTIONS); Model anonModel = ModelFactory.createDefaultModel(); Model namedModel = ModelFactory.createDefaultModel(); Set<String> resourcePaths = ctx.getResourcePaths(SPARQL_DIR); for (String path : resourcePaths) { log.debug("Attempting to execute SPARQL at " + path); File file = new File(ctx.getRealPath(path)); try { BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuffer fileContents = new StringBuffer(); String ln; try { while ((ln = reader.readLine()) != null) { fileContents.append(ln).append('\n'); } try { Query q = QueryFactory.create(fileContents.toString(), Syntax.syntaxARQ); QueryExecution qe = QueryExecutionFactory.create(q, baseOntModel); qe.execConstruct(anonModel); } catch (Exception e) { String queryErrMsg = "Unable to execute query at " + path + " :"; log.error(queryErrMsg); System.out.println(queryErrMsg); e.printStackTrace(); } } catch (IOException ioe) { log.error("IO Exception reading " + path + " :"); ioe.printStackTrace(); } } catch (FileNotFoundException fnfe) { log.info(path + " not found. Skipping."); } } namedModel.add(anonModel); for (Iterator<Resource> i = anonModel.listSubjects(); i.hasNext();) { Resource s = i.next(); if (s.isAnon()) { int randomInt = -1; while (randomInt < 0 || baseOntModel.getIndividual(namespace + LOCAL_NAME_PREPEND + randomInt) != null) { randomInt = random.nextInt(Integer.MAX_VALUE); } Resource t = namedModel.createResource(s.getId()); ResourceUtils.renameResource(t, namespace + LOCAL_NAME_PREPEND + randomInt); } } baseOntModel.addSubModel(namedModel); String msg = "Attaching " + namedModel.size() + " statements as a result of SPARQL CONSTRUCTS"; log.info(msg); System.out.println(msg); } catch (Throwable t) { System.out.println("Throwable in listener " + this.getClass().getName()); t.printStackTrace(); log.error(t); } }
From source file:com.cloudbees.jenkins.plugins.enterpriseplugins.CloudBeesUpdateSite.java
/** * Verifies the signature in the update center data file. *///from www . j a va2 s. c o m 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:psiprobe.AbstractTomcatContainer.java
/** * Lists and optionally compiles a directory recursively. * * @param jspName name of JSP file or directory to be listed and compiled. * @param opt the JSP compiler options//w w w.ja v a 2s .c o m * @param ctx the context * @param jrctx the runtime context used to create the compilation context * @param summary the summary in which the output is stored * @param classLoader the classloader used by the compiler * @param level the depth in the tree at which the item was encountered * @param compile whether or not to compile the item or just to check whether it's out of date */ protected void compileItem(String jspName, Options opt, Context ctx, JspRuntimeContext jrctx, Summary summary, URLClassLoader classLoader, int level, boolean compile) { ServletContext sctx = ctx.getServletContext(); Set<String> paths = sctx.getResourcePaths(jspName); if (paths != null) { for (String name : paths) { boolean isJsp = false; try { isJsp = name.endsWith(".jsp") || name.endsWith(".jspx") || opt.getJspConfig().isJspPage(name); } catch (Exception e) { // XXX Tomcat 7.0.x throws JasperException otherwise this could be removed. logger.info("isJspPage() thrown an error for '{}'", name, e); } if (isJsp) { JspCompilationContext jcctx = createJspCompilationContext(name, opt, sctx, jrctx, classLoader); ClassLoader prevCl = ClassUtils.overrideThreadContextClassLoader(classLoader); try { Item item = summary.getItems().get(name); if (item == null) { item = new Item(); item.setName(name); } item.setLevel(level); item.setCompileTime(-1); Long[] objects = this.getResourceAttributes(name, ctx); item.setSize(objects[0]); item.setLastModified(objects[1]); long time = System.currentTimeMillis(); try { org.apache.jasper.compiler.Compiler compiler = jcctx.createCompiler(); if (compile) { compiler.compile(); item.setState(Item.STATE_READY); item.setException(null); } else { if (!compiler.isOutDated()) { item.setState(Item.STATE_READY); item.setException(null); } else if (item.getState() != Item.STATE_FAILED) { item.setState(Item.STATE_OOD); item.setException(null); } } logger.info("Compiled '{}': OK", name); } catch (Exception e) { item.setState(Item.STATE_FAILED); item.setException(e); logger.info("Compiled '{}': FAILED", name, e); } if (compile) { item.setCompileTime(System.currentTimeMillis() - time); } item.setMissing(false); summary.getItems().put(name, item); } finally { ClassUtils.overrideThreadContextClassLoader(prevCl); } } else { compileItem(name, opt, ctx, jrctx, summary, classLoader, level + 1, compile); } } } else { logger.debug("getResourcePaths() is null for '{}'. Empty dir? Or Tomcat bug?", jspName); } }