List of usage examples for java.util.jar JarEntry getName
public String getName()
From source file:org.opencms.setup.CmsUpdateBean.java
/** * Preloads classes from the same jar file as a given class.<p> * // ww w .j av a 2s . co m * @param cls the class for which the classes from the same jar file should be loaded */ public void preload(Class<?> cls) { try { File jar = new File(cls.getProtectionDomain().getCodeSource().getLocation().getFile()); java.util.jar.JarFile jarfile = new JarFile(jar); try { Enumeration<JarEntry> entries = jarfile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (name.endsWith(".class")) { String className = name.replaceFirst("\\.class$", ""); className = className.replace('/', '.'); try { Class.forName(className); } catch (VirtualMachineError e) { throw e; } catch (Throwable e) { LOG.error(e.getLocalizedMessage(), e); } } } } finally { jarfile.close(); } } catch (VirtualMachineError e) { throw e; } catch (Throwable e) { LOG.error(e.getLocalizedMessage(), e); } }
From source file:org.apache.archiva.rest.services.DefaultBrowseService.java
protected List<ArtifactContentEntry> readFileEntries(File file, String filterPath, String repoId) throws IOException { Map<String, ArtifactContentEntry> artifactContentEntryMap = new HashMap<>(); int filterDepth = StringUtils.countMatches(filterPath, "/"); /*if ( filterDepth == 0 ) {/* www . j a v a2 s . c o m*/ filterDepth = 1; }*/ JarFile jarFile = new JarFile(file); try { Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries(); while (jarEntryEnumeration.hasMoreElements()) { JarEntry currentEntry = jarEntryEnumeration.nextElement(); String cleanedEntryName = StringUtils.endsWith(currentEntry.getName(), "/") ? // StringUtils.substringBeforeLast(currentEntry.getName(), "/") : currentEntry.getName(); String entryRootPath = getRootPath(cleanedEntryName); int depth = StringUtils.countMatches(cleanedEntryName, "/"); if (StringUtils.isEmpty(filterPath) // && !artifactContentEntryMap.containsKey(entryRootPath) // && depth == filterDepth) { artifactContentEntryMap.put(entryRootPath, new ArtifactContentEntry(entryRootPath, !currentEntry.isDirectory(), depth, repoId)); } else { if (StringUtils.startsWith(cleanedEntryName, filterPath) // && (depth == filterDepth || (!currentEntry.isDirectory() && depth == filterDepth))) { artifactContentEntryMap.put(cleanedEntryName, new ArtifactContentEntry(cleanedEntryName, !currentEntry.isDirectory(), depth, repoId)); } } } if (StringUtils.isNotEmpty(filterPath)) { Map<String, ArtifactContentEntry> filteredArtifactContentEntryMap = new HashMap<>(); for (Map.Entry<String, ArtifactContentEntry> entry : artifactContentEntryMap.entrySet()) { filteredArtifactContentEntryMap.put(entry.getKey(), entry.getValue()); } List<ArtifactContentEntry> sorted = getSmallerDepthEntries(filteredArtifactContentEntryMap); if (sorted == null) { return Collections.emptyList(); } Collections.sort(sorted, ArtifactContentEntryComparator.INSTANCE); return sorted; } } finally { if (jarFile != null) { jarFile.close(); } } List<ArtifactContentEntry> sorted = new ArrayList<>(artifactContentEntryMap.values()); Collections.sort(sorted, ArtifactContentEntryComparator.INSTANCE); return sorted; }
From source file:org.hyperic.hq.product.server.session.PluginManagerImpl.java
private void processJarEntries(JarFile jarFile, String jarFilename, String filename) throws PluginDeployException, IOException { final Map<String, JDOMException> xmlFailures = new HashMap<String, JDOMException>(); boolean hasPluginRootElement = false; final Enumeration<JarEntry> entries = jarFile.entries(); final Map<String, Reader> xmlReaders = getXmlReaderMap(jarFile); while (entries.hasMoreElements()) { Reader reader = null;/* w w w .ja va2 s .c om*/ String currXml = null; try { final JarEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; } if (!entry.getName().toLowerCase().endsWith(".xml")) { continue; } currXml = entry.getName(); reader = xmlReaders.get(currXml); final Document doc = getDocument(reader, xmlReaders); if (doc.getRootElement().getName().toLowerCase().equals("plugin")) { hasPluginRootElement = true; } currXml = null; } catch (JDOMException e) { log.debug(e, e); xmlFailures.put(currXml, e); } } if (!hasPluginRootElement) { final File toRemove = new File(jarFilename); if (toRemove != null && toRemove.exists()) { toRemove.delete(); } if (!xmlFailures.isEmpty()) { for (final Entry<String, JDOMException> entry : xmlFailures.entrySet()) { final String xml = entry.getKey(); JDOMException ex = entry.getValue(); log.error("could not parse " + xml, ex); } throw new PluginDeployException("plugin.manager.file.xml.wellformed.error", xmlFailures.keySet().toString()); } else { throw new PluginDeployException("plugin.manager.no.plugin.root.element", filename); } } }
From source file:catalina.startup.ContextConfig.java
/** * Scan the JAR file at the specified resource path for TLDs in the * <code>META-INF</code> subdirectory, and scan them for application * event listeners that need to be registered. * * @param resourcePath Resource path of the JAR file to scan * * @exception Exception if an exception occurs while scanning this JAR *///from w w w. j a va2 s. c o m private void tldScanJar(String resourcePath) throws Exception { if (debug >= 1) { log(" Scanning JAR at resource path '" + resourcePath + "'"); } JarFile jarFile = null; String name = null; InputStream inputStream = null; try { URL url = context.getServletContext().getResource(resourcePath); if (url == null) { throw new IllegalArgumentException(sm.getString("contextConfig.tldResourcePath", resourcePath)); } url = new URL("jar:" + url.toString() + "!/"); JarURLConnection conn = (JarURLConnection) url.openConnection(); conn.setUseCaches(false); jarFile = conn.getJarFile(); 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 (debug >= 2) { log(" Processing TLD at '" + name + "'"); } inputStream = jarFile.getInputStream(entry); tldScanStream(inputStream); inputStream.close(); inputStream = null; name = null; } // FIXME - Closing the JAR file messes up the class loader??? // jarFile.close(); } catch (Exception e) { if (name == null) { throw new ServletException(sm.getString("contextConfig.tldJarException", resourcePath), e); } else { throw new ServletException(sm.getString("contextConfig.tldEntryException", name, resourcePath), e); } } finally { if (inputStream != null) { try { inputStream.close(); } catch (Throwable t) { ; } inputStream = null; } if (jarFile != null) { // FIXME - Closing the JAR file messes up the class loader??? // try { // jarFile.close(); // } catch (Throwable t) { // ; // } jarFile = null; } } }
From source file:com.paniclauncher.workers.InstanceInstaller.java
public void deleteMetaInf() { File inputFile = getMinecraftJar(); File outputTmpFile = new File(App.settings.getTempDir(), pack.getSafeName() + "-minecraft.jar"); try {/*ww w . ja v a 2 s . co m*/ JarInputStream input = new JarInputStream(new FileInputStream(inputFile)); JarOutputStream output = new JarOutputStream(new FileOutputStream(outputTmpFile)); JarEntry entry; while ((entry = input.getNextJarEntry()) != null) { if (entry.getName().contains("META-INF")) { continue; } output.putNextEntry(entry); byte buffer[] = new byte[1024]; int amo; while ((amo = input.read(buffer, 0, 1024)) != -1) { output.write(buffer, 0, amo); } output.closeEntry(); } input.close(); output.close(); inputFile.delete(); outputTmpFile.renameTo(inputFile); } catch (IOException e) { App.settings.getConsole().logStackTrace(e); } }
From source file:org.jahia.utils.maven.plugin.osgi.BuildFrameworkPackageListMojo.java
private void scanJar(Map<String, Map<String, Map<String, VersionLocation>>> packageVersionCounts, File jarFile, String defaultVersion) throws IOException { JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile)); Manifest jarManifest = jarInputStream.getManifest(); // Map<String, String> manifestVersions = new HashMap<String,String>(); String specificationVersion = null; if (jarManifest == null) { getLog().warn("No MANIFEST.MF file found for dependency " + jarFile); } else {//from ww w.j ava 2 s .c om if (jarManifest.getMainAttributes() == null) { getLog().warn("No main attributes found in MANIFEST.MF file found for dependency " + jarFile); } else { specificationVersion = jarManifest.getMainAttributes().getValue("Specification-Version"); if (defaultVersion == null) { if (jarManifest.getMainAttributes().getValue("Bundle-Version") != null) { } else if (specificationVersion != null) { defaultVersion = specificationVersion; } else { defaultVersion = jarManifest.getMainAttributes().getValue("Implementation-Version"); } } String exportPackageHeaderValue = jarManifest.getMainAttributes().getValue("Export-Package"); if (exportPackageHeaderValue != null) { ManifestElement[] manifestElements = new ManifestElement[0]; try { manifestElements = ManifestElement.parseHeader("Export-Package", exportPackageHeaderValue); } catch (BundleException e) { getLog().warn("Error while parsing Export-Package header value for jar " + jarFile, e); } for (ManifestElement manifestElement : manifestElements) { String[] packageNames = manifestElement.getValueComponents(); String version = manifestElement.getAttribute("version"); for (String packageName : packageNames) { updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(), version, version, packageName); } } } for (Map.Entry<String, Attributes> manifestEntries : jarManifest.getEntries().entrySet()) { String packageName = manifestEntries.getKey().replaceAll("/", "."); if (packageName.endsWith(".class")) { continue; } if (packageName.endsWith(".")) { packageName = packageName.substring(0, packageName.length() - 1); } if (packageName.endsWith(".*")) { packageName = packageName.substring(0, packageName.length() - 1); } int lastDotPos = packageName.lastIndexOf("."); String lastPackage = packageName; if (lastDotPos > -1) { lastPackage = packageName.substring(lastDotPos + 1); } if (lastPackage.length() > 0 && Character.isUpperCase(lastPackage.charAt(0))) { // ignore non package version continue; } if (StringUtils.isEmpty(packageName) || packageName.startsWith("META-INF") || packageName.startsWith("OSGI-INF") || packageName.startsWith("OSGI-OPT") || packageName.startsWith("WEB-INF") || packageName.startsWith("org.osgi")) { // ignore private package names continue; } String packageVersion = null; if (manifestEntries.getValue().getValue("Specification-Version") != null) { packageVersion = manifestEntries.getValue().getValue("Specification-Version"); } else { packageVersion = manifestEntries.getValue().getValue("Implementation-Version"); } if (packageVersion != null) { getLog().info("Found package version in " + jarFile.getName() + " MANIFEST : " + packageName + " v" + packageVersion); updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(), packageVersion, specificationVersion, packageName); // manifestVersions.put(packageName, packageVersion); } } } } JarEntry jarEntry = null; // getLog().debug("Processing file " + artifact.getFile() + "..."); while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { if (!jarEntry.isDirectory()) { String entryName = jarEntry.getName(); String entryPackage = ""; int lastSlash = entryName.lastIndexOf("/"); if (lastSlash > -1) { entryPackage = entryName.substring(0, lastSlash); entryPackage = entryPackage.replaceAll("/", "."); if (StringUtils.isNotEmpty(entryPackage) && !entryPackage.startsWith("META-INF") && !entryPackage.startsWith("OSGI-INF") && !entryPackage.startsWith("OSGI-OPT") && !entryPackage.startsWith("WEB-INF") && !entryPackage.startsWith("org.osgi")) { updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(), defaultVersion, specificationVersion, entryPackage); } } } } jarInputStream.close(); }
From source file:org.kepler.kar.KARFile.java
/** * Returns only valid KAREntries contained in this KARFile. To get all of * the JarEntries use the entries() method. * /*from ww w.ja v a 2 s . c o m*/ * @return List<KAREntry> of all valid KAREntries in this KARFile. */ public List<KAREntry> karEntries() { if (isDebugging) log.debug("karEntries()"); Enumeration<JarEntry> entries = entries(); Vector<KAREntry> karEntries = new Vector<KAREntry>(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (isDebugging) log.debug(entry.getName()); if (entry.getName().equals("MANIFEST.MF") || entry.getName().equals("META-INF/") || entry.getName().equals(JarFile.MANIFEST_NAME)) { // skip manifest entries } else { KAREntry karEntry = new KAREntry(entry); if (karEntry.isValid()) { if (isDebugging) log.debug("karEntry.isValid() == true"); karEntries.add(karEntry); } else { if (isDebugging) log.debug("karEntry.isValid() == false"); } } } return karEntries; }
From source file:UnpackedJarFile.java
public Enumeration entries() { if (isClosed) { throw new IllegalStateException("NestedJarFile is closed"); }//from w w w. j a v a2 s. c o m Collection baseEntries = Collections.list(baseJar.entries()); Collection entries = new LinkedList(); for (Iterator iterator = baseEntries.iterator(); iterator.hasNext();) { JarEntry baseEntry = (JarEntry) iterator.next(); String path = baseEntry.getName(); if (path.startsWith(basePath)) { entries.add(new NestedJarEntry(path.substring(basePath.length()), baseEntry, getManifestSafe())); } } return Collections.enumeration(entries); }
From source file:org.apache.openejb.config.DeploymentLoader.java
public static Map<String, URL> getWebDescriptors(final File warFile) throws IOException { final Map<String, URL> descriptors = new TreeMap<String, URL>(); // xbean resource finder has a bug when you use any uri but "META-INF" // and the jar file does not contain a directory entry for the uri if (warFile.isFile()) { // only to discover module type so xml file filtering is enough final URL jarURL = new URL("jar", "", -1, warFile.toURI().toURL() + "!/"); try {/*from w w w. ja v a 2 s . c o m*/ final JarFile jarFile = new JarFile(warFile); for (final JarEntry entry : Collections.list(jarFile.entries())) { final String entryName = entry.getName(); if (!entry.isDirectory() && entryName.startsWith("WEB-INF/") && (KNOWN_DESCRIPTORS.contains(entryName.substring("WEB-INF/".length())) || entryName.endsWith(".xml"))) { // + web.xml, web-fragment.xml... descriptors.put(entryName, new URL(jarURL, entry.getName())); } } } catch (final IOException e) { // most likely an invalid jar file } } else if (warFile.isDirectory()) { final File webInfDir = new File(warFile, "WEB-INF"); if (webInfDir.isDirectory()) { final File[] files = webInfDir.listFiles(); if (files != null) { for (final File file : files) { if (!file.isDirectory()) { descriptors.put(file.getName(), file.toURI().toURL()); } } } } // handle some few file(s) which can be in META-INF too final File webAppDdDir = new File(webInfDir, "classes/" + ddDir); if (webAppDdDir.isDirectory()) { final File[] files = webAppDdDir.listFiles(); if (files != null) { for (final File file : files) { final String name = file.getName(); if (!descriptors.containsKey(name)) { descriptors.put(name, file.toURI().toURL()); } else { logger.warning("Can't have a " + name + " in WEB-INF and WEB-INF/classes/META-INF, second will be ignored"); } } } } } return descriptors; }
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 va 2 s .c om*/ * * @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; }