List of usage examples for java.util.zip ZipFile entries
public Enumeration<? extends ZipEntry> entries()
From source file:org.fuin.esmp.EventStoreDownloadMojo.java
private void unzip(final File zipFile, final File destDir) throws MojoExecutionException { try {//from www . ja va2s. co m final ZipFile zip = new ZipFile(zipFile); try { final Enumeration<? extends ZipEntry> enu = zip.entries(); while (enu.hasMoreElements()) { final ZipEntry entry = (ZipEntry) enu.nextElement(); final File file = new File(entry.getName()); if (file.isAbsolute()) { throw new IllegalArgumentException( "Only relative path entries are allowed! [" + entry.getName() + "]"); } if (entry.isDirectory()) { final File dir = new File(destDir, entry.getName()); createIfNecessary(dir); } else { final File outFile = new File(destDir, entry.getName()); createIfNecessary(outFile.getParentFile()); final InputStream in = new BufferedInputStream(zip.getInputStream(entry)); try { final OutputStream out = new BufferedOutputStream(new FileOutputStream(outFile)); try { final byte[] buf = new byte[4096]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { out.close(); } } finally { in.close(); } } } } finally { zip.close(); } } catch (final IOException ex) { throw new MojoExecutionException("Error unzipping event store archive: " + zipFile, ex); } }
From source file:com.brienwheeler.apps.tomcat.TomcatBean.java
private void extractWarFile() { if (webAppBase != null && webAppBase.length() > 0) { ProtectionDomain protectionDomain = this.getClass().getProtectionDomain(); URL location = protectionDomain.getCodeSource().getLocation(); log.info("detected run JAR at " + location); if (!location.toExternalForm().startsWith("file:") || !location.toExternalForm().endsWith(".jar")) throw new IllegalArgumentException("invalid code location: " + location); try {//from ww w . j av a 2 s . c o m ZipFile zipFile = new ZipFile(new File(location.toURI())); Enumeration<? extends ZipEntry> entryEnum = zipFile.entries(); ZipEntry warEntry = null; while (entryEnum.hasMoreElements()) { ZipEntry entry = entryEnum.nextElement(); String entryName = entry.getName(); if (entryName.startsWith(webAppBase) && entryName.endsWith(".war")) { warEntry = entry; break; } } if (warEntry == null) throw new RuntimeException("can't find JAR entry for " + webAppBase + "*.war"); log.info("extracting WAR file " + warEntry.getName()); // extract web app WAR to current directory InputStream inputStream = zipFile.getInputStream(warEntry); OutputStream outputStream = new FileOutputStream(new File(warEntry.getName())); byte buf[] = new byte[1024]; int nread; while ((nread = inputStream.read(buf, 0, 1024)) > 0) { outputStream.write(buf, 0, nread); } outputStream.close(); inputStream.close(); zipFile.close(); String launchContextRoot = contextRoot != null ? contextRoot : webAppBase; if (!launchContextRoot.startsWith("/")) launchContextRoot = "/" + launchContextRoot; log.info("launching WAR file " + warEntry.getName() + " at context root " + launchContextRoot); // add web app to Tomcat Context context = tomcat.addWebapp(launchContextRoot, warEntry.getName()); if (context instanceof StandardContext) ((StandardContext) context).setUnpackWAR(false); } catch (Exception e) { throw new RuntimeException("error extracting WAR file", e); } } }
From source file:net.sf.sripathi.ws.mock.util.Folder.java
public void createFilesAndFolder(ZipFile zip) { @SuppressWarnings("unchecked") Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries(); Set<String> files = new TreeSet<String>(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.getName().toLowerCase().endsWith(".wsdl") || entry.getName().toLowerCase().endsWith(".xsd")) files.add(entry.getName());//w ww .j av a 2 s. c om } for (String fileStr : files) { String[] split = fileStr.split("/"); Folder parent = this; if (split.length > 1) { Folder sub = null; for (int i = 0; i < split.length - 1; i++) { sub = parent.getSubFolderByName(split[i]); if (sub == null) { sub = parent.createSubFolder(split[i]); } parent = sub; } } File file = parent.createFile(split[split.length - 1]); FileOutputStream fos = null; InputStream zipStream = null; try { fos = new FileOutputStream(file); zipStream = zip.getInputStream(zip.getEntry(fileStr)); fos.write(IOUtils.toByteArray(zipStream)); } catch (Exception e) { throw new MockException("Unable to create file - " + fileStr); } finally { try { fos.close(); } catch (Exception e) { } try { zipStream.close(); } catch (Exception e) { } } } }
From source file:com.ning.maven.plugins.duplicatefinder.ClasspathDescriptor.java
private void addArchive(File element) throws IOException { if (addCached(element)) { return;// ww w. ja v a 2 s.c om } List classes = new ArrayList(); List resources = new ArrayList(); ZipFile zipFile = null; try { zipFile = new ZipFile(element); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.isDirectory()) { String name = entry.getName(); if ("class".equals(FilenameUtils.getExtension(name))) { String className = FilenameUtils.removeExtension(name).replace('/', '.').replace('\\', '.'); classes.add(className); addClass(className, element); } else { String resourcePath = name.replace('\\', File.separatorChar); resources.add(resourcePath); addResource(resourcePath, element); } } } CACHED_BY_ELEMENT.put(element, new Cached(classes, resources)); } finally { // IOUtils has no closeQuietly for Closable in the 1.x series. if (zipFile != null) { try { zipFile.close(); } catch (IOException ex) { // ignored } } } }
From source file:io.github.jeremgamer.preview.actions.Download.java
private void download() { GeneralSave gs = new GeneralSave(); try {//from ww w.j a va 2 s. com gs.load(new File("projects/" + Editor.getProjectName() + "/general.rbd")); } catch (IOException e1) { e1.printStackTrace(); } name = gs.getString("name"); new Thread(new Runnable() { @Override public void run() { if (url == null) { } else { File archive = new File(System.getProperty("user.home") + "/AppData/Roaming/.rocketbuilder/" + name + "/data.zip"); File outputFolder = new File( System.getProperty("user.home") + "/AppData/Roaming/.rocketbuilder/" + name); new File(System.getProperty("user.home") + "/AppData/Roaming/.rocketbuilder/" + name).mkdirs(); URL webFile; try { webFile = new URL(url); ReadableByteChannel rbc = Channels.newChannel(webFile.openStream()); fos = new FileOutputStream(System.getProperty("user.home") + "/AppData/Roaming/.rocketbuilder/" + name + "/data.zip"); HttpURLConnection httpConn = (HttpURLConnection) webFile.openConnection(); totalBytes = httpConn.getContentLength(); new Thread(new Runnable() { @Override public void run() { try { while (bytesCopied < totalBytes) { for (CustomProgressBar bar : barList) { bytesCopied = fos.getChannel().size(); progressValue = (int) (100 * bytesCopied / totalBytes); bar.setValue(progressValue); if (bar.isStringPainted()) { bar.setString(progressValue + "% " + bytesCopied / 1000 + "/" + totalBytes / 1000 + "Kb tape " + step + "/2"); } } } } catch (IOException e) { e.printStackTrace(); } } }).start(); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); step = 2; for (CustomProgressBar bar : barList) { if (bar.isStringPainted()) { bar.setString("tape " + step + "/2 : Extraction"); } } for (int timeout = 100; timeout > 0; timeout--) { RandomAccessFile ran = null; try { ran = new RandomAccessFile(archive, "rw"); break; } catch (Exception ex) { } finally { if (ran != null) try { ran.close(); } catch (IOException ex) { } ran = null; } try { Thread.sleep(100); } catch (InterruptedException ex) { } } ZipFile zipFile = new ZipFile(archive, Charset.forName("Cp437")); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File entryDestination = new File(outputFolder, entry.getName()); entryDestination.getParentFile().mkdirs(); if (entry.isDirectory()) entryDestination.mkdirs(); else { InputStream in = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(entryDestination); IOUtils.copy(in, out); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); in.close(); out.close(); } } for (CustomProgressBar bar : barList) { bar.setString(""); } zipFile.close(); archive.delete(); } catch (IOException e) { e.printStackTrace(); } } } }).start(); }
From source file:org.devproof.portal.core.module.theme.service.ThemeServiceImpl.java
@Override public void install(File themeArchive) { String uuid = UUID.randomUUID().toString(); try {/*from w ww .jav a 2 s.c o m*/ File folder = new File(servletContext.getRealPath("/WEB-INF/themes")); folder = new File(folder.toString() + File.separator + uuid); FileUtils.forceMkdir(folder); ZipFile zipFile = new ZipFile(themeArchive); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File out = new File(folder.getAbsolutePath() + File.separator + entry.getName()); if (entry.isDirectory()) { FileUtils.forceMkdir(out); } else { FileUtils.touch(out); FileOutputStream fos = new FileOutputStream(out, false); IOUtils.copy(zipFile.getInputStream(entry), fos); fos.close(); } } zipFile.close(); logger.info("New theme installed: " + uuid); } catch (MalformedURLException e) { logger.warn("Unknown error", e); } catch (IOException e) { logger.warn("Unknown error", e); } }
From source file:edu.umd.cs.marmoset.utilities.ZipExtractor.java
/** * Extract the zip file./* w w w. j a va2 s .com*/ * @throws IOException * @throws BuilderException */ public void extract(File directory) throws IOException, ZipExtractorException { ZipFile z = new ZipFile(zipFile); Pattern badName = Pattern.compile("[\\p{Cntrl}<>]"); try { Enumeration<? extends ZipEntry> entries = z.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (!shouldExtract(entryName)) continue; if (badName.matcher(entryName).find()) { if (entry.getSize() > 0) getLog().debug("Skipped entry of length " + entry.getSize() + " with bad file name " + java.net.URLEncoder.encode(entryName, "UTF-8")); continue; } try { // Get the filename to extract the entry into. // Subclasses may define this to be something other // than the entry name. String entryFileName = transformFileName(entryName); if (!entryFileName.equals(entryName)) { getLog().debug("Transformed zip entry name: " + entryName + " ==> " + entryFileName); } entriesExtractedFromZipArchive.add(entryFileName); File entryOutputFile = new File(directory, entryFileName).getAbsoluteFile(); File parentDir = entryOutputFile.getParentFile(); if (!parentDir.exists()) { if (!parentDir.mkdirs()) { throw new ZipExtractorException( "Couldn't make directory for entry output file " + entryOutputFile.getPath()); } } if (!parentDir.isDirectory()) { throw new ZipExtractorException( "Parent directory for entry " + entryOutputFile.getPath() + " is not a directory"); } // Make sure the entry output file lies within the build directory. // A malicious zip file might have ".." components in it. getLog().trace("entryOutputFile path: " + entryOutputFile.getCanonicalPath()); if (!entryOutputFile.getCanonicalPath().startsWith(directory.getCanonicalPath() + "/")) { if (!entry.isDirectory()) getLog().warn("Zip entry " + entryName + " accesses a path " + entryOutputFile.getPath() + "outside the build directory " + directory.getPath()); continue; } if (entry.isDirectory()) { entryOutputFile.mkdir(); continue; } // Extract the entry InputStream entryInputStream = null; OutputStream entryOutputStream = null; try { entryInputStream = z.getInputStream(entry); entryOutputStream = new BufferedOutputStream(new FileOutputStream(entryOutputFile)); CopyUtils.copy(entryInputStream, entryOutputStream); } finally { IOUtils.closeQuietly(entryInputStream); IOUtils.closeQuietly(entryOutputStream); } // Hook for subclasses, to specify when entries are // successfully extracted. successfulFileExtraction(entryName, entryFileName); ++numFilesExtacted; } catch (RuntimeException e) { getLog().error("Error extracting " + entryName, e); throw e; } } } finally { z.close(); } }
From source file:fi.mikuz.boarder.gui.ZipImporter.java
@SuppressWarnings("rawtypes") public void unzipArchive(final File archive, final File outputDir) { Thread t = new Thread() { public void run() { Looper.prepare();// w w w . ja va 2s. c o m String archiveName = archive.getName(); String boardName = archiveName.substring(0, archiveName.indexOf(".zip")); String boardDirectory = SoundboardMenu.mSbDir.getAbsolutePath() + "/" + boardName; try { File boardDirectoryFile = new File(boardDirectory); if (boardDirectoryFile.exists()) { postMessage(boardDirectoryFile.getName() + " already exists."); } else { ZipFile zipfile = new ZipFile(archive); boolean normalStructure = true; log = "Checking if zip structure is legal\n" + log; for (Enumeration e = zipfile.entries(); e.hasMoreElements();) { ZipEntry entry = (ZipEntry) e.nextElement(); File outputFile = new File(outputDir, entry.getName()); if (!Pattern.matches(boardDirectory + ".*", outputFile.getAbsolutePath())) { normalStructure = false; log = entry.getName() + " failed\n" + outputFile.getAbsolutePath() + "\ndoens't match\n" + boardDirectory + "\n\n" + log; Log.e(TAG, entry.getName() + " failed\n" + outputFile.getAbsolutePath() + "\ndoens't match\n" + boardDirectory); } } if (normalStructure) { log = "\nGoing to extract\n" + log; outputDir.mkdirs(); for (Enumeration e = zipfile.entries(); e.hasMoreElements();) { ZipEntry entry = (ZipEntry) e.nextElement(); log = "Extracting " + entry.getName() + "\n" + log; postMessage("Please wait\n\n" + log); unzipEntry(zipfile, entry, outputDir); } log = "Success\n\n" + log; postMessage(log); } else { postMessage("Zip was not extracted because it doesn't follow the normal structure.\n\n" + "Please use another application to check the content of this zip file and extract it if you want to.\n\n" + log); } } } catch (Exception e) { log = "Couldn't extract " + archive + "\n\nError: \n" + e.getMessage() + "\n\n" + log; postMessage(log); Log.e(TAG, "Error while extracting file " + archive, e); } mHandler.post(showContinueButton); } }; t.start(); }
From source file:com.servoy.extension.install.CopyZipEntryImporter.java
public void handleFile() { if (expFile != null && expFile.exists() && expFile.isFile() && expFile.canRead() && expFile.getName().endsWith(FileBasedExtensionProvider.EXTENSION_PACKAGE_FILE_EXTENSION) && installDir != null && installDir.exists() && installDir.isDirectory() && installDir.canWrite()) { ZipFile zipFile = null; try {// w ww. j ava 2 s .c o m zipFile = new ZipFile(expFile); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (!entry.isDirectory()) { String fileName = entry.getName().replace('\\', '/'); fileName = fileName.replace(WEBTEMPLATES_SOURCE_FOLDER, WEBTEMPLATES_DESTINATION_FOLDER); File outputFile = new File(installDir, fileName); handleZipEntry(outputFile, zipFile, entry); } } } catch (IOException ex) { String tmp = "Exception while handling entries of expFile: " + expFile; //$NON-NLS-1$ messages.addError(tmp); Debug.error(tmp, ex); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // ignore } } enforceBackUpFolderLimit(); } handleExpFile(); } else { // shouldn't happen String tmp = "Invalid install/uninstall file/destination: " + expFile + ", " + installDir; //$NON-NLS-1$//$NON-NLS-2$ messages.addError(tmp); Debug.error(tmp); } }
From source file:net.sf.sripathi.ws.mock.util.Folder.java
public Set<String> checkDuplicateFiles(ZipFile zip) { Set<String> dups = new TreeSet<String>(); @SuppressWarnings("unchecked") Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (fileSet.contains(this.path + "/" + entry.getName())) dups.add(entry.getName());//from w w w . j a v a 2 s . c om } return dups; }