List of usage examples for java.util.jar JarEntry getName
public String getName()
From source file:org.allcolor.yahp.converter.CClassLoader.java
/** * analyse the content of the given jar file * /*from www . j a v a2 s .c o m*/ * @param jarFile * the jar to analise */ private final void readDirectories(final URL jarFile) { JarInputStream jarIn = null; try { if (!jarFile.getPath().endsWith(".jar")) { return; } if (CClassLoader.sl(CClassLoader.DEBUG)) { CClassLoader.log("opening jar : " + jarFile.toExternalForm(), CClassLoader.DEBUG); } jarIn = new JarInputStream(jarFile.openStream()); JarEntry jarEntry = null; while ((jarEntry = jarIn.getNextJarEntry()) != null) { if (jarEntry.isDirectory()) { continue; } final URL url = new URL("yahpjarloader://" + CBASE64Codec.encode(jarFile.toExternalForm().getBytes("utf-8")).replaceAll("\n", "") + "/" + jarEntry.getName()); if (CClassLoader.sl(CClassLoader.DEBUG)) { CClassLoader.log("found entry : " + url.toString(), CClassLoader.DEBUG); } if (jarEntry.getName().endsWith(".class")) { if (!this.classesMap.containsKey(jarEntry.getName())) { if (!this.booResourceOnly) { this.classesMap.put(jarEntry.getName(), url); } } if (this.resourcesMap.containsKey(jarEntry.getName())) { final Object to = this.resourcesMap.get(jarEntry.getName()); if (to instanceof URL) { final URL uo = (URL) to; final List l = new ArrayList(); l.add(uo); l.add(url); this.resourcesMap.put(jarEntry.getName(), l); } else if (to instanceof List) { final List uo = (List) to; uo.add(url); this.resourcesMap.put(jarEntry.getName(), uo); } } else { this.resourcesMap.put(jarEntry.getName(), url); } } else if (jarEntry.getName().startsWith("native/")) { String system = jarEntry.getName().substring(7); system = system.substring(0, system.indexOf('/')); if (!this.dllMap.containsKey(system)) { this.dllMap.put(system, url); } if (this.resourcesMap.containsKey(jarEntry.getName())) { final Object to = this.resourcesMap.get(jarEntry.getName()); if (to instanceof URL) { final URL uo = (URL) to; final List l = new ArrayList(); l.add(uo); l.add(url); this.resourcesMap.put(jarEntry.getName(), l); } else if (to instanceof List) { final List uo = (List) to; uo.add(url); this.resourcesMap.put(jarEntry.getName(), uo); } } else { this.resourcesMap.put(jarEntry.getName(), url); } } else { if (this.resourcesMap.containsKey(jarEntry.getName())) { final Object to = this.resourcesMap.get(jarEntry.getName()); if (to instanceof URL) { final URL uo = (URL) to; final List l = new ArrayList(); l.add(uo); l.add(url); this.resourcesMap.put(jarEntry.getName(), l); } else if (to instanceof List) { final List uo = (List) to; uo.add(url); this.resourcesMap.put(jarEntry.getName(), uo); } } else { this.resourcesMap.put(jarEntry.getName(), url); } } } if (CClassLoader.sl(CClassLoader.DEBUG)) { CClassLoader.log("opening jar : " + jarFile.getFile().toString() + " done.", CClassLoader.DEBUG); } } catch (final MalformedURLException mue) { mue.printStackTrace(); if (CClassLoader.sl(CClassLoader.FATAL)) { CClassLoader.log(mue.getMessage(), CClassLoader.FATAL); } } catch (final IOException ioe) { ioe.printStackTrace(); if (CClassLoader.sl(CClassLoader.FATAL)) { CClassLoader.log(ioe.getMessage(), CClassLoader.FATAL); } } catch (final Exception e) { e.printStackTrace(); if (CClassLoader.sl(CClassLoader.FATAL)) { CClassLoader.log(e.getMessage(), CClassLoader.FATAL); } } finally { try { jarIn.close(); jarIn = null; } catch (final Exception e) { } } }
From source file:JNLPAppletLauncher.java
/** * Enumerate the list of entries in the jar file and return those that are * the root entries.//w w w.java 2 s .c o m */ private Set/*<String>*/ getRootEntries(JarFile jarFile) { if (VERBOSE) { System.err.println("getRootEntries:"); } Set/*<String>*/ names = new HashSet/*<String>*/(); Enumeration/*<JarEntry>*/ entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); String entryName = entry.getName(); if (VERBOSE) { System.err.println("JarEntry : " + entryName); } // only look at entries with no "/" if (entryName.indexOf('/') == -1 && entryName.indexOf(File.separatorChar) == -1) { names.add(entryName); } } return names; }
From source file:JNLPAppletLauncher.java
/** * Validate the certificates for each native Lib in the jar file. * Throws an IOException if any certificate is not valid. *///w w w. ja va2 s.com private void validateCertificates(JarFile jarFile, Set/*<String>*/ nativeLibNames) throws IOException { if (DEBUG) { System.err.println("validateCertificates:"); } byte[] buf = new byte[1000]; Enumeration/*<JarEntry>*/ entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); String entryName = entry.getName(); if (VERBOSE) { System.err.println("JarEntry : " + entryName); } if (nativeLibNames.contains(entryName)) { if (DEBUG) { System.err.println("VALIDATE: " + entryName); } if (!checkNativeCertificates(jarFile, entry, buf)) { throw new IOException("Cannot validate certificate for " + entryName); } } } }
From source file:JNLPAppletLauncher.java
/** * Extract the specified set of native libraries in the given jar file. */// ww w .ja v a 2 s . c om private void extractNativeLibs(JarFile jarFile, Set/*<String>*/ rootEntries, Set/*<String>*/ nativeLibNames) throws IOException { if (DEBUG) { System.err.println("extractNativeLibs:"); } Enumeration/*<JarEntry>*/ entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); String entryName = entry.getName(); if (VERBOSE) { System.err.println("JarEntry : " + entryName); } // In order to be compatible with Java Web Start, we need // to extract all root entries from the jar file. However, // we only allow direct loading of the previously // discovered native library names. if (rootEntries.contains(entryName)) { // strip prefix & suffix String libName = entryName.substring(nativePrefix.length(), entryName.length() - nativeSuffix.length()); if (DEBUG) { System.err.println("EXTRACT: " + entryName + "(" + libName + ")"); } File nativeLib = new File(nativeTmpDir, entryName); InputStream in = new BufferedInputStream(jarFile.getInputStream(entry)); OutputStream out = new BufferedOutputStream(new FileOutputStream(nativeLib)); int numBytesWritten = copyStream(in, out, -1); in.close(); out.close(); if (nativeLibNames.contains(entryName)) { nativeLibMap.put(libName, nativeLib.getAbsolutePath()); } } } }
From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfiguratorTest.java
@Test public void testUpdateZipfile() throws Exception { // First, set up our zipfile test. // Create a manifest with a random header so that we can ensure it's preserved by the configurator. Manifest mf = new Manifest(); Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR; String mfTestValue = "someCrazyValue"; mf.getMainAttributes().put(mfTestHeader, mfTestValue); // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you // don't add it, your manifest will be blank. mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader)); File testWar = File.createTempFile("JenkinsServiceConfiguratorTest", ".war"); configurator.setWarTemplateFile(testWar.getAbsolutePath()); try {// w w w .ja v a2 s . co m JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf); String specialFileName = "foo/bar.xml"; String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file."; // Make our configurator replace this file within the JAR. configurator.setWebXmlFilename(specialFileName); // Create several random files in the zip. for (int i = 0; i < 10; i++) { JarEntry curEntry = new JarEntry("folder/file" + i); jarOutStream.putNextEntry(curEntry); IOUtils.write(fileContents, jarOutStream); } // Push in our special file now. JarEntry specialEntry = new JarEntry(specialFileName); jarOutStream.putNextEntry(specialEntry); IOUtils.write(fileContents, jarOutStream); // Close the output stream now, time to do the test. jarOutStream.close(); // Configure this configurator with appropriate folders for testing. String expectedHomeDir = "/some/silly/random/homeDir"; String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/"; File webappsTargetDir = new File(webappsTarget); if (webappsTargetDir.exists()) { FileUtils.deleteDirectory(webappsTargetDir); } String expectedDestFile = webappsTarget + "s#test#jenkins.war"; configurator.setTargetJenkinsHomeBaseDir(expectedHomeDir); configurator.setTargetWebappsDir(webappsTarget); configurator.setJenkinsPath("/s/"); ProjectServiceConfiguration config = new ProjectServiceConfiguration(); config.setProjectIdentifier("test123"); Map<String, String> m = new HashMap<String, String>(); m.put(ProjectServiceConfiguration.PROJECT_ID, "test"); m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com"); config.setProperties(m); config.setProjectIdentifier("test"); // Now, run it against our test setup configurator.configure(config); // Confirm that the zipfile was updates as expected. File configuredWar = new File(expectedDestFile); assertTrue(configuredWar.exists()); try { JarFile configuredWarJar = new JarFile(configuredWar); Manifest extractedMF = configuredWarJar.getManifest(); assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader)); // Make sure all of our entries are present, and contain the data we expected. JarEntry curEntry = null; Enumeration<JarEntry> entries = configuredWarJar.entries(); while (entries.hasMoreElements()) { curEntry = entries.nextElement(); // If this is the manifest, skip it. if (curEntry.getName().equals("META-INF/MANIFEST.MF")) { continue; } String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry)); if (curEntry.getName().equals(specialFileName)) { assertFalse(fileContents.equals(entryContents)); assertTrue(entryContents.contains(expectedHomeDir)); } else { // Make sure our content was unchanged. assertEquals(fileContents, entryContents); assertFalse(entryContents.contains(expectedHomeDir)); } } } finally { // Clean up our test file. configuredWar.delete(); } } finally { // Clean up our test file. testWar.delete(); } }
From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfiguratorTest.java
@Test public void testUpdateZipfile() throws Exception { // First, set up our zipfile test. // Create a manifest with a random header so that we can ensure it's preserved by the configurator. Manifest mf = new Manifest(); Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR; String mfTestValue = "someCrazyValue"; mf.getMainAttributes().put(mfTestHeader, mfTestValue); // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you // don't add it, your manifest will be blank. mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader)); File testWar = File.createTempFile("HudsonServiceConfiguratorTest", ".war"); configurator.setWarTemplateFile(testWar.getAbsolutePath()); try {/*w ww .ja v a2 s .c o m*/ JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf); String specialFileName = "foo/bar.xml"; String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file."; // Make our configurator replace this file within the JAR. configurator.setWebXmlFilename(specialFileName); // Create several random files in the zip. for (int i = 0; i < 10; i++) { JarEntry curEntry = new JarEntry("folder/file" + i); jarOutStream.putNextEntry(curEntry); IOUtils.write(fileContents, jarOutStream); } // Push in our special file now. JarEntry specialEntry = new JarEntry(specialFileName); jarOutStream.putNextEntry(specialEntry); IOUtils.write(fileContents, jarOutStream); // Close the output stream now, time to do the test. jarOutStream.close(); // Configure this configurator with appropriate folders for testing. String expectedHomeDir = "/some/silly/random/homeDir"; String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/"; File webappsTargetDir = new File(webappsTarget); if (webappsTargetDir.exists()) { FileUtils.deleteDirectory(webappsTargetDir); } String expectedDestFile = webappsTarget + "s#test#hudson.war"; HudsonWarNamingStrategy warNamingStrategy = new HudsonWarNamingStrategy(); warNamingStrategy.setPathPattern(webappsTarget + "s#%s#hudson.war"); configurator.setHudsonWarNamingStrategy(warNamingStrategy); configurator.setTargetHudsonHomeBaseDir(expectedHomeDir); ProjectServiceConfiguration config = new ProjectServiceConfiguration(); config.setProjectIdentifier("test123"); Map<String, String> m = new HashMap<String, String>(); m.put(ProjectServiceConfiguration.PROJECT_ID, "test"); m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com"); config.setProperties(m); config.setProjectIdentifier("test"); // Now, run it against our test setup configurator.configure(config); // Confirm that the zipfile was updates as expected. File configuredWar = new File(expectedDestFile); assertTrue(configuredWar.exists()); try { JarFile configuredWarJar = new JarFile(configuredWar); Manifest extractedMF = configuredWarJar.getManifest(); assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader)); // Make sure all of our entries are present, and contain the data we expected. JarEntry curEntry = null; Enumeration<JarEntry> entries = configuredWarJar.entries(); while (entries.hasMoreElements()) { curEntry = entries.nextElement(); // If this is the manifest, skip it. if (curEntry.getName().equals("META-INF/MANIFEST.MF")) { continue; } String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry)); if (curEntry.getName().equals(specialFileName)) { assertFalse(fileContents.equals(entryContents)); assertTrue(entryContents.contains(expectedHomeDir)); } else { // Make sure our content was unchanged. assertEquals(fileContents, entryContents); assertFalse(entryContents.contains(expectedHomeDir)); } } } finally { // Clean up our test file. configuredWar.delete(); } } finally { // Clean up our test file. testWar.delete(); } }
From source file:org.lockss.plugin.PluginManager.java
void ensureJarPluginsLoaded(String jarname, Pattern pat) { try {/*from w w w.jav a 2 s. com*/ JarFile jar = new JarFile(jarname); for (Enumeration<JarEntry> en = jar.entries(); en.hasMoreElements();) { JarEntry ent = en.nextElement(); Matcher mat = pat.matcher(ent.getName()); if (mat.matches()) { String membname = mat.group(1); String plugname = membname.replace('/', '.'); String plugkey = pluginKeyFromName(plugname); ensurePluginLoaded(plugkey); } } } catch (IOException e) { log.error("Couldn't open plugin registry jar: " + jarname); } }
From source file:org.apache.catalina.loader.WebappClassLoader.java
/** * Find specified resource in local repositories. * * @return the loaded resource, or null if the resource isn't found *//* w w w. j a va2 s. c o m*/ protected ResourceEntry findResourceInternal(String name, String path) { if (!started) { log.info(sm.getString("webappClassLoader.stopped")); return null; } if ((name == null) || (path == null)) return null; ResourceEntry entry = (ResourceEntry) resourceEntries.get(name); if (entry != null) return entry; int contentLength = -1; InputStream binaryStream = null; int jarFilesLength = jarFiles.length; int repositoriesLength = repositories.length; int i; Resource resource = null; for (i = 0; (entry == null) && (i < repositoriesLength); i++) { try { String fullPath = repositories[i] + path; Object lookupResult = resources.lookup(fullPath); if (lookupResult instanceof Resource) { resource = (Resource) lookupResult; } // Note : Not getting an exception here means the resource was // found if (securityManager != null) { PrivilegedAction dp = new PrivilegedFindResource(files[i], path); entry = (ResourceEntry) AccessController.doPrivileged(dp); } else { entry = findResourceInternal(files[i], path); } ResourceAttributes attributes = (ResourceAttributes) resources.getAttributes(fullPath); contentLength = (int) attributes.getContentLength(); entry.lastModified = attributes.getLastModified(); if (resource != null) { try { binaryStream = resource.streamContent(); } catch (IOException e) { return null; } // Register the full path for modification checking // Note: Only syncing on a 'constant' object is needed synchronized (allPermission) { int j; long[] result2 = new long[lastModifiedDates.length + 1]; for (j = 0; j < lastModifiedDates.length; j++) { result2[j] = lastModifiedDates[j]; } result2[lastModifiedDates.length] = entry.lastModified; lastModifiedDates = result2; String[] result = new String[paths.length + 1]; for (j = 0; j < paths.length; j++) { result[j] = paths[j]; } result[paths.length] = fullPath; paths = result; } } } catch (NamingException e) { } } if ((entry == null) && (notFoundResources.containsKey(name))) return null; JarEntry jarEntry = null; synchronized (jarFiles) { openJARs(); for (i = 0; (entry == null) && (i < jarFilesLength); i++) { jarEntry = jarFiles[i].getJarEntry(path); if (jarEntry != null) { entry = new ResourceEntry(); try { entry.codeBase = getURL(jarRealFiles[i]); String jarFakeUrl = getURI(jarRealFiles[i]).toString(); jarFakeUrl = "jar:" + jarFakeUrl + "!/" + path; entry.source = new URL(jarFakeUrl); entry.lastModified = jarRealFiles[i].lastModified(); } catch (MalformedURLException e) { return null; } contentLength = (int) jarEntry.getSize(); try { entry.manifest = jarFiles[i].getManifest(); binaryStream = jarFiles[i].getInputStream(jarEntry); } catch (IOException e) { return null; } // Extract resources contained in JAR to the workdir if (!(path.endsWith(".class"))) { byte[] buf = new byte[1024]; File resourceFile = new File(loaderDir, jarEntry.getName()); if (!resourceFile.exists()) { Enumeration entries = jarFiles[i].entries(); while (entries.hasMoreElements()) { JarEntry jarEntry2 = (JarEntry) entries.nextElement(); if (!(jarEntry2.isDirectory()) && (!jarEntry2.getName().endsWith(".class"))) { resourceFile = new File(loaderDir, jarEntry2.getName()); // No need to check mkdirs result because an // IOException will occur anyway resourceFile.getParentFile().mkdirs(); FileOutputStream os = null; InputStream is = null; try { is = jarFiles[i].getInputStream(jarEntry2); os = new FileOutputStream(resourceFile); while (true) { int n = is.read(buf); if (n <= 0) { break; } os.write(buf, 0, n); } } catch (IOException e) { // Ignore } finally { try { if (is != null) { is.close(); } } catch (IOException e) { } try { if (os != null) { os.close(); } } catch (IOException e) { } } } } } } } } if (entry == null) { synchronized (notFoundResources) { notFoundResources.put(name, name); } return null; } if (binaryStream != null) { byte[] binaryContent = new byte[contentLength]; try { int pos = 0; while (true) { int n = binaryStream.read(binaryContent, pos, binaryContent.length - pos); if (n <= 0) break; pos += n; } binaryStream.close(); } catch (IOException e) { e.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); return null; } entry.binaryContent = binaryContent; // The certificates are only available after the JarEntry // associated input stream has been fully read if (jarEntry != null) { entry.certificates = jarEntry.getCertificates(); } } } // Add the entry in the local resource repository synchronized (resourceEntries) { // Ensures that all the threads which may be in a race to load // a particular class all end up with the same ResourceEntry // instance ResourceEntry entry2 = (ResourceEntry) resourceEntries.get(name); if (entry2 == null) { resourceEntries.put(name, entry); } else { entry = entry2; } } return entry; }
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 a2 s.c om*/ 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; }