List of usage examples for java.util.jar JarInputStream getNextJarEntry
public JarEntry getNextJarEntry() throws IOException
From source file:com.speed.ob.api.ClassStore.java
public void dump(File in, File out, Config config) throws IOException { if (in.isDirectory()) { for (ClassNode node : nodes()) { String[] parts = node.name.split("\\."); String dirName = node.name.substring(0, node.name.lastIndexOf(".")); dirName = dirName.replace(".", "/"); File dir = new File(out, dirName); if (!dir.exists()) { if (!dir.mkdirs()) throw new IOException("Could not make output dir: " + dir.getAbsolutePath()); }// w w w .ja v a2s. c o m ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); node.accept(writer); byte[] data = writer.toByteArray(); FileOutputStream fOut = new FileOutputStream( new File(dir, node.name.substring(node.name.lastIndexOf(".") + 1))); fOut.write(data); fOut.flush(); fOut.close(); } } else if (in.getName().endsWith(".jar")) { File output = new File(out, in.getName()); JarFile jf = new JarFile(in); HashMap<JarEntry, Object> existingData = new HashMap<>(); if (output.exists()) { try { JarInputStream jarIn = new JarInputStream(new FileInputStream(output)); JarEntry entry; while ((entry = jarIn.getNextJarEntry()) != null) { if (!entry.isDirectory()) { byte[] data = IOUtils.toByteArray(jarIn); existingData.put(entry, data); jarIn.closeEntry(); } } jarIn.close(); } catch (IOException e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Could not read existing output file, overwriting", e); } } FileOutputStream fout = new FileOutputStream(output); Manifest manifest = null; if (jf.getManifest() != null) { manifest = jf.getManifest(); if (!config.getBoolean("ClassNameTransform.keep_packages") && config.getBoolean("ClassNameTransform.exclude_mains")) { manifest = new Manifest(manifest); if (manifest.getMainAttributes().getValue("Main-Class") != null) { String manifestName = manifest.getMainAttributes().getValue("Main-Class"); if (manifestName.contains(".")) { manifestName = manifestName.substring(manifestName.lastIndexOf(".") + 1); manifest.getMainAttributes().putValue("Main-Class", manifestName); } } } } jf.close(); JarOutputStream jarOut = manifest == null ? new JarOutputStream(fout) : new JarOutputStream(fout, manifest); Logger.getLogger(getClass().getName()).fine("Restoring " + existingData.size() + " existing files"); if (!existingData.isEmpty()) { for (Map.Entry<JarEntry, Object> entry : existingData.entrySet()) { Logger.getLogger(getClass().getName()).fine("Restoring " + entry.getKey().getName()); jarOut.putNextEntry(entry.getKey()); jarOut.write((byte[]) entry.getValue()); jarOut.closeEntry(); } } for (ClassNode node : nodes()) { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); node.accept(writer); byte[] data = writer.toByteArray(); int index = node.name.lastIndexOf("/"); String fileName; if (index > 0) { fileName = node.name.substring(0, index + 1).replace(".", "/"); fileName += node.name.substring(index + 1).concat(".class"); } else { fileName = node.name.concat(".class"); } JarEntry entry = new JarEntry(fileName); jarOut.putNextEntry(entry); jarOut.write(data); jarOut.closeEntry(); } jarOut.close(); } else { if (nodes().size() == 1) { File outputFile = new File(out, in.getName()); ClassNode node = nodes().iterator().next(); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); byte[] data = writer.toByteArray(); FileOutputStream stream = new FileOutputStream(outputFile); stream.write(data); stream.close(); } } }
From source file:streaming.common.HdfsClassLoader.java
/** * Search for the class in the configured jar file stored in HDFS. * * {@inheritDoc}/* w w w. j av a 2 s. c o m*/ */ @Override public Class findClass(String className) throws ClassNotFoundException { String classPath = convertNameToPath(className); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Searching for class %s (%s) in path %s", className, classPath, this.jar)); } FileSystem fs = null; JarInputStream jarIn = null; try { fs = this.jar.getFileSystem(this.configuration); jarIn = new JarInputStream(fs.open(this.jar)); JarEntry currentEntry = null; while ((currentEntry = jarIn.getNextJarEntry()) != null) { if (LOG.isTraceEnabled()) { LOG.trace(String.format("Comparing %s to entry %s", classPath, currentEntry.getName())); } if (currentEntry.getName().equals(classPath)) { byte[] classBytes = readEntry(jarIn); return defineClass(className, classBytes, 0, classBytes.length); } } } catch (IOException ioe) { throw new ClassNotFoundException("Unable to find " + className + " in path " + this.jar, ioe); } finally { closeQuietly(jarIn); // While you would think it would be prudent to close the filesystem that you opened, // it turns out that this filesystem is shared with HBase, so when you close this one, // it becomes closed for HBase, too. Therefore, there is no call to closeQuietly(fs); } throw new ClassNotFoundException("Unable to find " + className + " in path " + this.jar); }
From source file:com.flexive.shared.FxDropApplication.java
/** * Load text resources packaged with the drop. * * @param pathPrefix a path prefix (e.g. "scripts/") * @return a map of filename (relative to the drop application package) -> file contents * @throws java.io.IOException on I/O errors * @since 3.1//from w w w .j a v a2 s.c om */ public Map<String, String> loadTextResources(String pathPrefix) throws IOException { if (pathPrefix == null) { pathPrefix = ""; } else if (pathPrefix.startsWith("/")) { pathPrefix = pathPrefix.substring(1); } if (isJarProtocol) { // read directly from jar file final Map<String, String> result = Maps.newHashMap(); final JarInputStream stream = getJarStream(); try { JarEntry entry; while ((entry = stream.getNextJarEntry()) != null) { if (!entry.isDirectory() && entry.getName().startsWith(pathPrefix)) { try { result.put(entry.getName(), FxSharedUtils.readFromJarEntry(stream, entry)); } catch (Exception e) { if (LOG.isTraceEnabled()) { LOG.trace( "Failed to read text JAR entry " + entry.getName() + ": " + e.getMessage(), e); } // ignore, continue reading } } } return result; } finally { FxSharedUtils.close(stream); } } else { // read from filesystem final List<File> files = FxFileUtils.listRecursive(new File(resourceURL + File.separator + pathPrefix)); final Map<String, String> result = Maps.newHashMapWithExpectedSize(files.size()); for (File file : files) { try { result.put(StringUtils.replace(file.getPath(), resourceURL + File.separator, ""), FxSharedUtils.loadFile(file)); } catch (Exception e) { if (LOG.isTraceEnabled()) { LOG.trace("Failed to read text file " + file.getPath() + ": " + e.getMessage(), e); } } } return result; } }
From source file:io.squark.nestedjarclassloader.Module.java
private void addResource0(URL url) throws IOException { if (url.getPath().endsWith(".jar")) { if (logger != null) logger.debug("Adding jar " + url.getPath()); InputStream urlStream = url.openStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(urlStream); JarInputStream jarInputStream = new JarInputStream(bufferedInputStream); JarEntry jarEntry;/* w w w .j a v a2 s . co m*/ while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { if (resources.containsKey(jarEntry.getName())) { if (logger != null) logger.trace("Already have resource " + jarEntry.getName() + ". If different versions, unexpected behaviour " + "might occur. Available in " + resources.get(jarEntry.getName())); } String spec; if (url.getProtocol().equals("jar")) { spec = url.getPath(); } else { spec = url.getProtocol() + ":" + url.getPath(); } URL contentUrl = new URL(null, "jar:" + spec + "!/" + jarEntry.getName(), new NestedJarURLStreamHandler(false)); resources.put(jarEntry.getName(), contentUrl); addClassIfClass(jarInputStream, jarEntry.getName()); if (logger != null) logger.trace("Added resource " + jarEntry.getName() + " to ClassLoader"); if (jarEntry.getName().endsWith(".jar")) { addResource0(contentUrl); } } jarInputStream.close(); bufferedInputStream.close(); urlStream.close(); } else if (url.getPath().endsWith(".class")) { throw new IllegalStateException("Cannot add classes directly"); } else { try { addDirectory(new File(url.toURI())); } catch (URISyntaxException e) { throw new IllegalStateException(e); } } }
From source file:org.sourcepit.osgifier.core.packaging.Repackager.java
private void copyJarContents(JarInputStream srcJarIn, final JarOutputStream destJarOut, PathMatcher contentMatcher) throws IOException { final Set<String> processedEntires = new HashSet<String>(); JarEntry srcEntry = srcJarIn.getNextJarEntry(); while (srcEntry != null) { final String entryName = srcEntry.getName(); if (contentMatcher.isMatch(entryName)) { if (processedEntires.add(entryName)) { destJarOut.putNextEntry(new JarEntry(srcEntry.getName())); IOUtils.copy(srcJarIn, destJarOut); destJarOut.closeEntry(); } else { logger.warn("Ignored duplicate jar entry: " + entryName); }/*from w ww. j av a 2 s . c om*/ } srcJarIn.closeEntry(); srcEntry = srcJarIn.getNextJarEntry(); } }
From source file:com.sachviet.bookman.server.util.ResolverUtil.java
public void loadImplementationsInJar(String parent, URL jarfile, Test... tests) { JarInputStream jarStream = null; try {/*from www .j a va2s. co m*/ JarEntry entry; jarStream = new JarInputStream(jarfile.openStream()); while ((entry = jarStream.getNextJarEntry()) != null) { String name = entry.getName(); if (!entry.isDirectory() && name.startsWith(parent) && name.endsWith(".class")) { //$NON-NLS-1$ addIfMatching(name, tests); } } } catch (IOException ioe) { LOG.trace("Could not search jar file \\\'" + jarfile //$NON-NLS-1$ + "\\\' for classes matching criteria: " + tests //$NON-NLS-1$ + " due to an IOException", ioe); //$NON-NLS-1$ } finally { if (jarStream != null) try { jarStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:org.apache.openjpa.eclipse.PluginLibrary.java
void copyJar(JarInputStream jar, JarOutputStream out) throws IOException { if (jar == null || out == null) return;//from w w w . j a va2 s . c o m try { JarEntry entry = null; while ((entry = jar.getNextJarEntry()) != null) { out.putNextEntry(entry); int b = -1; while ((b = jar.read()) != -1) { out.write(b); } } out.closeEntry(); } finally { out.finish(); out.flush(); out.close(); jar.close(); } }
From source file:com.jeeframework.util.resource.ResolverUtil.java
/** * Finds matching classes within a jar files that contains a folder structure * matching the package structure. If the File is not a JarFile or does not exist a warning * will be logged, but no error will be raised. * * @param test a Test used to filter the classes that are discovered * @param parent the parent package under which classes must be in order to be considered * @param jarfile the jar file to be examined for classes *//*from w w w . ja va 2 s . c om*/ private void loadImplementationsInJar(Test test, String parent, File jarfile) { try { JarEntry entry; JarInputStream jarStream = new JarInputStream(new FileInputStream(jarfile)); while ((entry = jarStream.getNextJarEntry()) != null) { String name = entry.getName(); if (!entry.isDirectory() && name.startsWith(parent) && name.endsWith(".class")) { addIfMatching(test, name); } } } catch (IOException ioe) { log.error("Could not search jar file '" + jarfile + "' for classes matching criteria: " + test + " due to an IOException", ioe); } }
From source file:org.romaframework.core.resource.ResourceResolver.java
/** * Examine a jar file searching for entities. * //from w ww.j a v a 2s . c om * @param f * @throws IOException */ protected void examineJarFile(File f, String iStartingPackage) { FileInputStream fis = null; try { fis = new FileInputStream(f); final JarInputStream jis = new JarInputStream(new BufferedInputStream(fis)); JarEntry entry; String fullName, packagePrefix, name; String pathStartingPackage = Utility.getResourcePath(iStartingPackage); int i; while ((entry = jis.getNextJarEntry()) != null) { fullName = entry.getName(); if (fullName.startsWith(pathStartingPackage) && acceptResorce(fullName)) { i = fullName.lastIndexOf(JAR_PATH_SEPARATOR) + 1; packagePrefix = fullName.substring(0, i).replace(JAR_PATH_SEPARATOR, PACKAGE_SEPARATOR); name = fullName.substring(i, fullName.length()); addResource(f, name, packagePrefix, iStartingPackage); } } } catch (Exception e) { } finally { try { if (fis != null) fis.close(); } catch (IOException e) { } } }
From source file:org.openspaces.maven.plugin.CreatePUProjectMojo.java
/** * Returns a set containing all templates defined in this JAR file. *///from w ww.j a va2 s . c o m public HashMap getJarTemplates(URL url) throws Exception { PluginLog.getLog().debug("retrieving all templates from jar file: " + url); String lookFor = DIR_TEMPLATES + "/"; int length = lookFor.length(); HashMap templates = new HashMap(); BufferedInputStream bis = new BufferedInputStream(url.openStream()); JarInputStream jis = new JarInputStream(bis); JarEntry je; Set temp = new HashSet(); while ((je = jis.getNextJarEntry()) != null) { // find the template name String jarEntryName = je.getName(); PluginLog.getLog().debug("Found entry: " + jarEntryName); if (jarEntryName.length() <= length || !jarEntryName.startsWith(lookFor)) { continue; } int nextSlashIndex = jarEntryName.indexOf("/", length); if (nextSlashIndex == -1) { continue; } String jarTemplate = jarEntryName.substring(length, nextSlashIndex); PluginLog.getLog().debug("Found template: " + jarTemplate); if (templates.containsKey(jarTemplate)) { continue; } if (jarEntryName.endsWith("readme.txt")) { // a description found - add to templates String description = getShortDescription(jis); templates.put(jarTemplate, description); // remove from temp temp.remove(jarTemplate); } else { // add to temp until a description is found temp.add(jarTemplate); } } // add all templates that has no description Iterator iter = temp.iterator(); while (iter.hasNext()) { templates.put(iter.next(), "No description found."); } return templates; }