List of usage examples for java.util.zip ZipEntry isDirectory
public boolean isDirectory()
From source file:ca.phon.app.workspace.ExtractProjectArchiveTask.java
/** * Extract contents of a zip file to the destination directory. *//* w w w. j a v a 2 s .co m*/ private void extractArchive(File archive, File destDir) throws IOException { BufferedOutputStream out = null; BufferedInputStream in = null; try (ZipFile zip = new ZipFile(archive)) { // create output directory if it does not exist if (destDir.exists() && !destDir.isDirectory()) { throw new IOException("'" + destDir.getAbsolutePath() + "' is not a directory."); } if (!destDir.exists()) { setProperty(STATUS_PROP, "Creating output directory"); destDir.mkdirs(); } Tuple<ZippedProjectType, String> zipDetect = getZipDetect(); ZipEntry entry = null; Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { if (isShutdown()) { return; } entry = entries.nextElement(); String entryName = entry.getName(); File outFile = null; if (zipDetect.getObj1() == ZippedProjectType.PROJECT_BASE_INCLUDED) { // dest dir has already b outFile = new File(destDir, entryName.replaceFirst(zipDetect.getObj2(), "")); } else { outFile = new File(destDir, entryName); } if (entry.isDirectory()) { if (!outFile.exists()) outFile.mkdirs(); } else { LOGGER.info("Extracting: " + entry); setProperty(STATUS_PROP, "Extracting: " + entry); in = new BufferedInputStream(zip.getInputStream(entry)); int count = -1; byte data[] = new byte[ZIP_BUFFER]; if (outFile.exists()) { LOGGER.warning("Overwriting file '" + outFile.getAbsolutePath() + "'"); } File parentFile = outFile.getParentFile(); if (!parentFile.exists()) parentFile.mkdirs(); FileOutputStream fos = new FileOutputStream(outFile); out = new BufferedOutputStream(fos, ZIP_BUFFER); while ((count = in.read(data, 0, ZIP_BUFFER)) != -1) { out.write(data, 0, count); } out.flush(); out.close(); in.close(); } } } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e); throw e; } setProperty(STATUS_PROP, "Finished"); }
From source file:com.drevelopment.couponcodes.bukkit.updater.Updater.java
/** * Part of Zip-File-Extractor, modified by Gravity for use with Updater. * * @param file the location of the file to extract. *///from w w w .java 2 s . c o m private void unzip(String file) { final File fSourceZip = new File(file); try { final String zipPath = file.substring(0, file.length() - 4); ZipFile zipFile = new ZipFile(fSourceZip); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); File destinationFilePath = new File(zipPath, entry.getName()); this.fileIOOrError(destinationFilePath.getParentFile(), destinationFilePath.getParentFile().mkdirs(), true); if (!entry.isDirectory()) { final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; final byte[] buffer = new byte[Updater.BYTE_SIZE]; final FileOutputStream fos = new FileOutputStream(destinationFilePath); final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE); while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) { bos.write(buffer, 0, b); } bos.flush(); bos.close(); bis.close(); final String name = destinationFilePath.getName(); if (name.endsWith(".jar") && this.pluginExists(name)) { File output = new File(this.updateFolder, name); this.fileIOOrError(output, destinationFilePath.renameTo(output), true); } } } zipFile.close(); // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. moveNewZipFiles(zipPath); } catch (final IOException e) { this.plugin.getLogger().log(Level.SEVERE, "The auto-updater tried to unzip a new update file, but was unsuccessful.", e); this.result = Updater.UpdateResult.FAIL_DOWNLOAD; } finally { this.fileIOOrError(fSourceZip, fSourceZip.delete(), false); } }
From source file:net.sourceforge.squirrel_sql.client.update.UpdateUtilImpl.java
/** * TODO: Move this to IOUtilities Extracts the specified zip file to the specified output directory. * //from w w w . j av a 2 s . c o m * @param zipFile * @param outputDirectory * @throws IOException */ public void extractZipFile(FileWrapper zipFile, FileWrapper outputDirectory) throws IOException { if (!outputDirectory.isDirectory()) { s_log.error("Output directory specified (" + outputDirectory.getAbsolutePath() + ") doesn't appear to be a directory"); return; } FileInputStream fis = null; ZipInputStream zis = null; FileOutputStream fos = null; try { fis = new FileInputStream(zipFile.getAbsolutePath()); zis = new ZipInputStream(fis); ZipEntry zipEntry = zis.getNextEntry(); while (zipEntry != null) { String name = zipEntry.getName(); if (zipEntry.isDirectory()) { checkDir(outputDirectory, name); } else { FileWrapper newFile = _fileWrapperFactory.create(outputDirectory, name); if (newFile.exists()) { if (s_log.isInfoEnabled()) { s_log.info("Deleting extraction file that already exists:" + newFile.getAbsolutePath()); } newFile.delete(); } fos = new FileOutputStream(newFile.getAbsolutePath()); byte[] buffer = new byte[ZIP_EXTRACTION_BUFFER_SIZE]; int n = 0; while ((n = zis.read(buffer, 0, ZIP_EXTRACTION_BUFFER_SIZE)) > -1) { fos.write(buffer, 0, n); } fos.close(); } zipEntry = zis.getNextEntry(); } } finally { _iou.closeOutputStream(fos); _iou.closeInputStream(fis); _iou.closeInputStream(zis); } }
From source file:com.simpligility.maven.plugins.android.phase09package.ApkMojo.java
private void updateWithMetaInf(ZipOutputStream zos, File jarFile, Set<String> entries, boolean metaInfOnly) throws IOException { ZipFile zin = new ZipFile(jarFile); for (Enumeration<? extends ZipEntry> en = zin.entries(); en.hasMoreElements();) { ZipEntry ze = en.nextElement(); if (ze.isDirectory()) { continue; }/*from w ww . j ava 2 s. c o m*/ String zn = ze.getName(); if (metaInfOnly) { if (!zn.startsWith("META-INF/")) { continue; } if (!this.apkMetaInf.isIncluded(zn)) { continue; } } boolean resourceTransformed = false; if (transformers != null) { for (ResourceTransformer transformer : transformers) { if (transformer.canTransformResource(zn)) { getLog().info("Transforming " + zn + " using " + transformer.getClass().getName()); InputStream is = zin.getInputStream(ze); transformer.processResource(zn, is, null); is.close(); resourceTransformed = true; break; } } } if (!resourceTransformed) { // Avoid duplicates that aren't accounted for by the resource transformers if (metaInfOnly && this.extractDuplicates && !entries.add(zn)) { continue; } InputStream is = zin.getInputStream(ze); final ZipEntry ne; if (ze.getMethod() == ZipEntry.STORED) { ne = new ZipEntry(ze); } else { ne = new ZipEntry(zn); } zos.putNextEntry(ne); copyStreamWithoutClosing(is, zos); is.close(); zos.closeEntry(); } } zin.close(); }
From source file:com.photon.maven.plugins.android.phase09package.ApkMojo.java
private void computeDuplicateFiles(File jar) throws IOException { ZipFile file = new ZipFile(jar); Enumeration<? extends ZipEntry> list = file.entries(); while (list.hasMoreElements()) { ZipEntry ze = list.nextElement(); if (!(ze.getName().contains("META-INF/") || ze.isDirectory())) { // Exclude // META-INF // and // Directories List<File> l = m_jars.get(ze.getName()); if (l == null) { l = new ArrayList<File>(); m_jars.put(ze.getName(), l); }/*from ww w .j a v a 2 s. c o m*/ l.add(jar); } } }
From source file:it.greenvulcano.configuration.BaseConfigurationManager.java
@Override public void deploy(String name) throws XMLConfigException, FileNotFoundException { Path configurationArchivePath = getConfigurationPath(name); Path current = Paths.get(XMLConfig.getBaseConfigPath()); Path staging = current.getParent().resolve("deploy"); Path destination = current.getParent().resolve(name); if (LOCK.tryLock()) { if (Files.exists(configurationArchivePath) && !Files.isDirectory(configurationArchivePath)) { try { ZipInputStream configurationArchive = new ZipInputStream( Files.newInputStream(configurationArchivePath, StandardOpenOption.READ)); LOG.debug("Starting deploy of configuration " + name); ZipEntry zipEntry = null; for (Path cfgFile : Files.walk(current).collect(Collectors.toSet())) { if (!Files.isDirectory(cfgFile)) { Path target = staging.resolve(current.relativize(cfgFile)); Files.createDirectories(target); Files.copy(cfgFile, target, StandardCopyOption.REPLACE_EXISTING); }/*w ww.ja va 2 s . c o m*/ } LOG.debug("Staging new config " + name); while ((zipEntry = configurationArchive.getNextEntry()) != null) { Path entryPath = staging.resolve(zipEntry.getName()); LOG.debug("Adding resource: " + entryPath); if (zipEntry.isDirectory()) { entryPath.toFile().mkdirs(); } else { Path parent = entryPath.getParent(); if (!Files.exists(parent)) { Files.createDirectories(parent); } Files.copy(configurationArchive, entryPath, StandardCopyOption.REPLACE_EXISTING); } } //**** Deleting old config dir LOG.debug("Removing old config: " + current); Files.walk(current, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) .map(java.nio.file.Path::toFile).forEach(File::delete); LOG.debug("Deploy new config " + name + " in path " + destination); Files.move(staging, destination, StandardCopyOption.ATOMIC_MOVE); setXMLConfigBasePath(destination.toString()); LOG.debug("Deploy complete"); deployListeners.forEach(l -> l.onDeploy(destination)); } catch (Exception e) { if (Objects.nonNull(staging) && Files.exists(staging)) { LOG.error("Deploy failed, rollback to previous configuration", e); try { Files.walk(staging, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) .map(java.nio.file.Path::toFile).forEach(File::delete); setXMLConfigBasePath(current.toString()); } catch (IOException | InvalidSyntaxException rollbackException) { LOG.error("Failed to delete old configuration", e); } } else { LOG.error("Deploy failed", e); } throw new XMLConfigException("Deploy failed", e); } finally { LOCK.unlock(); } } else { throw new FileNotFoundException(configurationArchivePath.toString()); } } else { throw new IllegalStateException("A deploy is already in progress"); } }
From source file:freenet.client.ArchiveManager.java
private void handleZIPArchive(ArchiveStoreContext ctx, FreenetURI key, InputStream data, String element, ArchiveExtractCallback callback, MutableBoolean gotElement, boolean throwAtExit, ClientContext context) throws ArchiveFailureException, ArchiveRestartException { if (logMINOR) Logger.minor(this, "Handling a ZIP Archive"); ZipInputStream zis = null;/*from w w w . j a va2 s . com*/ try { zis = new ZipInputStream(data); // MINOR: Assumes the first entry in the zip is a directory. ZipEntry entry; byte[] buf = new byte[32768]; HashSet<String> names = new HashSet<String>(); boolean gotMetadata = false; outerZIP: while (true) { entry = zis.getNextEntry(); if (entry == null) break; if (entry.isDirectory()) continue; String name = stripLeadingSlashes(entry.getName()); if (names.contains(name)) { Logger.error(this, "Duplicate key " + name + " in archive " + key); continue; } long size = entry.getSize(); if (name.equals(".metadata")) gotMetadata = true; if (size > maxArchivedFileSize && !name.equals(element)) { addErrorElement(ctx, key, name, "File too big: " + maxArchivedFileSize + " greater than current archived file size limit " + maxArchivedFileSize, true); } else { // Read the element long realLen = 0; Bucket output = tempBucketFactory.makeBucket(size); OutputStream out = output.getOutputStream(); try { int readBytes; while ((readBytes = zis.read(buf)) > 0) { out.write(buf, 0, readBytes); readBytes += realLen; if (readBytes > maxArchivedFileSize) { addErrorElement(ctx, key, name, "File too big: " + maxArchivedFileSize + " greater than current archived file size limit " + maxArchivedFileSize, true); out.close(); out = null; output.free(); continue outerZIP; } } } finally { if (out != null) out.close(); } if (size <= maxArchivedFileSize) { addStoreElement(ctx, key, name, output, gotElement, element, callback, context); names.add(name); trimStoredData(); } else { // We are here because they asked for this file. callback.gotBucket(output, context); gotElement.value = true; addErrorElement( ctx, key, name, "File too big: " + size + " greater than current archived file size limit " + maxArchivedFileSize, true); } } } // If no metadata, generate some if (!gotMetadata) { generateMetadata(ctx, key, names, gotElement, element, callback, context); trimStoredData(); } if (throwAtExit) throw new ArchiveRestartException("Archive changed on re-fetch"); if ((!gotElement.value) && element != null) callback.notInArchive(context); } catch (IOException e) { throw new ArchiveFailureException("Error reading archive: " + e.getMessage(), e); } finally { if (zis != null) { try { zis.close(); } catch (IOException e) { Logger.error(this, "Failed to close stream: " + e, e); } } } }
From source file:org.universAAL.itests.IntegrationTest.java
/** * Helper method for extracting zipped archive provided as input stream into * given directory.// www . jav a2 s . c om * * @param is * @param destDirStr */ private void unzipInpuStream(final InputStream is, final String destDirStr) { try { File destDir = new File(destDirStr); final int BUFFER = 1024; BufferedOutputStream dest = null; ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { System.out.println("Extracting: " + entry); if (entry.getName().startsWith("META-INF")) { // META-INF (which includes MANIFEST) should not be // unpacked. It should be just ignored continue; } if (entry.isDirectory()) { File newDir = new File(destDir, entry.getName()); newDir.mkdirs(); } else { int count; byte[] data = new byte[BUFFER]; // write the files to the disk FileOutputStream fos = new FileOutputStream(new File(destDir, entry.getName())); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } } zis.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.web.server.SARDeployer.java
/** * This method extracts the SAR archive and configures for the SAR and starts the services * @param file/*from w w w .ja v a 2 s. c om*/ * @param warDirectoryPath * @throws IOException */ public void extractSar(File file, String warDirectoryPath) throws IOException { ZipFile zip = new ZipFile(file); ZipEntry ze = null; String fileName = file.getName(); fileName = fileName.substring(0, fileName.indexOf('.')); fileName += "sar"; String fileDirectory; CopyOnWriteArrayList classPath = new CopyOnWriteArrayList(); Enumeration<? extends ZipEntry> entries = zip.entries(); int numBytes; while (entries.hasMoreElements()) { ze = entries.nextElement(); // //System.out.println("Unzipping " + ze.getName()); String filePath = deployDirectory + "/" + fileName + "/" + ze.getName(); if (!ze.isDirectory()) { fileDirectory = filePath.substring(0, filePath.lastIndexOf('/')); } else { fileDirectory = filePath; } // //System.out.println(fileDirectory); createDirectory(fileDirectory); if (!ze.isDirectory()) { FileOutputStream fout = new FileOutputStream(filePath); byte[] inputbyt = new byte[8192]; InputStream istream = zip.getInputStream(ze); while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) { fout.write(inputbyt, 0, numBytes); } fout.close(); istream.close(); if (ze.getName().endsWith(".jar")) { classPath.add(filePath); } } } zip.close(); URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = loader.getURLs(); WebClassLoader sarClassLoader = new WebClassLoader(urls); for (int index = 0; index < classPath.size(); index++) { System.out.println("file:" + classPath.get(index)); new WebServer().addURL(new URL("file:" + classPath.get(index)), sarClassLoader); } new WebServer().addURL(new URL("file:" + deployDirectory + "/" + fileName + "/"), sarClassLoader); sarsMap.put(fileName, sarClassLoader); System.out.println(sarClassLoader.geturlS()); try { Sar sar = (Sar) sardigester.parse(new InputSource( new FileInputStream(deployDirectory + "/" + fileName + "/META-INF/" + "mbean-service.xml"))); CopyOnWriteArrayList mbeans = sar.getMbean(); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); System.out.println(mbs); ObjectName objName; for (int index = 0; index < mbeans.size(); index++) { Mbean mbean = (Mbean) mbeans.get(index); System.out.println(mbean.getObjectname()); System.out.println(mbean.getCls()); objName = new ObjectName(mbean.getObjectname()); Class helloWorldService = sarClassLoader.loadClass(mbean.getCls()); Object obj = helloWorldService.newInstance(); if (mbs.isRegistered(objName)) { mbs.invoke(objName, "stopService", null, null); //mbs.invoke(objName, "destroy", null, null); mbs.unregisterMBean(objName); } mbs.registerMBean(obj, objName); CopyOnWriteArrayList attrlist = mbean.getMbeanAttribute(); if (attrlist != null) { for (int count = 0; count < attrlist.size(); count++) { MBeanAttribute attr = (MBeanAttribute) attrlist.get(count); Attribute mbeanattribute = new Attribute(attr.getName(), attr.getValue()); mbs.setAttribute(objName, mbeanattribute); } } mbs.invoke(objName, "startService", null, null); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedObjectNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstanceAlreadyExistsException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MBeanRegistrationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NotCompliantMBeanException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstanceNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ReflectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MBeanException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidAttributeValueException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (AttributeNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:net.wastl.webmail.config.ExtConfigListener.java
/** * @param baseDir//from ww w . ja v a2 s. c o m * Parent directory of metaFile * @param metaFile * Properties file to be created. IT CAN NOT EXIST YET! * @throws IOException * if fail to create new XML Storage system */ protected void installXmlStorage(File baseDir, File metaFile) throws IOException { log.warn("Will attempt install a brand new data store"); final File dataDir = new File(baseDir, "data"); if (dataDir.exists()) throw new IOException("Target data path dir already exists: " + dataDir.getAbsolutePath()); if (!baseDir.isDirectory()) { final File parentDir = baseDir.getParentFile(); if (!parentDir.canWrite()) throw new IOException("Cannot create base RT directory '" + baseDir.getAbsolutePath() + "'"); if (!baseDir.mkdir()) throw new IOException("Failed to create base RT directory '" + baseDir.getAbsolutePath() + "'"); log.debug("Created base RT dir '" + baseDir.getAbsolutePath() + "'"); mkLockFile(); } if (!baseDir.canWrite()) throw new IOException( "Do not have privilegest to create meta file '" + metaFile.getAbsolutePath() + "'"); if (!dataDir.mkdir()) throw new IOException("Failed to create data directory '" + dataDir.getAbsolutePath() + "'"); log.debug("Created data dir '" + dataDir.getAbsolutePath() + "'"); // In my experience, you can't trust the return values of the // File.mkdir() method. But the file creations or extractions // wild fail below in that case, so that's no problem. // Could create a Properties object and save it, but why? final PrintWriter pw = new PrintWriter(new FileWriter(metaFile)); try { pw.println("webmail.data.path: ${rtconfig.dir}/data"); pw.println("webmail.mimetypes.filepath: " + "${rtconfig.dir}/mimetypes.txt"); pw.flush(); } finally { pw.close(); } final InputStream zipFileStream = getClass().getResourceAsStream("/data.zip"); if (zipFileStream == null) throw new IOException("Zip file 'data.zip' missing from web application"); final InputStream mimeInStream = getClass().getResourceAsStream("/mimetypes.txt"); if (mimeInStream == null) throw new IOException("Mime-types file 'mimetypes.txt' missing from web application"); ZipEntry entry; File newNode; FileOutputStream fileStream; long fileSize, bytesRead; int i; final byte[] buffer = new byte[10240]; final FileOutputStream mimeOutStream = new FileOutputStream(new File(baseDir, "mimetypes.txt")); try { while ((i = mimeInStream.read(buffer)) > 0) { mimeOutStream.write(buffer, 0, i); } mimeOutStream.flush(); } finally { mimeOutStream.close(); } log.debug("Extracted mime types file"); final ZipInputStream zipStream = new ZipInputStream(zipFileStream); try { while ((entry = zipStream.getNextEntry()) != null) { newNode = new File(dataDir, entry.getName()); if (entry.isDirectory()) { if (!newNode.mkdir()) throw new IOException( "Failed to extract dir '" + entry.getName() + "' from 'data.zip' file"); log.debug("Extracted dir '" + entry.getName() + "' to '" + newNode.getAbsolutePath() + "'"); zipStream.closeEntry(); continue; } fileSize = entry.getSize(); fileStream = new FileOutputStream(newNode); try { bytesRead = 0; while ((i = zipStream.read(buffer)) > 0) { fileStream.write(buffer, 0, i); bytesRead += i; } fileStream.flush(); } finally { fileStream.close(); } zipStream.closeEntry(); if (bytesRead != fileSize) throw new IOException("Expected " + fileSize + " bytes for '" + entry.getName() + ", but extracted " + bytesRead + " bytes to '" + newNode.getAbsolutePath() + "'"); log.debug("Extracted file '" + entry.getName() + "' to '" + newNode.getAbsolutePath() + "'"); } } finally { zipStream.close(); } }