List of usage examples for java.util.jar JarEntry getName
public String getName()
From source file:org.apache.tajo.catalog.store.XMLCatalogSchemaManager.java
protected String[] listJarResources(URL dirURL, FilenameFilter filter) throws IOException, URISyntaxException { String[] files = new String[0]; String spec = dirURL.getFile(); int seperator = spec.indexOf("!/"); if (seperator == -1) { return files; }/*from w w w . j a v a 2 s. co m*/ URL jarFileURL = new URL(spec.substring(0, seperator)); Set<String> filesSet = new HashSet<>(); try (JarFile jarFile = new JarFile(jarFileURL.toURI().getPath())) { Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; } String entryName = entry.getName(); if (entryName.indexOf(schemaPath) > -1 && filter.accept(null, entryName)) { filesSet.add(entryName); } } } if (!filesSet.isEmpty()) { files = new String[filesSet.size()]; files = filesSet.toArray(files); } return files; }
From source file:com.opensymphony.xwork2.util.finder.ClassFinder.java
private List<String> jar(JarInputStream jarStream) throws IOException { List<String> classNames = new ArrayList<String>(); JarEntry entry; while ((entry = jarStream.getNextJarEntry()) != null) { if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; }/* ww w .java 2s. c o m*/ String className = entry.getName(); className = className.replaceFirst(".class$", ""); //war files are treated as .jar files, so takeout WEB-INF/classes className = StringUtils.removeStart(className, "WEB-INF/classes/"); className = className.replace('/', '.'); classNames.add(className); } return classNames; }
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; }/*w ww .j a v a2 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:spring.osgi.io.OsgiBundleResourcePatternResolver.java
/** * Checks the jar entries from the Bundle-Classpath for the given pattern. * * @param list paths/* w w w.j a va 2s. c o m*/ * @param url url * @param pattern pattern */ private void findBundleClassPathMatchingJarEntries(List<String> list, URL url, String pattern) throws IOException { // get the stream to the resource and read it as a jar JarInputStream jis = new JarInputStream(url.openStream()); Set<String> result = new LinkedHashSet<>(8); boolean patternWithFolderSlash = pattern.startsWith(FOLDER_SEPARATOR); // parse the jar and do pattern matching try { while (jis.available() > 0) { JarEntry jarEntry = jis.getNextJarEntry(); // if the jar has ended, the entry can be null (on Sun JDK at least) if (jarEntry != null) { String entryPath = jarEntry.getName(); // check if leading "/" is needed or not (it depends how the jar was created) if (entryPath.startsWith(FOLDER_SEPARATOR)) { if (!patternWithFolderSlash) { entryPath = entryPath.substring(FOLDER_SEPARATOR.length()); } } else { if (patternWithFolderSlash) { entryPath = FOLDER_SEPARATOR.concat(entryPath); } } if (getPathMatcher().match(pattern, entryPath)) { result.add(entryPath); } } } } finally { try { jis.close(); } catch (IOException io) { // ignore it - nothing we can't do about it } } if (logger.isTraceEnabled()) logger.trace("Found in nested jar [" + url + "] matching entries " + result); list.addAll(result); }
From source file:org.eclipse.gemini.blueprint.io.OsgiBundleResourcePatternResolver.java
/** * Checks the jar entries from the Bundle-Classpath for the given pattern. * //w w w . java 2 s. co m * @param list * @param ur */ private void findBundleClassPathMatchingJarEntries(List<String> list, URL url, String pattern) throws IOException { // get the stream to the resource and read it as a jar JarInputStream jis = new JarInputStream(url.openStream()); Set<String> result = new LinkedHashSet<String>(8); boolean patternWithFolderSlash = pattern.startsWith(FOLDER_SEPARATOR); // parse the jar and do pattern matching try { while (jis.available() > 0) { JarEntry jarEntry = jis.getNextJarEntry(); // if the jar has ended, the entry can be null (on Sun JDK at least) if (jarEntry != null) { String entryPath = jarEntry.getName(); // check if leading "/" is needed or not (it depends how the jar was created) if (entryPath.startsWith(FOLDER_SEPARATOR)) { if (!patternWithFolderSlash) { entryPath = entryPath.substring(FOLDER_SEPARATOR.length()); } } else { if (patternWithFolderSlash) { entryPath = FOLDER_SEPARATOR.concat(entryPath); } } if (getPathMatcher().match(pattern, entryPath)) { result.add(entryPath); } } } } finally { try { jis.close(); } catch (IOException io) { // ignore it - nothing we can't do about it } } if (logger.isTraceEnabled()) logger.trace("Found in nested jar [" + url + "] matching entries " + result); list.addAll(result); }
From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java
/** * Sign a JAR file outputting the signed JAR to a different file. * * @param jarFile/* w w w . j a v a 2s . c o m*/ * JAR file to sign * @param signedJarFile * Output file for signed JAR * @param privateKey * Private key to sign with * @param certificateChain * Certificate chain for private key * @param signatureType * Signature type * @param signatureName * Signature name * @param signer * Signer * @param digestType * Digest type * @param tsaUrl * TSA URL * @throws IOException * If an I/O problem occurs while signing the JAR file * @throws CryptoException * If a crypto problem occurs while signing the JAR file */ public static void sign(File jarFile, File signedJarFile, PrivateKey privateKey, X509Certificate[] certificateChain, SignatureType signatureType, String signatureName, String signer, DigestType digestType, String tsaUrl, Provider provider) throws IOException, CryptoException { JarFile jar = null; JarOutputStream jos = null; try { // Replace illegal characters in signature name signatureName = convertSignatureName(signatureName); // Create Jar File accessor for JAR to be signed jar = new JarFile(jarFile); // Write manifest content to here StringBuilder sbManifest = new StringBuilder(); // Write out main attributes to manifest String manifestMainAttrs = getManifestMainAttrs(jar, signer); sbManifest.append(manifestMainAttrs); // Write out all entries' attributes to manifest String entryManifestAttrs = getManifestEntriesAttrs(jar); if (entryManifestAttrs.length() > 0) { // Only output if there are any sbManifest.append(entryManifestAttrs); sbManifest.append(CRLF); } // Write signature file to here StringBuilder sbSf = new StringBuilder(); // Write out digests to manifest and signature file // Sign each JAR entry... for (Enumeration<?> jarEntries = jar.entries(); jarEntries.hasMoreElements();) { JarEntry jarEntry = (JarEntry) jarEntries.nextElement(); if (!jarEntry.isDirectory()) // Ignore directories { if (!ignoreJarEntry(jarEntry)) // Ignore some entries (existing signature files) { // Get the digest of the entry as manifest attributes String manifestEntry = getDigestManifestAttrs(jar, jarEntry, digestType); // Add it to the manifest string buffer sbManifest.append(manifestEntry); // Get the digest of manifest entries created above byte[] mdSf = DigestUtil.getMessageDigest(manifestEntry.getBytes(), digestType); byte[] mdSf64 = Base64.encode(mdSf); String mdSf64Str = new String(mdSf64); // Write this digest as entries in signature file sbSf.append(createAttributeText(NAME_ATTR, jarEntry.getName())); sbSf.append(CRLF); sbSf.append(createAttributeText(MessageFormat.format(DIGEST_ATTR, digestType.jce()), mdSf64Str)); sbSf.append(CRLF); sbSf.append(CRLF); } } } // Manifest file complete - get base 64 encoded digest of its content for inclusion in signature file byte[] manifest = sbManifest.toString().getBytes(); byte[] digestMf = DigestUtil.getMessageDigest(manifest, digestType); String digestMfStr = new String(Base64.encode(digestMf)); // Get base 64 encoded digest of manifest's main attributes for inclusion in signature file byte[] mainfestMainAttrs = manifestMainAttrs.getBytes(); byte[] digestMfMainAttrs = DigestUtil.getMessageDigest(mainfestMainAttrs, digestType); String digestMfMainAttrsStr = new String(Base64.encode(digestMfMainAttrs)); // Write out Manifest Digest, Created By and Signature Version to start of signature file sbSf.insert(0, CRLF); sbSf.insert(0, CRLF); sbSf.insert(0, createAttributeText(MessageFormat.format(DIGEST_MANIFEST_ATTR, digestType.jce()), digestMfStr)); sbSf.insert(0, CRLF); sbSf.insert(0, createAttributeText( MessageFormat.format(DIGEST_MANIFEST_MAIN_ATTRIBUTES_ATTR, digestType.jce()), digestMfMainAttrsStr)); sbSf.insert(0, CRLF); sbSf.insert(0, createAttributeText(CREATED_BY_ATTR, signer)); sbSf.insert(0, CRLF); sbSf.insert(0, createAttributeText(SIGNATURE_VERSION_ATTR, SIGNATURE_VERSION)); // Signature file complete byte[] sf = sbSf.toString().getBytes(); // Create output stream to write signed JAR jos = new JarOutputStream(new FileOutputStream(signedJarFile)); // Write JAR files from JAR to be signed to signed JAR writeJarEntries(jar, jos, signatureName); // Write manifest to signed JAR writeManifest(manifest, jos); // Write signature file to signed JAR writeSignatureFile(sf, signatureName, jos); // Create signature block and write it out to signed JAR byte[] sigBlock = createSignatureBlock(sf, privateKey, certificateChain, signatureType, tsaUrl, provider); writeSignatureBlock(sigBlock, signatureType, signatureName, jos); } finally { IOUtils.closeQuietly(jar); IOUtils.closeQuietly(jos); } }
From source file:org.eclipse.wb.internal.core.editor.palette.dialogs.ImportArchiveDialog.java
private List<PaletteElementInfo> extractElementsFromJarAllClasses(JarInputStream jarStream) throws Exception { // load all classes List<PaletteElementInfo> elements = Lists.newArrayList(); try {//from w ww .j ava2 s . c o m while (true) { JarEntry jarEntry = jarStream.getNextJarEntry(); if (jarEntry == null) { break; } String jarEntryName = jarEntry.getName(); if (jarEntryName.endsWith(JAVA_BEAN_CLASS_SUFFIX)) { // convert 'aaa/bbb/ccc.class' to 'aaa.bbb.ccc' PaletteElementInfo element = new PaletteElementInfo(); element.className = StringUtils.substringBeforeLast(jarEntryName, JAVA_BEAN_CLASS_SUFFIX) .replace('/', '.'); element.name = CodeUtils.getShortClass(element.className); elements.add(element); } } } catch (Throwable e) { DesignerPlugin.log(e); } // sort element over class name Collections.sort(elements, new Comparator<PaletteElementInfo>() { public int compare(PaletteElementInfo element0, PaletteElementInfo element1) { return element0.className.compareToIgnoreCase(element1.className); } }); return elements; }
From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java
/** * Find all resources in jar files that match the given location pattern * via the Ant-style PathMatcher./* ww w.j av a 2s.co m*/ * @param rootDirResource the root directory as Resource * @param rootDirURL the pre-resolved root directory URL * @param subPattern the sub pattern to match (below the root directory) * @return a mutable Set of matching Resource instances * @throws IOException in case of I/O errors * @since 4.3 * @see java.net.JarURLConnection * @see org.springframework.util.PathMatcher */ protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, URL rootDirURL, String subPattern) throws IOException { URLConnection con = rootDirURL.openConnection(); JarFile jarFile; String jarFileUrl; String rootEntryPath; boolean closeJarFile; if (con instanceof JarURLConnection) { // Should usually be the case for traditional JAR files. JarURLConnection jarCon = (JarURLConnection) con; ResourceUtils.useCachesIfNecessary(jarCon); jarFile = jarCon.getJarFile(); jarFileUrl = jarCon.getJarFileURL().toExternalForm(); JarEntry jarEntry = jarCon.getJarEntry(); rootEntryPath = (jarEntry != null ? jarEntry.getName() : ""); closeJarFile = !jarCon.getUseCaches(); } else { // No JarURLConnection -> need to resort to URL file parsing. // We'll assume URLs of the format "jar:path!/entry", with the protocol // being arbitrary as long as following the entry format. // We'll also handle paths with and without leading "file:" prefix. String urlFile = rootDirURL.getFile(); try { int separatorIndex = urlFile.indexOf(ResourceUtils.WAR_URL_SEPARATOR); if (separatorIndex == -1) { separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR); } if (separatorIndex != -1) { jarFileUrl = urlFile.substring(0, separatorIndex); rootEntryPath = urlFile.substring(separatorIndex + 2); // both separators are 2 chars jarFile = getJarFile(jarFileUrl); } else { jarFile = new JarFile(urlFile); jarFileUrl = urlFile; rootEntryPath = ""; } closeJarFile = true; } catch (ZipException ex) { if (logger.isDebugEnabled()) { logger.debug("Skipping invalid jar classpath entry [" + urlFile + "]"); } return Collections.emptySet(); } } try { if (logger.isDebugEnabled()) { logger.debug("Looking for matching resources in jar file [" + jarFileUrl + "]"); } if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) { // Root entry path must end with slash to allow for proper matching. // The Sun JRE does not return a slash here, but BEA JRockit does. rootEntryPath = rootEntryPath + "/"; } Set<Resource> result = new LinkedHashSet<>(8); for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) { JarEntry entry = entries.nextElement(); String entryPath = entry.getName(); if (entryPath.startsWith(rootEntryPath)) { String relativePath = entryPath.substring(rootEntryPath.length()); if (getPathMatcher().match(subPattern, relativePath)) { result.add(rootDirResource.createRelative(relativePath)); } } } return result; } finally { if (closeJarFile) { jarFile.close(); } } }
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 {// w ww. jav a 2s. co 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:org.schemaspy.Config.java
public static Set<String> getBuiltInDatabaseTypes(String loadedFromJar) { Set<String> databaseTypes = new TreeSet<>(); JarInputStream jar = null;//w ww . j av a 2s .c om try { jar = new JarInputStream(new FileInputStream(loadedFromJar)); JarEntry entry; while ((entry = jar.getNextJarEntry()) != null) { String entryName = entry.getName(); if (entryName.indexOf("types") != -1) { int dotPropsIndex = entryName.indexOf(".properties"); if (dotPropsIndex != -1) databaseTypes.add(entryName.substring(0, dotPropsIndex)); } } } catch (IOException exc) { } finally { if (jar != null) { try { jar.close(); } catch (IOException ignore) { } } } return databaseTypes; }