List of usage examples for java.util.jar JarFile getInputStream
public synchronized InputStream getInputStream(ZipEntry ze) throws IOException
From source file:org.rhq.plugins.jbossas.JBossASServerComponent.java
/** * Parse the passed war file, try to read an enclosed jboss-web.xml and look for * virtual-hosts in it. If found, return one virtual host name. Else return localhost. * @param warFile File pointer pointing to a .war file * @return The name of a defined virtual host or localhost *//*from www. j a v a2s . c o m*/ private String getVhostFromWarFile(File warFile) { JarFile jfile = null; InputStream is = null; try { jfile = new JarFile(warFile); JarEntry entry = jfile.getJarEntry("WEB-INF/jboss-web.xml"); if (entry != null) { is = jfile.getInputStream(entry); SAXBuilder saxBuilder = new SAXBuilder(); SelectiveSkippingEntityResolver entityResolver = SelectiveSkippingEntityResolver .getDtdAndXsdSkippingInstance(); saxBuilder.setEntityResolver(entityResolver); Document doc = saxBuilder.build(is); Element root = doc.getRootElement(); // <jboss-web> List<Element> vHosts = root.getChildren("virtual-host"); if (vHosts == null || vHosts.isEmpty()) { if (log.isDebugEnabled()) log.debug("No vhosts found in war file, using " + LOCALHOST); return LOCALHOST; } // So we have vhost, just return one of them, this is enough Element vhost = vHosts.get(0); return vhost.getText(); } } catch (Exception ioe) { log.warn("Exception when getting vhost from war file : " + ioe.getMessage()); } finally { if (jfile != null) { if (is != null) { try { // see http://bugs.sun.com/view_bug.do?bug_id=6735255 for why we do this is.close(); } catch (IOException e) { log.info("Exception when trying to close the war file stream: " + e.getMessage()); } } try { jfile.close(); } catch (IOException e) { log.info("Exception when trying to close the war file: " + e.getMessage()); } } } // We're not able to determine a vhost, so return localhost return LOCALHOST; }
From source file:nl.geodienstencentrum.maven.plugin.sass.AbstractSassMojo.java
/** * Extract the Bourbon assets to the build directory. * @param destinationDir directory for the Bourbon resources *///from w w w.ja v a2s . co m private void extractBourbonResources(String destinationDir) { final Log log = this.getLog(); try { File destDir = new File(destinationDir); if (destDir.isDirectory()) { // skip extracting Bourbon, as it seems to hav been done log.info("Bourbon resources seems to have been extracted before."); return; } log.info("Extracting Bourbon resources to: " + destinationDir); destDir.mkdirs(); // find the jar with the Bourbon directory in the classloader URL urlJar = this.getClass().getClassLoader().getResource("scss-report.xsl"); String resourceFilePath = urlJar.getFile(); int index = resourceFilePath.indexOf("!"); String jarFileURI = resourceFilePath.substring(0, index); File jarFile = new File(new URI(jarFileURI)); JarFile jar = new JarFile(jarFile); // extract app/assets/stylesheets to destinationDir for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements();) { JarEntry entry = enums.nextElement(); if (entry.getName().contains("app/assets/stylesheets")) { // shorten the path a bit index = entry.getName().indexOf("app/assets/stylesheets"); String fileName = destinationDir + File.separator + entry.getName().substring(index); File f = new File(fileName); if (fileName.endsWith("/")) { f.mkdirs(); } else { FileOutputStream fos = new FileOutputStream(f); try { IOUtil.copy(jar.getInputStream(entry), fos); } finally { IOUtil.close(fos); } } } } } catch (IOException | URISyntaxException ex) { log.error("Error extracting Bourbon resources.", ex); } }
From source file:au.com.addstar.objects.Plugin.java
/** * Adds the Spigot.ver file to the jar//from w w w.j a v a 2 s .c om * * @param ver */ public void addSpigotVer(String ver) { if (latestFile == null) return; File newFile = new File(latestFile.getParentFile(), SpigotUpdater.getFormat().format(Calendar.getInstance().getTime()) + "-" + ver + "-s.jar"); File spigotFile = new File(latestFile.getParentFile(), "spigot.ver"); if (spigotFile.exists()) FileUtils.deleteQuietly(spigotFile); try { JarFile oldjar = new JarFile(latestFile); if (oldjar.getEntry("spigot.ver") != null) return; JarOutputStream tempJarOutputStream = new JarOutputStream(new FileOutputStream(newFile)); try (Writer wr = new FileWriter(spigotFile); BufferedWriter writer = new BufferedWriter(wr)) { writer.write(ver); writer.newLine(); } try (FileInputStream stream = new FileInputStream(spigotFile)) { byte[] buffer = new byte[1024]; int bytesRead = 0; JarEntry je = new JarEntry(spigotFile.getName()); tempJarOutputStream.putNextEntry(je); while ((bytesRead = stream.read(buffer)) != -1) { tempJarOutputStream.write(buffer, 0, bytesRead); } stream.close(); } Enumeration jarEntries = oldjar.entries(); while (jarEntries.hasMoreElements()) { JarEntry entry = (JarEntry) jarEntries.nextElement(); InputStream entryInputStream = oldjar.getInputStream(entry); tempJarOutputStream.putNextEntry(entry); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = entryInputStream.read(buffer)) != -1) { tempJarOutputStream.write(buffer, 0, bytesRead); } entryInputStream.close(); } tempJarOutputStream.close(); oldjar.close(); FileUtils.deleteQuietly(latestFile); FileUtils.deleteQuietly(spigotFile); FileUtils.moveFile(newFile, latestFile); latestFile = newFile; } catch (ZipException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.wso2.carbon.mss.examples.petstore.security.ldap.server.ApacheDirectoryServerActivator.java
private void copyResources() throws IOException, EmbeddingLDAPException { final File jarFile = new File( this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()); final String repositoryDirectory = "repository"; final File destinationRoot = new File(getCarbonHome()); //Check whether ladap configs are already configured File repository = new File(getCarbonHome() + File.separator + repositoryDirectory); if (!repository.exists()) { JarFile jar = null; try {//from www.ja va2 s.co m jar = new JarFile(jarFile); final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); // Skip if the entry is not about the 'repository' directory. if (!entry.getName().startsWith(repositoryDirectory)) { continue; } // If the entry is a directory create the relevant directory in the destination. File destination = new File(destinationRoot, entry.getName()); if (entry.isDirectory()) { if (destination.mkdirs()) { continue; } } InputStream in = null; OutputStream out = null; try { // If the entry is a file, copy the file to the destination in = jar.getInputStream(entry); out = new FileOutputStream(destination); IOUtils.copy(in, out); IOUtils.closeQuietly(in); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } } } finally { if (jar != null) { jar.close(); } } } }
From source file:org.jasig.portal.plugin.deployer.AbstractExtractingEarDeployer.java
/** * Reads the specified {@link JarEntry} from the {@link JarFile} assuming that the * entry represents another a JAR file. The files in the {@link JarEntry} will be * extracted using the contextDir as the base directory. * //from w w w . j a v a 2 s.co m * @param earFile The JarEntry for the JAR to read from the archive. * @param earEntry The JarFile to get the {@link InputStream} for the file from. * @param contextDir The directory to extract the JAR to. * @throws IOException If the extracting of data from the JarEntry fails. */ protected void extractWar(JarFile earFile, final JarEntry earEntry, final File contextDir) throws MojoFailureException { if (this.getLogger().isInfoEnabled()) { this.getLogger().info("Extracting EAR entry '" + earFile.getName() + "!" + earEntry.getName() + "' to '" + contextDir + "'"); } if (!contextDir.exists()) { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("Creating context directory entry '" + contextDir + "'"); } try { FileUtils.forceMkdir(contextDir); } catch (IOException e) { throw new MojoFailureException("Failed to create '" + contextDir + "' to extract '" + earEntry.getName() + "' out of '" + earFile.getName() + "' into", e); } } JarInputStream warInputStream = null; try { warInputStream = new JarInputStream(earFile.getInputStream(earEntry)); // Write out the MANIFEST.MF file to the target directory Manifest manifest = warInputStream.getManifest(); if (manifest != null) { FileOutputStream manifestFileOutputStream = null; try { final File manifestFile = new File(contextDir, MANIFEST_PATH); manifestFile.getParentFile().mkdirs(); manifestFileOutputStream = new FileOutputStream(manifestFile); manifest.write(manifestFileOutputStream); } catch (Exception e) { this.getLogger().error("Failed to copy the MANIFEST.MF file for ear entry '" + earEntry.getName() + "' out of '" + earFile.getName() + "'", e); throw new MojoFailureException("Failed to copy the MANIFEST.MF file for ear entry '" + earEntry.getName() + "' out of '" + earFile.getName() + "'", e); } finally { try { if (manifestFileOutputStream != null) { manifestFileOutputStream.close(); } } catch (Exception e) { this.getLogger().warn("Error closing the OutputStream for MANIFEST.MF in warEntry: " + earEntry.getName()); } } } JarEntry warEntry; while ((warEntry = warInputStream.getNextJarEntry()) != null) { final File warEntryFile = new File(contextDir, warEntry.getName()); if (warEntry.isDirectory()) { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("Creating WAR directory entry '" + earEntry.getName() + "!" + warEntry.getName() + "' as '" + warEntryFile + "'"); } FileUtils.forceMkdir(warEntryFile); } else { if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("Extracting WAR entry '" + earEntry.getName() + "!" + warEntry.getName() + "' to '" + warEntryFile + "'"); } FileUtils.forceMkdir(warEntryFile.getParentFile()); final FileOutputStream jarEntryFileOutputStream = new FileOutputStream(warEntryFile); try { IOUtils.copy(warInputStream, jarEntryFileOutputStream); } finally { IOUtils.closeQuietly(jarEntryFileOutputStream); } } } } catch (IOException e) { throw new MojoFailureException("Failed to extract EAR entry '" + earEntry.getName() + "' out of '" + earFile.getName() + "' to '" + contextDir + "'", e); } finally { IOUtils.closeQuietly(warInputStream); } }
From source file:org.pepstock.jem.util.ReverseURLClassLoader.java
/** * Returns an input stream to a given resource in the given file which may * either be a directory or a jar file. */*from w ww. j ava2 s.c om*/ * @param url the file (directory or jar) in which to search for the * resource. Must not be <code>null</code>. * @param resourceName The name of the resource for which a stream is * required. Must not be <code>null</code>. * * @return a stream to the required resource or <code>null</code> if * the resource cannot be found in the given file. */ private InputStream getResourceStream(URL url, String resourceName) { JarFile jFile = null; try { // gets the file from URL File file = new File(url.toURI()); // if is a directory, then checks on the file system // where URL id the parent file and resource name is the file if (file.isDirectory()) { File resource = new File(file, resourceName); // checks if exists if (resource.exists()) { // returns inpu stream return new FileInputStream(resource); } } else if (file.exists()) { // if here, the URL must be a link to a JAR file jFile = new JarFile(file); // searches in the JAR for the resource name JarEntry entry = jFile.getJarEntry(resourceName); // if found return the JAR InputStream if (entry != null) { // FINDBUGS: it's correct do not close the jar file // otherwise the stream will be closed InputStream resourceIS = jFile.getInputStream(entry); // reads input stream in byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); return copy(jFile, resourceIS, baos); } // close always the jar file jFile.close(); } } catch (Exception e) { LogAppl.getInstance().ignore(e.getMessage(), e); } return null; }
From source file:edu.stanford.muse.email.JarDocCache.java
public void exportAsMbox(String outFilename, String prefix, Collection<EmailDocument> selectedDocs, boolean append) throws IOException, GeneralSecurityException, ClassNotFoundException { PrintWriter mbox = new PrintWriter(new FileOutputStream("filename", append)); Map<Integer, Document> allHeadersMap = getAllHeaders(prefix); Map<Integer, Document> selectedHeadersMap = new LinkedHashMap<Integer, Document>(); Set<EmailDocument> selectedDocsSet = new LinkedHashSet<EmailDocument>(selectedDocs); for (Integer I : allHeadersMap.keySet()) { EmailDocument ed = (EmailDocument) allHeadersMap.get(I); if (selectedDocsSet.contains(ed)) selectedHeadersMap.put(I, ed); }/*from ww w . j a v a 2s. c o m*/ JarFile contentJar = null; try { contentJar = new JarFile(baseDir + File.separator + prefix + ".contents"); } catch (Exception e) { Util.print_exception(e, log); return; } Enumeration<JarEntry> contentEntries = contentJar.entries(); String suffix = ".content"; while (contentEntries.hasMoreElements()) { JarEntry c_je = contentEntries.nextElement(); String s = c_je.getName(); if (!s.endsWith(suffix)) continue; int index = -1; String idx_str = s.substring(0, s.length() - suffix.length()); try { index = Integer.parseInt(idx_str); } catch (Exception e) { log.error("Funny file in header: " + index); } EmailDocument ed = (EmailDocument) selectedHeadersMap.get(index); if (ed == null) continue; // not selected byte[] b = Util.getBytesFromStream(contentJar.getInputStream(c_je)); String contents = new String(b, "UTF-8"); EmailUtils.printHeaderToMbox(ed, mbox); EmailUtils.printBodyAndAttachmentsToMbox(contents, ed, mbox, null); mbox.println(contents); } }
From source file:org.ebayopensource.turmeric.tools.library.builders.CodeGenTypeLibraryGenerator.java
private static void deleteTheGeneratedDependentTypesForV3(String dependentJarPath, TypeLibraryCodeGenContext codeGenCtx) { if (TypeLibraryUtilities.isEmptyString(dependentJarPath)) return;//from w ww . ja va 2 s .c o m String[] dependentLibrariesJarPaths = dependentJarPath.split(DEPENDENT_JARS_DELIMITER); if (dependentLibrariesJarPaths.length == 0) return; //identify the possible java types to be deleted List<String> javaTypesToDelete = new ArrayList<String>(); //Need to check if ObjectFactory is being deleted. //One ObjectFactory per library.Need to get a set of all namespaces being referred. Set<String> dependentLibsNamespace = new HashSet<String>(); for (String currDepLibraryJar : dependentLibrariesJarPaths) { String currLibraryName = getLibraryNameFromJarFilePath(currDepLibraryJar); //for referred libraries the TypeInformation.xml from the related jar . this jar won't be available in classpath and hence has to be mnaually processed String typeInformationFileRelativePath = TypeLibraryConstants.META_INF_FOLDER + File.separator + currLibraryName + File.separator + TypeLibraryConstants.TYPE_INFORMATION_FILE_NAME; File theJarFile = new File(currDepLibraryJar); if (!theJarFile.exists()) continue; JarFile jarFile = null; try { jarFile = new JarFile(currDepLibraryJar); JarEntry entry = jarFile.getJarEntry(typeInformationFileRelativePath); if (entry == null) entry = jarFile.getJarEntry(typeInformationFileRelativePath.replace("\\", "/")); if (entry == null) { getLogger().log(Level.WARNING, "Could not find the TypeInformation.xml file for the dependent library represented by the jar : " + currDepLibraryJar); continue; } InputStream inputStream = jarFile.getInputStream(entry); if (inputStream != null) { TypeLibraryType typeLibraryType = JAXB.unmarshal(inputStream, TypeLibraryType.class); if (typeLibraryType != null) { dependentLibsNamespace.add(typeLibraryType.getLibraryNamespace()); for (TypeInformationType typeInformationType : typeLibraryType.getType()) javaTypesToDelete.add(typeInformationType.getJavaTypeName()); } } } catch (IOException e) { getLogger().log(Level.WARNING, "Exception while parsing the TypeInformation.xml of jar " + currDepLibraryJar, e); } } deleteJavaTypes(javaTypesToDelete, codeGenCtx); findPackageForObjectFactoriesAndDelete(codeGenCtx, dependentLibsNamespace); }
From source file:org.apache.catalina.startup.TldConfig.java
/** * Scans all TLD entries in the given JAR for application listeners. * * @param file JAR file whose TLD entries are scanned for application * listeners// w w w . j a v a2 s .co m */ private void tldScanJar(File file) throws Exception { JarFile jarFile = null; String name = null; String jarPath = file.getAbsolutePath(); try { jarFile = new JarFile(file); Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); name = entry.getName(); if (!name.startsWith("META-INF/")) { continue; } if (!name.endsWith(".tld")) { continue; } if (log.isTraceEnabled()) { log.trace(" Processing TLD at '" + name + "'"); } try { tldScanStream(new InputSource(jarFile.getInputStream(entry))); } catch (Exception e) { log.error(sm.getString("contextConfig.tldEntryException", name, jarPath, context.getPath()), e); } } } catch (Exception e) { log.error(sm.getString("contextConfig.tldJarException", jarPath, context.getPath()), e); } finally { if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { // Ignore } } } }
From source file:org.owasp.dependencycheck.analyzer.JarAnalyzer.java
/** * Retrieves the specified POM from a jar file and converts it to a Model. * * @param path the path to the pom.xml file within the jar file * @param jar the jar file to extract the pom from * @param dependency the dependency being analyzed * @return returns the POM object//from w w w .ja v a 2 s. c om * @throws AnalysisException is thrown if there is an exception extracting * or parsing the POM {@link org.owasp.dependencycheck.xml.pom.Model} object */ private Model extractPom(String path, JarFile jar, Dependency dependency) throws AnalysisException { InputStream input = null; FileOutputStream fos = null; final File tmpDir = getNextTempDirectory(); final File file = new File(tmpDir, "pom.xml"); try { final ZipEntry entry = jar.getEntry(path); input = jar.getInputStream(entry); fos = new FileOutputStream(file); IOUtils.copy(input, fos); dependency.setActualFilePath(file.getAbsolutePath()); } catch (IOException ex) { LOGGER.warn("An error occurred reading '{}' from '{}'.", path, dependency.getFilePath()); LOGGER.error("", ex); } finally { closeStream(fos); closeStream(input); } return PomUtils.readPom(file); }