List of usage examples for java.util.zip ZipEntry isDirectory
public boolean isDirectory()
From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java
/** * @param zipFile/*from ww w. j a v a2s .c om*/ * @param directoryToExtractTo Provides file unzip functionality */ public void unzipZipFile(InputStream zipFile, String directoryToExtractTo) { ZipInputStream in = new ZipInputStream(zipFile); try { File directory = new File(directoryToExtractTo); if (!directory.exists()) { directory.mkdirs(); getLog().info("Creating directory for Extraction..."); } ZipEntry entry = in.getNextEntry(); while (entry != null) { try { File file = new File(directory, entry.getName()); if (entry.isDirectory()) { file.mkdirs(); } else { FileOutputStream out = new FileOutputStream(file); byte[] buffer = new byte[2048]; int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.close(); } in.closeEntry(); entry = in.getNextEntry(); } catch (Exception e) { getLog().error(e); } } } catch (IOException ioe) { getLog().error(ioe); return; } }
From source file:com.mirth.connect.client.ui.reference.ReferenceListFactory.java
private void addUserutilReferences(URL url) { InputStream inputStream = null; try {//from w w w . ja v a 2 s. c om inputStream = url.openStream(); ZipInputStream zis = new ZipInputStream(inputStream); ZipEntry zipEntry; Map<String, InputStream> entryMap = new HashMap<String, InputStream>(); // Iterate through each entry in the JAR file while ((zipEntry = zis.getNextEntry()) != null) { if (!zipEntry.isDirectory() && StringUtils.endsWithIgnoreCase(zipEntry.getName(), ".java")) { entryMap.put(zipEntry.getName(), new ByteArrayInputStream(IOUtils.toByteArray(zis))); } } for (Entry<String, InputStream> entry : entryMap.entrySet()) { try { // Parse the source file CompilationUnit compilationUnit = JavaParser.parse(entry.getValue()); // Determine any runtime aliases for the class List<String> inputTextList = aliasMap .get(entry.getKey().replaceAll("\\.java$", "").replace('/', '.')); // Create and add references for the parsed source file addReferences(ClassVisitor.getReferencesByCompilationUnit(compilationUnit, inputTextList)); } catch (Exception e) { logger.error("Unable to load references from userutil entry " + entry.getKey(), e); } } } catch (Exception e) { logger.error("Error occurred while scanning for userutil references.", e); } finally { IOUtils.closeQuietly(inputStream); } }
From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileUtilities.java
public void decompressZip(File inputZipPath, File zipPath) { int BUFFER = 2048; List<File> zipFiles = new ArrayList<File>(); try {/* w ww. j a v a 2s .c o m*/ zipPath.mkdir(); } catch (SecurityException e) { jlog.fatal("Security exception when creating " + zipPath.getName()); } ZipFile zipFile = null; boolean isZip = true; // Open Zip file for reading (should be in temppath) try { zipFile = new ZipFile(inputZipPath, ZipFile.OPEN_READ); } catch (IOException e) { jlog.fatal("IO exception in " + inputZipPath.getName()); } // Create an enumeration of the entries in the zip file Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries(); if (isZip) { // Process each entry while (zipFileEntries.hasMoreElements()) { // Get a zip file entry ZipEntry entry = zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = null; // destFile should be pointing to temppath\%date%\ try { destFile = new File(zipPath.getAbsolutePath(), currentEntry); destFile = new File(zipPath.getAbsolutePath(), destFile.getName()); } catch (NullPointerException e) { jlog.fatal("File not found" + destFile.getName()); } // If the entry is a .zip add it to the list so that it can be extracted if (currentEntry.endsWith(".zip")) { zipFiles.add(destFile); } try { // Extract file if not a directory if (!entry.isDirectory()) { // Stream the zip entry BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry)); int currentByte; // establish buffer for writing file byte data[] = new byte[BUFFER]; FileOutputStream fos = null; // Write the current file to disk try { fos = new FileOutputStream(destFile); } catch (FileNotFoundException e) { jlog.fatal("File not found " + destFile.getName()); } catch (SecurityException e) { jlog.fatal("Access denied to " + destFile.getName()); } BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); // read and write until last byte is encountered while ((currentByte = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, currentByte); } dest.flush(); dest.close(); is.close(); } } catch (IOException ioe) { jlog.fatal("IO exception in " + zipFile.getName()); } } try { zipFile.close(); } catch (IOException e) { jlog.fatal("IO exception when closing " + zipFile.getName()); } } // Recursively decompress the list of zip files for (File f : zipFiles) { decompressZip(f, zipPath); } return; }
From source file:de.xirp.plugin.PluginManager.java
/** * Extracts files from the plugins jar.// w w w . jav a 2 s .c o m * * @param info * the information about the plugin * @param destination * destination for extraction * @param comparer * comparer which returns <code>0</code> if an * element from the jar should be extracted * @param replace * string of the elements path which should be deleted * @param deleteOnExit * <code>true</code> if the extracted files should be * deleted on exit of the application. * @return <code>false</code> if an error occurred while * extraction */ private static boolean extractFromJar(PluginInfo info, String destination, Comparable<String> comparer, String replace, boolean deleteOnExit) { if (logClass.isTraceEnabled()) { logClass.trace(Constants.LINE_SEPARATOR + "Extracting for Plugin: " + info.getDefaultName() //$NON-NLS-1$ + " to path " + destination + Constants.LINE_SEPARATOR); //$NON-NLS-1$ } ZipInputStream zip = null; FileInputStream in = null; try { in = new FileInputStream(info.getAbsoluteJarPath()); zip = new ZipInputStream(in); ZipEntry entry = null; while ((entry = zip.getNextEntry()) != null) { // relative name with slashes to separate dirnames. String elementName = entry.getName(); // Check if it's an entry within Plugin Dir. // Only need to extract these if (comparer.compareTo(elementName) == 0) { // Remove Help Dir Name, because we don't like // to extract this parent dir elementName = elementName.replaceFirst(replace + JAR_SEPARATOR, "").trim(); //$NON-NLS-1$ if (!elementName.equalsIgnoreCase("")) { //$NON-NLS-1$ // if parent dir for File does not exist, // create // it File elementFile = new File(destination, elementName); if (!elementFile.exists()) { elementFile.getParentFile().mkdirs(); if (deleteOnExit) { DeleteManager.deleteOnShutdown(elementFile); } } // Only extract files, directorys are created // above with mkdirs if (!entry.isDirectory()) { FileOutputStream fos = new FileOutputStream(elementFile); byte[] buf = new byte[1024]; int len; while ((len = zip.read(buf)) > 0) { fos.write(buf, 0, len); } fos.close(); elementFile.setLastModified(entry.getTime()); } logClass.trace("Extracted: " + elementName + Constants.LINE_SEPARATOR); //$NON-NLS-1$ } } zip.closeEntry(); } } catch (IOException e) { logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$ return false; } finally { if (zip != null) { try { zip.close(); } catch (IOException e) { logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$ } } if (in != null) { try { in.close(); } catch (IOException e) { logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$ } } } return true; }
From source file:com.pari.nm.utils.backup.BackupRestore.java
public boolean unzip(File zipFile) { ZipFile zf = null;//from w w w. jav a 2 s . co m FileOutputStream fout = null; // File zipFile = new File(localDir, zipFileName); try { zf = new ZipFile(zipFile); Enumeration en = zf.entries(); while (en.hasMoreElements()) { ZipEntry ze = (ZipEntry) en.nextElement(); String currentEntry = ze.getName(); File destFile = new File(zipFile.getParent(), currentEntry); File destinationParent = destFile.getParentFile(); if (!destinationParent.exists()) { destinationParent.mkdirs(); destinationParent.setWritable(true, false); } System.err.println("ZIP ENTRY NAME:" + currentEntry); if (!ze.isDirectory()) { InputStream in = zf.getInputStream(ze); byte[] data = new byte[4096]; int read = 0; File extractFile = new File(zipFile.getParent(), ze.getName()); fout = new FileOutputStream(extractFile); while ((read = in.read(data)) != -1) { fout.write(data, 0, read); } fout.close(); } } return true; } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (zf != null) { zf.close(); } } catch (Exception ex) { } try { if (fout != null) { fout.close(); } } catch (Exception ex) { } } return false; }
From source file:de.climbingguide.erzgebirsgrenzgebiet.downloader.DownloaderThread.java
private boolean unpackZip(String path, String zipname) { InputStream is;/*from w w w .j ava2 s . c o m*/ ZipInputStream zis; BufferedInputStream bis; try { String filename; is = new FileInputStream(path + zipname); bis = new BufferedInputStream(is); zis = new ZipInputStream(bis); ZipEntry ze; // byte[] buffer = new byte[1024]; // int count; long fileSize = 0; //Gesamtdownloadgre bestimmen // while ((ze = zis.getNextEntry()) != null) // { ze = zis.getNextEntry(); fileSize = ze.getSize() + fileSize; // } int fileSizeInKB = (int) (fileSize / 1024); Message msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_UNZIP_STARTED, fileSizeInKB, 0, ""); activityHandler.sendMessage(msg); int bytesRead = 0, totalRead = 0; FileInputStream gis = new FileInputStream(path + zipname); BufferedInputStream fis = new BufferedInputStream(gis); ZipInputStream dis = new ZipInputStream(fis); while ((ze = dis.getNextEntry()) != null) { // zapis do souboru filename = ze.getName(); // Need to create directories if not exists, or // it will generate an Exception... if (ze.isDirectory()) { File fmd = new File(path + filename); fmd.mkdirs(); continue; } // // BufferedInputStream inStream = new BufferedInputStream(mFTPClient.retrieveFileStream(ftpPathName)); // File outFile = new File(fileName); FileOutputStream fileStream = new FileOutputStream(path + filename); byte[] data = new byte[KleFuEntry.DOWNLOAD_BUFFER_SIZE]; while (!isInterrupted() && (bytesRead = zis.read(data)) >= 0) { fileStream.write(data, 0, bytesRead); // update progress bar totalRead += bytesRead; int totalReadInKB = totalRead / 1024; msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_UPDATE_PROGRESS_BAR, totalReadInKB, 0); activityHandler.sendMessage(msg); } // fileStream.close(); // inStream.close(); // FileOutputStream fout = new FileOutputStream(path + filename); // // while ((count = zis.read(buffer)) != -1) // { // fout.write(buffer, 0, count); // } // // fout.close(); // zis.closeEntry(); } zis.close(); dis.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
From source file:com.adobe.phonegap.contentsync.Sync.java
private boolean unzipSync(File targetFile, String outputDirectory, ProgressEvent progress, CallbackContext callbackContext) { Log.d(LOG_TAG, "unzipSync called"); Log.d(LOG_TAG, "zip = " + targetFile.getAbsolutePath()); InputStream inputStream = null; ZipFile zip = null;// w ww . j a v a2s . co m boolean anyEntries = false; try { synchronized (progress) { if (progress.isAborted()) { return false; } } zip = new ZipFile(targetFile); // Since Cordova 3.3.0 and release of File plugins, files are accessed via cdvfile:// // Accept a path or a URI for the source zip. Uri zipUri = getUriForArg(targetFile.getAbsolutePath()); Uri outputUri = getUriForArg(outputDirectory); CordovaResourceApi resourceApi = webView.getResourceApi(); File tempFile = resourceApi.mapUriToFile(zipUri); if (tempFile == null || !tempFile.exists()) { sendErrorMessage("Zip file does not exist", UNZIP_ERROR, callbackContext); } File outputDir = resourceApi.mapUriToFile(outputUri); outputDirectory = outputDir.getAbsolutePath(); outputDirectory += outputDirectory.endsWith(File.separator) ? "" : File.separator; if (outputDir == null || (!outputDir.exists() && !outputDir.mkdirs())) { sendErrorMessage("Could not create output directory", UNZIP_ERROR, callbackContext); } OpenForReadResult zipFile = resourceApi.openForRead(zipUri); progress.setStatus(STATUS_EXTRACTING); progress.setLoaded(0); progress.setTotal(zip.size()); Log.d(LOG_TAG, "zip file len = " + zip.size()); inputStream = new BufferedInputStream(zipFile.inputStream); inputStream.mark(10); int magic = readInt(inputStream); if (magic != 875721283) { // CRX identifier inputStream.reset(); } else { // CRX files contain a header. This header consists of: // * 4 bytes of magic number // * 4 bytes of CRX format version, // * 4 bytes of public key length // * 4 bytes of signature length // * the public key // * the signature // and then the ordinary zip data follows. We skip over the header before creating the ZipInputStream. readInt(inputStream); // version == 2. int pubkeyLength = readInt(inputStream); int signatureLength = readInt(inputStream); inputStream.skip(pubkeyLength + signatureLength); } // The inputstream is now pointing at the start of the actual zip file content. ZipInputStream zis = new ZipInputStream(inputStream); inputStream = zis; ZipEntry ze; byte[] buffer = new byte[32 * 1024]; while ((ze = zis.getNextEntry()) != null) { synchronized (progress) { if (progress.isAborted()) { return false; } } anyEntries = true; String compressedName = ze.getName(); if (ze.getSize() > getFreeSpace()) { return false; } if (ze.isDirectory()) { File dir = new File(outputDirectory + compressedName); dir.mkdirs(); } else { File file = new File(outputDirectory + compressedName); file.getParentFile().mkdirs(); if (file.exists() || file.createNewFile()) { Log.w(LOG_TAG, "extracting: " + file.getPath()); FileOutputStream fout = new FileOutputStream(file); int count; while ((count = zis.read(buffer)) != -1) { fout.write(buffer, 0, count); } fout.close(); } } progress.addLoaded(1); updateProgress(callbackContext, progress); zis.closeEntry(); } } catch (Exception e) { String errorMessage = "An error occurred while unzipping."; sendErrorMessage(errorMessage, UNZIP_ERROR, callbackContext); Log.e(LOG_TAG, errorMessage, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } if (zip != null) { try { zip.close(); } catch (IOException e) { } } } if (anyEntries) return true; else return false; }
From source file:org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl.java
/** * unzips the payload file/*w ww . j a va 2 s .c om*/ * * @param file * @param tempfileName */ private void unzipFile(File file, String tempfileName) { int buffer = 2048; BufferedOutputStream dest = null; ZipInputStream zis = null; try { FileInputStream fis = new FileInputStream(file); zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { log.debug("Extracting: " + entry); int count; byte data[] = new byte[buffer]; String outputFilename = tempfileName + File.separator + entry.getName(); createDirIfNeeded(tempfileName, entry); // write the files to the disk if (!entry.isDirectory()) { FileOutputStream fos = new FileOutputStream(outputFilename); dest = new BufferedOutputStream(fos, buffer); while ((count = zis.read(data, 0, buffer)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } } } catch (Exception e) { log.error("Exception is occurred in unzipping payload file. Reason:" + e.getMessage()); throw new AutoscalerServiceException(e.getMessage(), e); } finally { closeStream(zis); closeStream(dest); } }
From source file:com.xpn.xwiki.plugin.packaging.Package.java
/** * Load this package in memory from an InputStream. It may be installed later using {@link #install(XWikiContext)}. * /*w ww . ja v a 2 s . co m*/ * @param file an InputStream of a zipped package file * @param context current XWikiContext * @return an empty string, useless. * @throws IOException while reading the ZipFile * @throws XWikiException when package content is broken * @since 2.3M2 */ public String Import(InputStream file, XWikiContext context) throws IOException, XWikiException { ZipInputStream zis = new ZipInputStream(file); ZipEntry entry; Document description = null; try { zis = new ZipInputStream(file); List<XWikiDocument> docsToLoad = new LinkedList<XWikiDocument>(); /* * Loop 1: Cycle through the zip input stream and load out all of the documents, when we find the * package.xml file we put it aside to so that we only include documents which are in the file. */ while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory() || (entry.getName().indexOf("META-INF") != -1)) { // The entry is either a directory or is something inside of the META-INF dir. // (we use that directory to put meta data such as LICENSE/NOTICE files.) continue; } else if (entry.getName().compareTo(DefaultPackageFileName) == 0) { // The entry is the manifest (package.xml). Read this differently. description = fromXml(new CloseShieldInputStream(zis)); } else { XWikiDocument doc = null; try { doc = readFromXML(new CloseShieldInputStream(zis)); } catch (Throwable ex) { LOGGER.warn("Failed to parse document [" + entry.getName() + "] from XML during import, thus it will not be installed. " + "The error was: " + ex.getMessage()); // It will be listed in the "failed documents" section after the import. addToErrors(entry.getName().replaceAll("/", "."), context); continue; } // Run all of the registered DocumentFilters on this document and // if no filters throw exceptions, add it to the list to import. try { this.filter(doc, context); docsToLoad.add(doc); } catch (ExcludeDocumentException e) { LOGGER.info("Skip the document '" + doc.getDocumentReference() + "'"); } } } // Make sure a manifest was included in the package... if (description == null) { throw new PackageException(XWikiException.ERROR_XWIKI_UNKNOWN, "Could not find the package definition"); } /* * Loop 2: Cycle through the list of documents and if they are in the manifest then add them, otherwise log * a warning and add them to the skipped list. */ for (XWikiDocument doc : docsToLoad) { if (documentExistInPackageFile(doc.getFullName(), doc.getLanguage(), description)) { this.add(doc, context); } else { LOGGER.warn("document " + doc.getDocumentReference() + " does not exist in package definition." + " It will not be installed."); // It will be listed in the "skipped documents" section after the // import. addToSkipped(doc.getFullName(), context); } } updateFileInfos(description); } catch (DocumentException e) { throw new PackageException(XWikiException.ERROR_XWIKI_UNKNOWN, "Error when reading the XML"); } return ""; }