List of usage examples for java.util.jar JarFile getInputStream
public synchronized InputStream getInputStream(ZipEntry ze) throws IOException
From source file:org.hyperic.hq.product.server.session.PluginManagerImpl.java
private Map<String, Reader> getXmlReaderMap(JarFile jarFile) throws IOException { final Map<String, Reader> rtn = new HashMap<String, Reader>(); final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; }/*from w w w . j a va 2s. c om*/ if (!entry.getName().toLowerCase().endsWith(".xml")) { continue; } InputStream is = null; try { is = jarFile.getInputStream(entry); final BufferedReader br = new BufferedReader(new InputStreamReader(is)); final StringBuilder buf = new StringBuilder(); String tmp; while (null != (tmp = br.readLine())) { buf.append(tmp); } rtn.put(entry.getName(), new NoCloseStringReader(buf.toString())); } finally { close(is); } } return rtn; }
From source file:org.hyperic.snmp.MIBTree.java
public boolean parse(JarFile jar, String[] accept) throws IOException { AcceptFilter filter = new AcceptFilter(accept); for (Enumeration e = jar.entries(); e.hasMoreElements();) { JarEntry entry = (JarEntry) e.nextElement(); if (entry.isDirectory()) { continue; }//from www.jav a 2 s .c o m if (!entry.getName().startsWith("mibs/")) { continue; } String name = entry.getName().substring(5); if (!filter.accept(name)) { continue; } if (hasParsedFile(new File(name))) { continue; } String where = jar.getName() + "!" + entry.getName(); parse(where, jar.getInputStream(entry)); } return true; }
From source file:com.photon.phresco.util.PhrescoDynamicLoader.java
public InputStream getResourceAsStream(String fileName) throws PhrescoException { InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(fileName); if (resourceAsStream != null) { return resourceAsStream; }/*from w ww . j a va 2 s .co m*/ List<Artifact> artifacts = new ArrayList<Artifact>(); Artifact foundArtifact = null; String destFile = ""; JarFile jarfile = null; for (ArtifactGroup plugin : plugins) { List<ArtifactInfo> versions = plugin.getVersions(); for (ArtifactInfo artifactInfo : versions) { foundArtifact = createArtifact(plugin.getGroupId(), plugin.getArtifactId(), "jar", artifactInfo.getVersion()); artifacts.add(foundArtifact); } } try { URL artifactURLs = MavenArtifactResolver.resolveSingleArtifact(repoInfo.getGroupRepoURL(), repoInfo.getRepoUserName(), repoInfo.getRepoPassword(), artifacts); File jarFile = new File(artifactURLs.toURI()); if (jarFile.getName().equals(foundArtifact.getArtifactId() + "-" + foundArtifact.getVersion() + "." + foundArtifact.getType())) { jarfile = new JarFile(jarFile); for (Enumeration<JarEntry> em = jarfile.entries(); em.hasMoreElements();) { JarEntry jarEntry = em.nextElement(); if (jarEntry.getName().endsWith(fileName)) { destFile = jarEntry.getName(); } } } if (StringUtils.isNotEmpty(destFile)) { ZipEntry entry = jarfile.getEntry(destFile); return jarfile.getInputStream(entry); } } catch (Exception e) { e.printStackTrace(); throw new PhrescoException(e); } return null; }
From source file:org.springfield.lou.application.ApplicationManager.java
private void processRemoteWar(File warfile, String wantedname, String datestring) { // lets first check some vitals to check what it is String warfilename = warfile.getName(); if (warfilename.startsWith("smt_") && warfilename.endsWith("app.war")) { // ok so filename checks out is smt_[name]app.war format String appname = warfilename.substring(4, warfilename.length() - 7); if (wantedname.equals(appname)) { // ok found file is the wanted file // format "29-Aug-2013-16:55" System.out.println("NEW VERSION OF " + appname + " FOUND INSTALLING"); String writedir = "/springfield/lou/apps/" + appname + "/" + datestring; // make all the dirs we need File md = new File(writedir); md.mkdirs();/*from w ww . j a v a2s . c o m*/ md = new File(writedir + "/war"); md.mkdirs(); md = new File(writedir + "/jar"); md.mkdirs(); md = new File(writedir + "/components"); md.mkdirs(); md = new File(writedir + "/css"); md.mkdirs(); md = new File(writedir + "/libs"); md.mkdirs(); try { JarFile war = new JarFile(warfile); // ok lets first find the jar file ! JarEntry entry = war.getJarEntry("WEB-INF/lib/smt_" + appname + "app.jar"); if (entry != null) { byte[] bytes = readJarEntryToBytes(war.getInputStream(entry)); writeBytesToFile(bytes, writedir + "/jar/smt_" + appname + "app.jar"); } // unpack all in eddie dir Enumeration<JarEntry> iter = war.entries(); while (iter.hasMoreElements()) { JarEntry lentry = iter.nextElement(); //System.out.println("LI="+lentry.getName()); String lname = lentry.getName(); if (!lname.endsWith("/")) { int pos = lname.indexOf("/" + appname + "/"); if (pos != -1) { String nname = lname.substring(pos + appname.length() + 2); String dname = nname.substring(0, nname.lastIndexOf('/')); File de = new File(writedir + "/" + dname); de.mkdirs(); byte[] bytes = readJarEntryToBytes(war.getInputStream(lentry)); writeBytesToFile(bytes, writedir + "/" + nname); } } } war.close(); File ren = new File("/springfield/lou/uploaddir/" + warfilename); File nen = new File(writedir + "/war/smt_" + appname + "app.war"); ren.renameTo(nen); // lets tell set the available variable to tell the others we have it. FsNode unode = Fs .getNode("/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring); if (unode != null) { String warlist = unode.getProperty("waravailableat"); if (warlist == null || warlist.equals("")) { Fs.setProperty( "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring, "waravailableat", LazyHomer.myip); } else { Fs.setProperty( "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring, "waravailableat", warlist + "," + LazyHomer.myip); } } } catch (Exception e) { e.printStackTrace(); } } } }
From source file:org.owasp.dependencycheck.analyzer.JarAnalyzer.java
/** * Given a path to a pom.xml within a JarFile, this method attempts to load * a sibling pom.properties if one exists. * * @param path the path to the pom.xml within the JarFile * @param jar the JarFile to load the pom.properties from * @return a Properties object or null if no pom.properties was found * @throws IOException thrown if there is an exception reading the * pom.properties/*from www . j a va 2 s . c o m*/ */ private Properties retrievePomProperties(String path, final JarFile jar) throws IOException { Properties pomProperties = null; final String propPath = path.substring(0, path.length() - 7) + "pom.properies"; final ZipEntry propEntry = jar.getEntry(propPath); if (propEntry != null) { Reader reader = null; try { reader = new InputStreamReader(jar.getInputStream(propEntry), "UTF-8"); pomProperties = new Properties(); pomProperties.load(reader); LOGGER.debug("Read pom.properties: {}", propPath); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { LOGGER.trace("close error", ex); } } } } return pomProperties; }
From source file:org.springfield.lou.application.ApplicationManager.java
private void processUploadedWar(File warfile, String wantedname) { // lets first check some vitals to check what it is String warfilename = warfile.getName(); if (warfilename.startsWith("smt_") && warfilename.endsWith("app.war")) { // ok so filename checks out is smt_[name]app.war format String appname = warfilename.substring(4, warfilename.length() - 7); if (wantedname.equals(appname)) { // ok found file is the wanted file // format "29-Aug-2013-16:55" System.out.println("NEW VERSION OF " + appname + " FOUND INSTALLING"); Date now = new Date(); SimpleDateFormat df = new SimpleDateFormat("d-MMM-yyyy-HH:mm"); String datestring = df.format(now); String writedir = "/springfield/lou/apps/" + appname + "/" + datestring; // create the node Html5AvailableApplication vapp = getAvailableApplication(appname); String newbody = "<fsxml><properties></properties></fsxml>"; ServiceInterface smithers = ServiceManager.getService("smithers"); if (smithers == null) return; FsNode tnode = Fs.getNode("/domain/internal/service/lou/apps/" + appname); if (tnode == null) { smithers.put("/domain/internal/service/lou/apps/" + appname + "/properties", newbody, "text/xml"); }//from w w w . j a va 2 s . c o m smithers.put( "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring + "/properties", newbody, "text/xml"); // make all the dirs we need File md = new File(writedir); md.mkdirs(); md = new File(writedir + "/war"); md.mkdirs(); md = new File(writedir + "/jar"); md.mkdirs(); md = new File(writedir + "/components"); md.mkdirs(); md = new File(writedir + "/css"); md.mkdirs(); md = new File(writedir + "/libs"); md.mkdirs(); try { JarFile war = new JarFile(warfile); // ok lets first find the jar file ! JarEntry entry = war.getJarEntry("WEB-INF/lib/smt_" + appname + "app.jar"); if (entry != null) { byte[] bytes = readJarEntryToBytes(war.getInputStream(entry)); writeBytesToFile(bytes, writedir + "/jar/smt_" + appname + "app.jar"); } // unpack all in eddie dir Enumeration<JarEntry> iter = war.entries(); while (iter.hasMoreElements()) { JarEntry lentry = iter.nextElement(); //System.out.println("LI="+lentry.getName()); String lname = lentry.getName(); if (!lname.endsWith("/")) { int pos = lname.indexOf("/" + appname + "/"); if (pos != -1) { String nname = lname.substring(pos + appname.length() + 2); String dname = nname.substring(0, nname.lastIndexOf('/')); File de = new File(writedir + "/" + dname); de.mkdirs(); byte[] bytes = readJarEntryToBytes(war.getInputStream(lentry)); writeBytesToFile(bytes, writedir + "/" + nname); } } } war.close(); File ren = new File("/springfield/lou/uploaddir/" + warfilename); File nen = new File(writedir + "/war/smt_" + appname + "app.war"); //System.out.println("REN="+warfilename); //System.out.println("REN="+writedir+"/war/smt_"+appname+"app.war"); ren.renameTo(nen); loadAvailableApps(); // should we make in development or production based on autodeploy ? vapp = getAvailableApplication(appname); if (vapp != null) { String mode = vapp.getAutoDeploy(); if (appname.equals("dashboard")) { mode = "development/production"; } System.out.println("APPNAME=" + appname + " mode=" + mode); if (mode.equals("production")) { makeProduction(appname, datestring); } else if (mode.equals("development")) { makeDevelopment(appname, datestring); } else if (mode.equals("development/production")) { makeDevelopment(appname, datestring); makeProduction(appname, datestring); } } /* Html5ApplicationInterface app = getApplication("/domain/webtv/html5application/dashboard"); if (app!=null) { DashboardApplication dapp = (DashboardApplication)app; dapp.newApplicationFound(appname); } */ // lets tell set the available variable to tell the others we have it. FsNode unode = Fs .getNode("/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring); if (unode != null) { String warlist = unode.getProperty("waravailableat"); if (warlist == null || warlist.equals("")) { Fs.setProperty( "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring, "waravailableat", LazyHomer.myip); } else { System.out.println("BUG ? Already available war " + warlist + " a=" + appname); } } } catch (Exception e) { System.out.println("VERSION NOT READY STILL UPLOADING? RETRY WILL HAPPEN SOON"); } } } }
From source file:com.datatorrent.stram.webapp.OperatorDiscoverer.java
public void buildTypeGraph() { Map<String, JarFile> openJarFiles = new HashMap<String, JarFile>(); Map<String, File> openClassFiles = new HashMap<String, File>(); // use global cache to load resource in/out of the same jar as the classes Set<String> resourceCacheSet = new HashSet<>(); try {/*from w w w . j av a 2 s . c o m*/ for (String path : pathsToScan) { File f = null; try { f = new File(path); if (!f.exists() || f.isDirectory() || (!f.getName().endsWith("jar") && !f.getName().endsWith("class"))) { continue; } if (GENERATED_CLASSES_JAR.equals(f.getName())) { continue; } if (f.getName().endsWith("class")) { typeGraph.addNode(f); openClassFiles.put(path, f); } else { JarFile jar = new JarFile(path); openJarFiles.put(path, jar); java.util.Enumeration<JarEntry> entriesEnum = jar.entries(); while (entriesEnum.hasMoreElements()) { final java.util.jar.JarEntry jarEntry = entriesEnum.nextElement(); String entryName = jarEntry.getName(); if (jarEntry.isDirectory()) { continue; } if (entryName.endsWith("-javadoc.xml")) { try { processJavadocXml(jar.getInputStream(jarEntry)); // break; } catch (Exception ex) { LOG.warn("Cannot process javadoc {} : ", entryName, ex); } } else if (entryName.endsWith(".class")) { TypeGraph.TypeGraphVertex newNode = typeGraph.addNode(jarEntry, jar); // check if any visited resources belong to this type for (Iterator<String> iter = resourceCacheSet.iterator(); iter.hasNext();) { String entry = iter.next(); if (entry.startsWith(entryName.substring(0, entryName.length() - 6))) { newNode.setHasResource(true); iter.remove(); } } } else { String className = entryName; boolean foundClass = false; // check if this resource belongs to any visited type while (className.contains("/")) { className = className.substring(0, className.lastIndexOf('/')); TypeGraph.TypeGraphVertex tgv = typeGraph.getNode(className.replace('/', '.')); if (tgv != null) { tgv.setHasResource(true); foundClass = true; break; } } if (!foundClass) { resourceCacheSet.add(entryName); } } } } } catch (IOException ex) { LOG.warn("Cannot process file {}", f, ex); } } typeGraph.trim(); } finally { for (Entry<String, JarFile> entry : openJarFiles.entrySet()) { try { entry.getValue().close(); } catch (IOException e) { DTThrowable.wrapIfChecked(e); } } } }
From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java
private static void writeJarEntries(JarFile jar, JarOutputStream jos, String signatureName) throws IOException { for (Enumeration<?> jarEntries = jar.entries(); jarEntries.hasMoreElements();) { JarEntry jarEntry = (JarEntry) jarEntries.nextElement(); if (!jarEntry.isDirectory()) { String entryName = jarEntry.getName(); // Signature files not to write across String sigFileLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName, SIGNATURE_EXT) .toUpperCase();//from w w w. j av a 2s. co m String dsaSigBlockLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName, DSA_SIG_BLOCK_EXT); String rsaSigBlockLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName, RSA_SIG_BLOCK_EXT); // Do not write across existing manifest or matching signature files if ((!entryName.equalsIgnoreCase(MANIFEST_LOCATION)) && (!entryName.equalsIgnoreCase(sigFileLocation)) && (!entryName.equalsIgnoreCase(dsaSigBlockLocation)) && (!entryName.equalsIgnoreCase(rsaSigBlockLocation))) { // New JAR entry based on original JarEntry newJarEntry = new JarEntry(jarEntry.getName()); newJarEntry.setMethod(jarEntry.getMethod()); newJarEntry.setCompressedSize(jarEntry.getCompressedSize()); newJarEntry.setCrc(jarEntry.getCrc()); jos.putNextEntry(newJarEntry); InputStream jis = null; try { jis = jar.getInputStream(jarEntry); byte[] buffer = new byte[2048]; int read = -1; while ((read = jis.read(buffer)) != -1) { jos.write(buffer, 0, read); } jos.closeEntry(); } finally { IOUtils.closeQuietly(jis); } } } } }
From source file:org.apache.catalina.startup.HostConfig.java
/** * Deploy WAR files./*from ww w . j a v a2 s . c om*/ */ protected void deployWARs(File appBase, String[] files) { for (int i = 0; i < files.length; i++) { if (files[i].equalsIgnoreCase("META-INF")) continue; if (files[i].equalsIgnoreCase("WEB-INF")) continue; if (deployed.contains(files[i])) continue; File dir = new File(appBase, files[i]); if (files[i].toLowerCase().endsWith(".war")) { deployed.add(files[i]); // Calculate the context path and make sure it is unique String contextPath = "/" + files[i]; int period = contextPath.lastIndexOf("."); if (period >= 0) contextPath = contextPath.substring(0, period); if (contextPath.equals("/ROOT")) contextPath = ""; if (host.findChild(contextPath) != null) continue; // Checking for a nested /META-INF/context.xml JarFile jar = null; JarEntry entry = null; InputStream istream = null; BufferedOutputStream ostream = null; File xml = new File(configBase, files[i].substring(0, files[i].lastIndexOf(".")) + ".xml"); if (!xml.exists()) { try { jar = new JarFile(dir); entry = jar.getJarEntry("META-INF/context.xml"); if (entry != null) { istream = jar.getInputStream(entry); ostream = new BufferedOutputStream(new FileOutputStream(xml), 1024); byte buffer[] = new byte[1024]; while (true) { int n = istream.read(buffer); if (n < 0) { break; } ostream.write(buffer, 0, n); } ostream.flush(); ostream.close(); ostream = null; istream.close(); istream = null; entry = null; jar.close(); jar = null; deployDescriptors(configBase(), configBase.list()); return; } } catch (Exception e) { // Ignore and continue if (ostream != null) { try { ostream.close(); } catch (Throwable t) { ; } ostream = null; } if (istream != null) { try { istream.close(); } catch (Throwable t) { ; } istream = null; } entry = null; if (jar != null) { try { jar.close(); } catch (Throwable t) { ; } jar = null; } } } if (isUnpackWARs()) { // Expand and deploy this application as a directory log.debug(sm.getString("hostConfig.expand", files[i])); URL url = null; String path = null; try { url = new URL("jar:file:" + dir.getCanonicalPath() + "!/"); path = ExpandWar.expand(host, url); } catch (IOException e) { // JAR decompression failure log.warn(sm.getString("hostConfig.expand.error", files[i])); continue; } catch (Throwable t) { log.error(sm.getString("hostConfig.expand.error", files[i]), t); continue; } try { if (path != null) { url = new URL("file:" + path); ((Deployer) host).install(contextPath, url); } } catch (Throwable t) { log.error(sm.getString("hostConfig.expand.error", files[i]), t); } } else { // Deploy the application in this WAR file log.info(sm.getString("hostConfig.deployJar", files[i])); try { URL url = new URL("file", null, dir.getCanonicalPath()); url = new URL("jar:" + url.toString() + "!/"); ((Deployer) host).install(contextPath, url); } catch (Throwable t) { log.error(sm.getString("hostConfig.deployJar.error", files[i]), t); } } } } }
From source file:org.jahia.utils.maven.plugin.osgi.DependenciesMojo.java
private int scanJar(File jarFile, boolean externalDependency, String packageDirectory, String version, boolean optional, ParsingContext parsingContext, String logPrefix) throws IOException { int scanned = 0; if (jarFile.isDirectory()) { getLog().debug(logPrefix + "Processing dependency directory " + jarFile + "..."); processDirectoryTlds(jarFile, version, parsingContext); processDirectory(jarFile, false, version, parsingContext); return scanned; }// ww w. ja v a 2 s . c o m JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile)); try { JarEntry jarEntry = null; getLog().debug(logPrefix + "Processing JAR file " + jarFile + "..."); if (processJarManifest(jarFile, parsingContext, jarInputStream)) { getLog().debug(logPrefix + "Used OSGi bundle manifest information, but scanning for additional resources (taglibs, CNDs, etc)... "); } scanned = processJarInputStream(jarFile.getPath(), externalDependency, packageDirectory, version, optional, parsingContext, logPrefix, scanned, jarInputStream); } finally { jarInputStream.close(); } if (parsingContext.getBundleClassPath().size() > 0) { getLog().debug(logPrefix + "Processing embedded dependencies..."); JarFile jar = new JarFile(jarFile); for (String embeddedJar : parsingContext.getBundleClassPath()) { if (".".equals(embeddedJar)) { continue; } JarEntry jarEntry = jar.getJarEntry(embeddedJar); if (jarEntry != null) { getLog().debug(logPrefix + "Processing embedded JAR..." + jarEntry); InputStream jarEntryInputStream = jar.getInputStream(jarEntry); ByteArrayOutputStream entryOutputStream = new ByteArrayOutputStream(); IOUtils.copy(jarEntryInputStream, entryOutputStream); JarInputStream entryJarInputStream = new JarInputStream( new ByteArrayInputStream(entryOutputStream.toByteArray())); processJarInputStream(jarFile.getPath() + "!" + jarEntry, externalDependency, packageDirectory, version, optional, parsingContext, logPrefix, scanned, entryJarInputStream); IOUtils.closeQuietly(jarEntryInputStream); IOUtils.closeQuietly(entryJarInputStream); } else { getLog().warn(logPrefix + "Couldn't find embedded JAR to parse " + embeddedJar + " in JAR " + jarFile); } } } if (parsingContext.getAdditionalFilesToParse().size() > 0) { getLog().debug(logPrefix + "Processing additional files to parse..."); JarFile jar = new JarFile(jarFile); for (String fileToParse : parsingContext.getAdditionalFilesToParse()) { JarEntry jarEntry = jar.getJarEntry(fileToParse); if (jarEntry != null) { InputStream jarEntryInputStream = jar.getInputStream(jarEntry); ByteArrayOutputStream entryOutputStream = new ByteArrayOutputStream(); IOUtils.copy(jarEntryInputStream, entryOutputStream); if (processNonTldFile(jarEntry.getName(), new ByteArrayInputStream(entryOutputStream.toByteArray()), jarFile.getPath(), optional, version, parsingContext)) { scanned++; } IOUtils.closeQuietly(jarEntryInputStream); } else { getLog().warn(logPrefix + "Couldn't find additional file to parse " + fileToParse + " in JAR " + jarFile); } } parsingContext.clearAdditionalFilesToParse(); } return scanned; }