List of usage examples for java.util.zip ZipFile entries
public Enumeration<? extends ZipEntry> entries()
From source file:com.isomorphic.maven.packaging.Distribution.java
/** * Extract the relevant contents from each file in the distribution. Additionally creates ZIP/JAR * files from specified resources (e.g., javadoc). * /*from ww w . j ava 2s. c om*/ * @param to The directory to which each file should be extracted. * @throws IOException */ public void unpack(File to) throws IOException { outer: for (File file : files) { String ext = FilenameUtils.getExtension(file.getName()).toUpperCase(); //copy uncompressed files to target, renaming as necessary per 'contents' configuration if (!"ZIP".equals(ext)) { for (Map.Entry<String, AntPathMatcherFilter> filterEntry : content.entrySet()) { AntPathMatcherFilter filter = filterEntry.getValue(); if (filter.accept(file.getName())) { File target = FileUtils.getFile(to, ArchiveUtils.rewritePath(file.getName(), filterEntry.getKey())); FileUtils.copyFile(file, target); LOGGER.debug("Copied file '{}' to file '{}'", file.getName(), target.getAbsolutePath()); continue outer; } } FileUtils.copyFileToDirectory(file, new File(to, "lib")); continue outer; } //otherwise extract contents (again renaming / relocating contents as necessary) ZipFile zip = new ZipFile(file); Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; } for (Map.Entry<String, AntPathMatcherFilter> filterEntry : content.entrySet()) { AntPathMatcherFilter filter = filterEntry.getValue(); if (filter.accept(entry.getName())) { File target = FileUtils.getFile(to, ArchiveUtils.rewritePath(entry.getName(), filterEntry.getKey())); FileUtils.copyInputStreamToFile(zip.getInputStream(entry), target); LOGGER.debug("Copied input stream to file '{}'", target.getAbsolutePath()); } } } zip.close(); } /* * Create any number of assemblies by dropping their resources here. * Each subdirectory will get zipped up and then deleted */ File assembliesDir = new File(to, "assembly"); @SuppressWarnings("unchecked") Collection<File> assemblies = CollectionUtils.arrayToList(assembliesDir.listFiles(new FileFilter() { @Override public boolean accept(File arg0) { return arg0.isDirectory(); } })); for (File assembly : assemblies) { String name = FilenameUtils.getBaseName(assembly.getName()); LOGGER.debug("Copying resources for assembly '{}'", name); ArchiveUtils.zip(assembly, FileUtils.getFile(assembliesDir, name + ".zip")); FileUtils.deleteQuietly(assembly); } LOGGER.debug("Repackaging Javadoc..."); File docLib = new File(to, "doc/lib"); //TODO these paths should probably all be stuck in some constant File client = FileUtils.getFile(to, "doc/api/client"); if (client.exists()) { ArchiveUtils.jar(client, new File(docLib, "smartgwt-javadoc.jar")); } File server = FileUtils.getFile(to, "doc/api/server"); if (server.exists()) { ArchiveUtils.jar(server, new File(docLib, "isomorphic-javadoc.jar")); } }
From source file:com.openmeap.file.FileOperationManagerImpl.java
@Override public void unzipFile(ZipFile zipFile, String destinationDir) throws FileOperationException { try {//from w w w . j a v a 2s .c o m int BUFFER = 1024; BufferedOutputStream dest = null; BufferedInputStream is = null; OutputStream fos = null; ZipEntry entry; Enumeration e = zipFile.entries(); while (e.hasMoreElements()) { try { entry = (ZipEntry) e.nextElement(); is = new BufferedInputStream(zipFile.getInputStream(entry)); String newFile = destinationDir + File.separator + entry.getName(); if (entry.isDirectory()) { continue; // skip directories, resource manager will create for us } else { fos = write(newFile); dest = new BufferedOutputStream(fos, BUFFER); Utils.pipeInputStreamIntoOutputStream(is, dest); } } finally { if (dest != null) { dest.close(); } if (fos != null) { fos.close(); } if (is != null) { is.close(); } } } } catch (IOException ioe) { throw new FileOperationException(ioe); } }
From source file:com.denimgroup.threadfix.importer.impl.upload.SkipfishChannelImporter.java
private InputStream findSamplesFile(@Nonnull ZipFile zipFile) { if (zipFile.entries() == null) { throw new ScanFileUnavailableException("No zip entries were found in the zip file."); }//from ww w . j a v a 2s . c om Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.getName().endsWith("samples.js")) { try { return zipFile.getInputStream(entry); } catch (IOException e) { log.error("IOException thrown when reading entries from zip file.", e); } } } throw new ScanFileUnavailableException("Samples.js was not found in the zip file."); }
From source file:com.wolvereness.renumerated.Renumerated.java
private void process() throws Throwable { validateInput();/* w w w . ja v a2 s.c o m*/ final MultiProcessor executor = MultiProcessor.newMultiProcessor(cores - 1, new ThreadFactoryBuilder().setDaemon(true) .setNameFormat(Renumerated.class.getName() + "-processor-%d") .setUncaughtExceptionHandler(this).build()); final Future<?> fileCopy = executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { if (original != null) { if (original.exists()) { original.delete(); } Files.copy(input, original); } return null; } }); final List<Pair<ZipEntry, Future<byte[]>>> fileEntries = newArrayList(); final List<Pair<MutableObject<ZipEntry>, Future<byte[]>>> classEntries = newArrayList(); { final ZipFile input = new ZipFile(this.input); final Enumeration<? extends ZipEntry> inputEntries = input.entries(); while (inputEntries.hasMoreElements()) { final ZipEntry entry = inputEntries.nextElement(); final Future<byte[]> future = executor.submit(new Callable<byte[]>() { @Override public byte[] call() throws Exception { return ByteStreams.toByteArray(input.getInputStream(entry)); } }); if (entry.getName().endsWith(".class")) { classEntries.add(new MutablePair<MutableObject<ZipEntry>, Future<byte[]>>( new MutableObject<ZipEntry>(entry), future)); } else { fileEntries.add(new ImmutablePair<ZipEntry, Future<byte[]>>(entry, future)); } } for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> pair : classEntries) { final byte[] data = pair.getRight().get(); pair.setValue(executor.submit(new Callable<byte[]>() { String className; List<String> fields; @Override public byte[] call() throws Exception { try { return method(); } catch (final Exception ex) { throw new Exception(pair.getLeft().getValue().getName(), ex); } } private byte[] method() throws Exception { final ClassReader clazz = new ClassReader(data); clazz.accept(new ClassVisitor(ASM4) { @Override public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { if (superName.equals("java/lang/Enum")) { className = name; } } @Override public FieldVisitor visitField(final int access, final String name, final String desc, final String signature, final Object value) { if (className != null && (access & 0x4000) != 0) { List<String> fieldNames = fields; if (fieldNames == null) { fieldNames = fields = newArrayList(); } fieldNames.add(name); } return null; } }, ClassReader.SKIP_CODE); if (className == null) return data; final String classDescriptor = Type.getObjectType(className).getDescriptor(); final ClassWriter writer = new ClassWriter(0); clazz.accept(new ClassVisitor(ASM4, writer) { @Override public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { final MethodVisitor methodVisitor = super.visitMethod(access, name, desc, signature, exceptions); if (!name.equals("<clinit>")) { return methodVisitor; } return new MethodVisitor(ASM4, methodVisitor) { final Iterator<String> it = fields.iterator(); boolean active; String lastName; @Override public void visitTypeInsn(final int opcode, final String type) { if (!active && it.hasNext()) { // Initiate state machine if (opcode != NEW) throw new AssertionError("Unprepared for " + opcode + " on " + type + " in " + className); active = true; } super.visitTypeInsn(opcode, type); } @Override public void visitLdcInsn(final Object cst) { if (active && lastName == null) { if (!(cst instanceof String)) throw new AssertionError( "Unprepared for " + cst + " in " + className); // Switch the first constant in the Enum constructor super.visitLdcInsn(lastName = it.next()); } else { super.visitLdcInsn(cst); } } @Override public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) { if (opcode == PUTSTATIC && active && lastName != null && owner.equals(className) && desc.equals(classDescriptor) && name.equals(lastName)) { // Finish the current state machine active = false; lastName = null; } super.visitFieldInsn(opcode, owner, name, desc); } }; } }, ClassReader.EXPAND_FRAMES); final MutableObject<ZipEntry> key = pair.getLeft(); key.setValue(new ZipEntry(key.getValue().getName())); return writer.toByteArray(); } })); } for (final Pair<ZipEntry, Future<byte[]>> pair : fileEntries) { pair.getRight().get(); } input.close(); } fileCopy.get(); FileOutputStream fileOut = null; JarOutputStream jar = null; try { jar = new JarOutputStream(fileOut = new FileOutputStream(output)); for (final Pair<ZipEntry, Future<byte[]>> fileEntry : fileEntries) { jar.putNextEntry(fileEntry.getLeft()); jar.write(fileEntry.getRight().get()); } for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> classEntry : classEntries) { final byte[] data = classEntry.getRight().get(); final ZipEntry entry = classEntry.getLeft().getValue(); entry.setSize(data.length); jar.putNextEntry(entry); jar.write(data); } } finally { if (jar != null) { try { jar.close(); } catch (final IOException ex) { } } if (fileOut != null) { try { fileOut.close(); } catch (final IOException ex) { } } } final Pair<Thread, Throwable> uncaught = this.uncaught; if (uncaught != null) throw new MojoExecutionException(String.format("Uncaught exception in %s", uncaught.getLeft()), uncaught.getRight()); }
From source file:com.microsoft.tfs.client.common.ui.teambuild.commands.CreateUploadZipCommand.java
/** * Copy zip file and remove ignored files * * @param srcFile/* w w w . j av a2s . c om*/ * @param destFile * @throws IOException */ public void copyZip(final String srcFile, final String destFile) throws Exception { loadDefaultExcludePattern(getRootFolderInZip(srcFile)); final ZipFile zipSrc = new ZipFile(srcFile); final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destFile)); try { final Enumeration<? extends ZipEntry> entries = zipSrc.entries(); while (entries.hasMoreElements()) { final ZipEntry entry = entries.nextElement(); if (!isExcluded(LocalPath.combine(srcFile, entry.getName()), false, srcFile)) { final ZipEntry newEntry = new ZipEntry(entry.getName()); out.putNextEntry(newEntry); final BufferedInputStream in = new BufferedInputStream(zipSrc.getInputStream(entry)); int len; final byte[] buf = new byte[65536]; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } } out.finish(); } catch (final IOException e) { errorMsg = Messages.getString("CreateUploadZipCommand.CopyArchiveErrorMessageFormat"); //$NON-NLS-1$ log.error("Exceptions when copying exising archive ", e); //$NON-NLS-1$ throw e; } finally { out.close(); zipSrc.close(); } }
From source file:com.enioka.jqm.tools.LibraryCache.java
private void loadCache(Node node, JobDef jd, EntityManager em) throws JqmPayloadException { jqmlogger.debug("Resolving classpath for job definition " + jd.getApplicationName()); File jarFile = new File(FilenameUtils.concat(new File(node.getRepo()).getAbsolutePath(), jd.getJarPath())); File jarDir = jarFile.getParentFile(); File libDir = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "lib")); File libDirExtracted = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "libFromJar")); File pomFile = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "pom.xml")); // POM file should be deleted if it comes from the jar file. Otherwise, it would stay into place and modifications to the internal // pom would be ignored. boolean pomFromJar = false; // 1st: if no pom, no lib dir => find a pom inside the JAR. (& copy it, we will read later) if (!pomFile.exists() && !libDir.exists()) { jqmlogger.trace("No pom inside jar directory. Checking for a pom inside the jar file"); InputStream is = null;/* ww w.j a v a 2 s .c o m*/ FileOutputStream os = null; try { ZipFile zf = new ZipFile(jarFile); Enumeration<? extends ZipEntry> zes = zf.entries(); while (zes.hasMoreElements()) { ZipEntry ze = zes.nextElement(); if (ze.getName().endsWith("pom.xml")) { is = zf.getInputStream(ze); os = new FileOutputStream(pomFile); IOUtils.copy(is, os); pomFromJar = true; break; } } zf.close(); } catch (Exception e) { throw new JqmPayloadException("Could not handle pom inside jar", e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } // 2nd: no pom, no pom inside jar, no lib dir => find a lib dir inside the jar if (!pomFile.exists() && !libDir.exists()) { jqmlogger.trace("Checking for a lib directory inside jar"); InputStream is = null; FileOutputStream os = null; ZipFile zf = null; FileUtils.deleteQuietly(libDirExtracted); try { zf = new ZipFile(jarFile); Enumeration<? extends ZipEntry> zes = zf.entries(); while (zes.hasMoreElements()) { ZipEntry ze = zes.nextElement(); if (ze.getName().startsWith("lib/") && ze.getName().endsWith(".jar")) { if (!libDirExtracted.isDirectory() && !libDirExtracted.mkdir()) { throw new JqmPayloadException("Could not extract libraries from jar"); } is = zf.getInputStream(ze); os = new FileOutputStream(FilenameUtils.concat(libDirExtracted.getAbsolutePath(), FilenameUtils.getName(ze.getName()))); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } } catch (Exception e) { throw new JqmPayloadException("Could not handle internal lib directory", e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); try { zf.close(); } catch (Exception e) { jqmlogger.warn("could not close jar file", e); } } // If libs were extracted, put in cache and return if (libDirExtracted.isDirectory()) { FileFilter fileFilter = new WildcardFileFilter("*.jar"); File[] files = libDirExtracted.listFiles(fileFilter); URL[] libUrls = new URL[files.length]; try { for (int i = 0; i < files.length; i++) { libUrls[i] = files[i].toURI().toURL(); } } catch (Exception e) { throw new JqmPayloadException("Could not handle internal lib directory", e); } // Put in cache putInCache(libUrls, jd.getApplicationName()); return; } } // 3rd: if pom, use pom! if (pomFile.exists() && !libDir.exists()) { jqmlogger.trace("Reading a pom file"); // Retrieve resolver configuration List<GlobalParameter> repolist = em .createQuery("SELECT gp FROM GlobalParameter gp WHERE gp.key = :repo", GlobalParameter.class) .setParameter("repo", "mavenRepo").getResultList(); List<GlobalParameter> settings = em .createQuery("SELECT gp FROM GlobalParameter gp WHERE gp.key = :k", GlobalParameter.class) .setParameter("k", "mavenSettingsCL").getResultList(); List<GlobalParameter> settingFiles = em .createQuery("SELECT gp FROM GlobalParameter gp WHERE gp.key = :k", GlobalParameter.class) .setParameter("k", "mavenSettingsFile").getResultList(); boolean withCentral = false; String withCustomSettings = null; String withCustomSettingsFile = null; if (settings.size() == 1 && settingFiles.isEmpty()) { jqmlogger.trace("Custom settings file will be used: " + settings.get(0).getValue()); withCustomSettings = settings.get(0).getValue(); } if (settingFiles.size() == 1) { jqmlogger.trace("Custom settings file will be used: " + settingFiles.get(0).getValue()); withCustomSettingsFile = settingFiles.get(0).getValue(); } // Configure resolver ConfigurableMavenResolverSystem resolver = Maven.configureResolver(); if (withCustomSettings != null && withCustomSettingsFile == null) { resolver.fromClassloaderResource(withCustomSettings); } if (withCustomSettingsFile != null) { resolver.fromFile(withCustomSettingsFile); } for (GlobalParameter gp : repolist) { if (gp.getValue().contains("repo1.maven.org")) { withCentral = true; } resolver = resolver.withRemoteRepo(MavenRemoteRepositories .createRemoteRepository(gp.getId().toString(), gp.getValue(), "default") .setUpdatePolicy(MavenUpdatePolicy.UPDATE_POLICY_NEVER)); } resolver.withMavenCentralRepo(withCentral); // Resolve File[] depFiles = null; try { depFiles = resolver.loadPomFromFile(pomFile).importRuntimeDependencies().resolve() .withTransitivity().asFile(); } catch (IllegalArgumentException e) { // Happens when no dependencies inside pom, which is a weird use of the feature... jqmlogger.trace("No dependencies inside pom.xml file - no libs will be used", e); depFiles = new File[0]; } // Extract results int size = 0; for (File artifact : depFiles) { if (!"pom".equals(FilenameUtils.getExtension(artifact.getName()))) { size++; } } URL[] tmp = new URL[size]; int i = 0; for (File artifact : depFiles) { if ("pom".equals(FilenameUtils.getExtension(artifact.getName()))) { continue; } try { tmp[i] = artifact.toURI().toURL(); } catch (MalformedURLException e) { throw new JqmPayloadException("Incorrect dependency in POM file", e); } i++; } // Put in cache putInCache(tmp, jd.getApplicationName()); // Cleanup if (pomFromJar && !pomFile.delete()) { jqmlogger.warn("Could not delete the temp pom file extracted from the jar."); } return; } // 4: if lib, use lib... (lib has priority over pom) if (libDir.exists()) { jqmlogger.trace( "Using the lib directory " + libDir.getAbsolutePath() + " as the source for dependencies"); FileFilter fileFilter = new WildcardFileFilter("*.jar"); File[] files = libDir.listFiles(fileFilter); URL[] tmp = new URL[files.length]; for (int i = 0; i < files.length; i++) { try { tmp[i] = files[i].toURI().toURL(); } catch (MalformedURLException e) { throw new JqmPayloadException("incorrect file inside lib directory", e); } } // Put in cache putInCache(tmp, jd.getApplicationName()); return; } throw new JqmPayloadException( "There is no lib dir or no pom.xml inside the directory containing the jar or inside the jar. The jar cannot be launched."); }
From source file:org.apache.phoenix.pherf.util.ResourceList.java
Collection<String> getResourcesFromJarFile(final File file, final Pattern pattern) { final List<String> retVal = new ArrayList<>(); ZipFile zf; try {//from ww w .j a v a2s. c o m zf = new ZipFile(file); } catch (FileNotFoundException e) { // Gracefully handle a jar listed on the classpath that doesn't actually exist. return Collections.emptyList(); } catch (final ZipException e) { throw new Error(e); } catch (final IOException e) { throw new Error(e); } final Enumeration e = zf.entries(); while (e.hasMoreElements()) { final ZipEntry ze = (ZipEntry) e.nextElement(); final String fileName = ze.getName(); final boolean accept = pattern.matcher(fileName).matches(); logger.trace("fileName:" + fileName); logger.trace("File:" + file.toString()); logger.trace("Match:" + accept); if (accept) { logger.trace("Adding File from Jar: " + fileName); retVal.add("/" + fileName); } } try { zf.close(); } catch (final IOException e1) { throw new Error(e1); } return retVal; }
From source file:com.liferay.mobile.sdk.core.tests.MobileSDKCoreTests.java
private void checkJar(File jar, boolean src) throws Exception { assertTrue(jar.exists());// w w w. j a va 2s . co m final ZipFile zipFile = new ZipFile(jar); final ZipEntry manifest = zipFile.getEntry("META-INF/MANIFEST.MF"); assertNotNull(manifest); final String manifestContents = CoreUtil.readStreamToString(zipFile.getInputStream(manifest)); assertTrue(manifestContents.startsWith("Manifest-Version: 1.0")); boolean valid = false; Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { final String entryName = entries.nextElement().getName(); if (entryName.startsWith(PACKAGE.split("\\.")[0]) && entryName.endsWith(src ? ".java" : ".class")) { valid = true; break; } } zipFile.close(); assertTrue(valid); }
From source file:org.apache.maven.archetype.common.DefaultArchetypeArtifactManager.java
public List<String> getFilesetArchetypeResources(File archetypeFile) throws UnknownArchetype { getLogger().debug("getFilesetArchetypeResources( \"" + archetypeFile.getAbsolutePath() + "\" )"); List<String> archetypeResources = new ArrayList<String>(); ZipFile zipFile = null; try {//from ww w . j av a 2s . c om zipFile = getArchetypeZipFile(archetypeFile); Enumeration<? extends ZipEntry> enumeration = zipFile.entries(); while (enumeration.hasMoreElements()) { ZipEntry entry = (ZipEntry) enumeration.nextElement(); if (entry.getName().startsWith(Constants.ARCHETYPE_RESOURCES)) { // not supposed to be file.separator String resource = entry.getName().substring(Constants.ARCHETYPE_RESOURCES.length() + 1); getLogger().debug(" - found resource (" + Constants.ARCHETYPE_RESOURCES + "/)" + resource); // TODO:FIXME archetypeResources.add(resource); } else { getLogger().debug(" - ignored resource " + entry.getName()); } } return archetypeResources; } finally { closeZipFile(zipFile); } }
From source file:com.google.appinventor.buildserver.ProjectBuilder.java
private ArrayList<String> extractProjectFiles(ZipFile inputZip, File projectRoot) throws IOException { ArrayList<String> projectFileNames = Lists.newArrayList(); Enumeration<? extends ZipEntry> inputZipEnumeration = inputZip.entries(); while (inputZipEnumeration.hasMoreElements()) { ZipEntry zipEntry = inputZipEnumeration.nextElement(); final InputStream extractedInputStream = inputZip.getInputStream(zipEntry); File extractedFile = new File(projectRoot, zipEntry.getName()); LOG.info("extracting " + extractedFile.getAbsolutePath() + " from input zip"); Files.createParentDirs(extractedFile); // Do I need this? Files.copy(new InputSupplier<InputStream>() { public InputStream getInput() throws IOException { return extractedInputStream; }/*from w ww .j a va 2s .co m*/ }, extractedFile); projectFileNames.add(extractedFile.getPath()); } return projectFileNames; }