List of usage examples for java.util.jar JarFile entries
public Enumeration<JarEntry> entries()
From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfigurator.java
@Override public void configure(ProjectServiceConfiguration configuration) { // Get a reference to our template WAR, and make sure it exists. File hudsonTemplateWar = new File(warTemplateFile); if (!hudsonTemplateWar.exists() || !hudsonTemplateWar.isFile()) { String message = "The given Hudson template WAR [" + hudsonTemplateWar + "] either did not exist or was not a file!"; LOG.error(message);/*w ww. j a v a 2s . com*/ throw new IllegalStateException(message); } String deployLocation = hudsonWarNamingStrategy.getWarFilePath(configuration); File hudsonDeployFile = new File(deployLocation); if (hudsonDeployFile.exists()) { String message = "When trying to deploy new WARfile [" + hudsonDeployFile.getAbsolutePath() + "] a file or directory with that name already existed! Continuing with provisioning."; LOG.info(message); return; } try { // Get a reference to our template war JarFile hudsonTemplateWarJar = new JarFile(hudsonTemplateWar); // Extract our web.xml from this war JarEntry webXmlEntry = hudsonTemplateWarJar.getJarEntry(webXmlFilename); String webXmlContents = IOUtils.toString(hudsonTemplateWarJar.getInputStream(webXmlEntry)); // Update the web.xml to contain the correct HUDSON_HOME value String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration); File tempDirFile = new File(tempDir); if (!tempDirFile.exists()) { tempDirFile.mkdirs(); } // Put the web.xml back into the war File updatedHudsonWar = File.createTempFile("hudson", ".war", tempDirFile); JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedHudsonWar), hudsonTemplateWarJar.getManifest()); // Loop through our existing zipfile and add in all of the entries to it except for our web.xml JarEntry curEntry = null; Enumeration<JarEntry> entries = hudsonTemplateWarJar.entries(); while (entries.hasMoreElements()) { curEntry = entries.nextElement(); // If this is the manifest, skip it. if (curEntry.getName().equals("META-INF/MANIFEST.MF")) { continue; } if (curEntry.getName().equals(webXmlEntry.getName())) { JarEntry newEntry = new JarEntry(curEntry.getName()); jarOutStream.putNextEntry(newEntry); // Substitute our edited entry content. IOUtils.write(updatedXml, jarOutStream); } else { jarOutStream.putNextEntry(curEntry); IOUtils.copy(hudsonTemplateWarJar.getInputStream(curEntry), jarOutStream); } } // Clean up our resources. jarOutStream.close(); // Move the war into it's deployment location so that it can be picked up and deployed by Tomcat. FileUtils.moveFile(updatedHudsonWar, hudsonDeployFile); } catch (IOException ioe) { // Log this exception and rethrow wrapped in a RuntimeException LOG.error(ioe.getMessage()); throw new RuntimeException(ioe); } }
From source file:org.owasp.dependencycheck.analyzer.JarAnalyzer.java
/** * Searches a JarFile for pom.xml entries and returns a listing of these * entries.//from ww w . ja v a2s . co m * * @param jar the JarFile to search * @return a list of pom.xml entries * @throws IOException thrown if there is an exception reading a JarEntry */ private List<String> retrievePomListing(final JarFile jar) throws IOException { final List<String> pomEntries = new ArrayList<String>(); final Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); final String entryName = (new File(entry.getName())).getName().toLowerCase(); if (!entry.isDirectory() && "pom.xml".equals(entryName)) { LOGGER.trace("POM Entry found: {}", entry.getName()); pomEntries.add(entry.getName()); } } return pomEntries; }
From source file:net.rim.ejde.internal.packaging.PackagingManager.java
/** * Checks if a jar file is a MidletJar created by rapc. * * @param f//from w ww. j a va 2 s. c o m * @return */ static public int getJarFileType(File f) { int type = 0x0; if (!f.exists()) { return type; } java.util.jar.JarFile jar = null; try { jar = new java.util.jar.JarFile(f, false); java.util.jar.Manifest manifest = jar.getManifest(); if (manifest != null) { java.util.jar.Attributes attributes = manifest.getMainAttributes(); String profile = attributes.getValue("MicroEdition-Profile"); if (profile != null) { if ("MIDP-1.0".equals(profile) || "MIDP-2.0".equals(profile)) { type = type | MIDLET_JAR; } } } Enumeration<JarEntry> entries = jar.entries(); JarEntry entry; String entryName; InputStream is = null; IClassFileReader classFileReader = null; // check the attribute of the class files in the jar file for (; entries.hasMoreElements();) { entry = entries.nextElement(); entryName = entry.getName(); if (entryName.endsWith(IConstants.CLASS_FILE_EXTENSION_WITH_DOT)) { is = jar.getInputStream(entry); classFileReader = ToolFactory.createDefaultClassFileReader(is, IClassFileReader.ALL); if (isEvisceratedClass(classFileReader)) { type = type | EVISCERATED_JAR; break; } } } } catch (IOException e) { _log.error(e.getMessage()); } finally { try { if (jar != null) { jar.close(); } } catch (IOException e) { _log.error(e.getMessage()); } } return type; }
From source file:org.owasp.dependencycheck.analyzer.JarAnalyzer.java
/** * Cycles through an enumeration of JarEntries, contained within the * dependency, and returns a list of the class names. This does not include * core Java package names (i.e. java.* or javax.*). * * @param dependency the dependency being analyzed * @return an list of fully qualified class names *///from www . j a va 2s . com private List<ClassNameInformation> collectClassNames(Dependency dependency) { final List<ClassNameInformation> classNames = new ArrayList<ClassNameInformation>(); JarFile jar = null; try { jar = new JarFile(dependency.getActualFilePath()); final Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); final String name = entry.getName().toLowerCase(); //no longer stripping "|com\\.sun" - there are some com.sun jar files with CVEs. if (name.endsWith(".class") && !name.matches("^javax?\\..*$")) { final ClassNameInformation className = new ClassNameInformation( name.substring(0, name.length() - 6)); classNames.add(className); } } } catch (IOException ex) { LOGGER.warn("Unable to open jar file '{}'.", dependency.getFileName()); LOGGER.debug("", ex); } finally { if (jar != null) { try { jar.close(); } catch (IOException ex) { LOGGER.trace("", ex); } } } return classNames; }
From source file:org.apache.axis2.jaxws.util.WSDL4JWrapper.java
private URL getURLFromJAR(URLClassLoader urlLoader, URL relativeURL) { URL[] urlList = null;/*from www. j av a 2s . co m*/ ResourceFinderFactory rff = (ResourceFinderFactory) MetadataFactoryRegistry .getFactory(ResourceFinderFactory.class); ResourceFinder cf = rff.getResourceFinder(); if (log.isDebugEnabled()) { log.debug("ResourceFinderFactory: " + rff.getClass().getName()); log.debug("ResourceFinder: " + cf.getClass().getName()); } urlList = cf.getURLs(urlLoader); if (urlList == null) { if (log.isDebugEnabled()) { log.debug("No URL's found in URL ClassLoader"); } throw ExceptionFactory.makeWebServiceException(Messages.getMessage("WSDL4JWrapperErr1")); } for (URL url : urlList) { if ("file".equals(url.getProtocol())) { // Insure that Windows spaces are properly handled in the URL final File f = new File(url.getPath().replaceAll("%20", " ")); // If file is not of type directory then its a jar file if (isAFile(f)) { try { JarFile jf = (JarFile) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws IOException { return new JarFile(f); } }); Enumeration<JarEntry> entries = jf.entries(); // read all entries in jar file and return the first // wsdl file that matches // the relative path while (entries.hasMoreElements()) { JarEntry je = entries.nextElement(); String name = je.getName(); if (name.endsWith(".wsdl")) { String relativePath = relativeURL.getPath(); if (relativePath.endsWith(name)) { String path = f.getAbsolutePath(); // This check is necessary because Unix/Linux file paths begin // with a '/'. When adding the prefix 'jar:file:/' we may end // up with '//' after the 'file:' part. This causes the URL // object to treat this like a remote resource if (path != null && path.indexOf("/") == 0) { path = path.substring(1, path.length()); } URL absoluteUrl = new URL("jar:file:/" + path + "!/" + je.getName()); return absoluteUrl; } } } } catch (Exception e) { throw ExceptionFactory.makeWebServiceException(e); } } } } return null; }
From source file:com.rapidminer.tools.Tools.java
public static void findImplementationsInJar(ClassLoader loader, JarFile jar, Class<?> superClass, List<String> implementations) { Enumeration<JarEntry> e = jar.entries(); while (e.hasMoreElements()) { JarEntry entry = e.nextElement(); String name = entry.getName(); int dotClass = name.lastIndexOf(".class"); if (dotClass < 0) { continue; }/*from w w w. j av a 2 s . c om*/ name = name.substring(0, dotClass); name = name.replaceAll("/", "\\."); try { Class<?> c = loader.loadClass(name); if (superClass.isAssignableFrom(c)) { if (!java.lang.reflect.Modifier.isAbstract(c.getModifiers())) { implementations.add(name); } } } catch (Throwable t) { } } }
From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfigurator.java
@Override public void configure(ProjectServiceConfiguration configuration) { // Get a reference to our template WAR, and make sure it exists. File jenkinsTemplateWar = new File(warTemplateFile); if (!jenkinsTemplateWar.exists() || !jenkinsTemplateWar.isFile()) { String message = "The given Jenkins template WAR [" + jenkinsTemplateWar + "] either did not exist or was not a file!"; LOG.error(message);/*from w w w. java 2s . c om*/ throw new IllegalStateException(message); } String pathProperty = perOrg ? configuration.getOrganizationIdentifier() : configuration.getProjectIdentifier(); String deployedUrl = configuration.getProperties().get(ProjectServiceConfiguration.PROFILE_BASE_URL) + jenkinsPath + pathProperty + "/jenkins/"; deployedUrl.replace("//", "/"); URL deployedJenkinsUrl; try { deployedJenkinsUrl = new URL(deployedUrl); } catch (MalformedURLException e) { throw new RuntimeException(e); } String webappName = deployedJenkinsUrl.getPath(); if (webappName.startsWith("/")) { webappName = webappName.substring(1); } if (webappName.endsWith("/")) { webappName = webappName.substring(0, webappName.length() - 1); } webappName = webappName.replace("/", "#"); webappName = webappName + ".war"; // Calculate our final filename. String deployLocation = targetWebappsDir + webappName; File jenkinsDeployFile = new File(deployLocation); if (jenkinsDeployFile.exists()) { String message = "When trying to deploy new WARfile [" + jenkinsDeployFile.getAbsolutePath() + "] a file or directory with that name already existed! Continuing with provisioning."; LOG.info(message); return; } try { // Get a reference to our template war JarFile jenkinsTemplateWarJar = new JarFile(jenkinsTemplateWar); // Extract our web.xml from this war JarEntry webXmlEntry = jenkinsTemplateWarJar.getJarEntry(webXmlFilename); String webXmlContents = IOUtils.toString(jenkinsTemplateWarJar.getInputStream(webXmlEntry)); // Update the web.xml to contain the correct JENKINS_HOME value String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration); File tempDirFile = new File(tempDir); if (!tempDirFile.exists()) { tempDirFile.mkdirs(); } // Put the web.xml back into the war File updatedJenkinsWar = File.createTempFile("jenkins", ".war", tempDirFile); JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedJenkinsWar), jenkinsTemplateWarJar.getManifest()); // Loop through our existing zipfile and add in all of the entries to it except for our web.xml JarEntry curEntry = null; Enumeration<JarEntry> entries = jenkinsTemplateWarJar.entries(); while (entries.hasMoreElements()) { curEntry = entries.nextElement(); // If this is the manifest, skip it. if (curEntry.getName().equals("META-INF/MANIFEST.MF")) { continue; } if (curEntry.getName().equals(webXmlEntry.getName())) { JarEntry newEntry = new JarEntry(curEntry.getName()); jarOutStream.putNextEntry(newEntry); // Substitute our edited entry content. IOUtils.write(updatedXml, jarOutStream); } else { jarOutStream.putNextEntry(curEntry); IOUtils.copy(jenkinsTemplateWarJar.getInputStream(curEntry), jarOutStream); } } // Clean up our resources. jarOutStream.close(); // Move the war into its deployment location so that it can be picked up and deployed by the app server. FileUtils.moveFile(updatedJenkinsWar, jenkinsDeployFile); } catch (IOException ioe) { // Log this exception and rethrow wrapped in a RuntimeException LOG.error(ioe.getMessage()); throw new RuntimeException(ioe); } }
From source file:UnpackedJarFile.java
public static void copyToPackedJar(JarFile inputJar, File outputFile) throws IOException { if (inputJar.getClass() == JarFile.class) { // this is a plain old jar... nothign special copyFile(new File(inputJar.getName()), outputFile); } else if (inputJar instanceof NestedJarFile && ((NestedJarFile) inputJar).isPacked()) { NestedJarFile nestedJarFile = (NestedJarFile) inputJar; JarFile baseJar = nestedJarFile.getBaseJar(); String basePath = nestedJarFile.getBasePath(); if (baseJar instanceof UnpackedJarFile) { // our target jar is just a file in upacked jar (a plain old directory)... now // we just need to find where it is and copy it to the outptu copyFile(((UnpackedJarFile) baseJar).getFile(basePath), outputFile); } else {//from w w w .j av a 2 s . c om // out target is just a plain old jar file directly accessabel from the file system copyFile(new File(baseJar.getName()), outputFile); } } else { // copy out the module contents to a standalone jar file (entry by entry) JarOutputStream out = null; try { out = new JarOutputStream(new FileOutputStream(outputFile)); byte[] buffer = new byte[4096]; Enumeration entries = inputJar.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); InputStream in = inputJar.getInputStream(entry); try { out.putNextEntry(new ZipEntry(entry.getName())); try { int count; while ((count = in.read(buffer)) > 0) { out.write(buffer, 0, count); } } finally { out.closeEntry(); } } finally { close(in); } } } finally { close(out); } } }
From source file:com.vectorcast.plugins.vectorcastexecution.VectorCASTSetup.java
/** * Perform the build step. Copy the scripts from the archive/directory to the workspace * @param build build//from ww w. j a v a 2 s. c om * @param workspace workspace * @param launcher launcher * @param listener listener */ @Override public void perform(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener) { FilePath destScriptDir = new FilePath(workspace, "vc_scripts"); JarFile jFile = null; try { String path = null; String override_path = System.getenv("VCAST_VC_SCRIPTS"); String extra_script_path = SCRIPT_DIR; Boolean directDir = false; if (override_path != null && !override_path.isEmpty()) { path = override_path; extra_script_path = ""; directDir = true; String msg = "VectorCAST - overriding vc_scripts. Copying from '" + path + "'"; Logger.getLogger(VectorCASTSetup.class.getName()).log(Level.ALL, msg); } else { path = VectorCASTSetup.class.getProtectionDomain().getCodeSource().getLocation().getPath(); path = URLDecoder.decode(path, "utf-8"); } File testPath = new File(path); if (testPath.isFile()) { // Have jar file... jFile = new JarFile(testPath); Enumeration<JarEntry> entries = jFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().startsWith("scripts")) { String fileOrDir = entry.getName().substring(8); // length of scripts/ FilePath dest = new FilePath(destScriptDir, fileOrDir); if (entry.getName().endsWith("/")) { // Directory, create destination dest.mkdirs(); } else { // File, copy it InputStream is = VectorCASTSetup.class.getResourceAsStream("/" + entry.getName()); dest.copyFrom(is); } } } } else { // Have directory File scriptDir = new File(path + extra_script_path); processDir(scriptDir, "./", destScriptDir, directDir); } } catch (IOException ex) { Logger.getLogger(VectorCASTSetup.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(VectorCASTSetup.class.getName()).log(Level.SEVERE, null, ex); } finally { if (jFile != null) { try { jFile.close(); } catch (IOException ex) { // Ignore } } } }