List of usage examples for java.util.zip ZipFile close
public void close() throws IOException
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 w w w . j a v a2 s . c om*/ 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:org.commonjava.maven.galley.filearc.internal.ZipPublish.java
private Boolean rewriteArchive(final File dest, final String path) { final boolean isJar = isJarOperation(); final File src = new File(dest.getParentFile(), dest.getName() + ".old"); dest.renameTo(src);// w w w.ja va 2s. com InputStream zin = null; ZipFile zfIn = null; FileOutputStream fos = null; ZipOutputStream zos = null; ZipFile zfOut = null; try { fos = new FileOutputStream(dest); zos = isJar ? new JarOutputStream(fos) : new ZipOutputStream(fos); zfOut = isJar ? new JarFile(dest) : new ZipFile(dest); zfIn = isJar ? new JarFile(src) : new ZipFile(src); for (final Enumeration<? extends ZipEntry> en = zfIn.entries(); en.hasMoreElements();) { final ZipEntry inEntry = en.nextElement(); final String inPath = inEntry.getName(); try { if (inPath.equals(path)) { zin = stream; } else { zin = zfIn.getInputStream(inEntry); } final ZipEntry entry = zfOut.getEntry(inPath); zos.putNextEntry(entry); copy(stream, zos); } finally { closeQuietly(zin); } } return true; } catch (final IOException e) { error = new TransferException("Failed to write path: %s to EXISTING archive: %s. Reason: %s", e, path, dest, e.getMessage()); } finally { closeQuietly(zos); closeQuietly(fos); if (zfOut != null) { //noinspection EmptyCatchBlock try { zfOut.close(); } catch (final IOException e) { } } if (zfIn != null) { //noinspection EmptyCatchBlock try { zfIn.close(); } catch (final IOException e) { } } closeQuietly(stream); } return false; }
From source file:pl.psnc.synat.wrdz.mdz.integrity.IntegrityVerifierBean.java
@Override public boolean isCorrupted(String identifier, File file) { ZipFile zip = null; try {// w w w . j a v a 2s .c o m zip = new ZipFile(file); List<FileHashDto> fileHashes = hashBrowser.getFileHashes(identifier); for (FileHashDto fileHash : fileHashes) { ZipEntry entry = zip.getEntry(fileHash.getObjectFilepath()); if (entry == null) { // file not found in the archive return true; } String calculatedHash; InputStream stream = zip.getInputStream(entry); try { calculatedHash = calculateHash(stream, fileHash.getHashType()); } finally { IOUtils.closeQuietly(stream); } if (!calculatedHash.equals(fileHash.getHashValue())) { return true; } } } catch (ZipException e) { throw new WrdzRuntimeException("Given file is not a valid zip archive", e); } catch (NoSuchAlgorithmException e) { throw new WrdzRuntimeException("Unable to locate appropriate hashing algorithm classes", e); } catch (ObjectNotFoundException e) { throw new WrdzRuntimeException("Digital object not found in ZMD", e); } catch (IOException e) { throw new WrdzRuntimeException("Error while verifying object integrity", e); } finally { if (zip != null) { try { zip.close(); } catch (IOException e) { logger.warn("Could not close the zip file", e); } } } return false; }
From source file:com.krawler.esp.fileparser.wordparser.DocxParser.java
public String extractText(String filepath) { StringBuilder sb = new StringBuilder(); ZipFile docxfile = null; try {/* w ww . j a va2 s. c om*/ docxfile = new ZipFile(filepath); } catch (Exception e) { // file corrupt or otherwise could not be found logger.warn(e.getMessage(), e); return sb.toString(); } InputStream in = null; try { ZipEntry ze = docxfile.getEntry("word/document.xml"); in = docxfile.getInputStream(ze); } catch (NullPointerException nulle) { System.err.println("Expected entry word/document.xml does not exist"); logger.warn(nulle.getMessage(), nulle); return sb.toString(); } catch (IOException ioe) { logger.warn(ioe.getMessage(), ioe); return sb.toString(); } Document document = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(in); } catch (ParserConfigurationException pce) { logger.warn(pce.getMessage(), pce); return sb.toString(); } catch (SAXException sex) { sex.printStackTrace(); return sb.toString(); } catch (IOException ioe) { logger.warn(ioe.getMessage(), ioe); return sb.toString(); } finally { try { docxfile.close(); } catch (IOException ioe) { System.err.println("Exception closing file."); logger.warn(ioe.getMessage(), ioe); } } NodeList list = document.getElementsByTagName("w:t"); List<String> content = new ArrayList<String>(); for (int i = 0; i < list.getLength(); i++) { Node aNode = list.item(i); content.add(aNode.getFirstChild().getNodeValue()); } for (String s : content) { sb.append(s); } return sb.toString(); }
From source file:org.jboss.windup.util.RecursiveZipMetaFactory.java
protected void recursivelyExtract(ZipMetadata parent, ZipFile zip, File outputDirectory) { String fileName = StringUtils.substringAfterLast(zip.getName(), File.separator); File subOutputDir = new File(outputDirectory.getAbsolutePath() + File.separator + fileName); ZipEntry entry;/* ww w. java 2s. c o m*/ Enumeration<?> e = zip.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); // must be a candidate file. if (!entry.isDirectory()) { if (archiveEndInEntryOfInterest(entry.getName())) { try { File extracted = unzipEntry(parent, entry, zip, subOutputDir); ZipFile zf = new ZipFile(extracted); // we should know it is a valid zip here.. ZipMetadata arch = generateArchive(parent, extracted); LOG.info("Prepared ZipMetadata: " + arch.getRelativePath()); recursivelyExtract(arch, zf, new File(StringUtils.substringBeforeLast(zf.getName(), File.separator))); } catch (FileNotFoundException e1) { LOG.warn("Skipping invalid zip entry: " + entry); } catch (IOException e1) { LOG.warn("Skipping invalid zip entry: " + entry); } } } } try { zip.close(); } catch (IOException e1) { LOG.error("Exception closing zip.", e1); } }
From source file:fr.fastconnect.factory.tibco.bw.fcunit.PrepareTestMojo.java
private void removeFileInZipContaining(List<String> contentFilter, File zipFile) throws ZipException, IOException { ZipScanner zs = new ZipScanner(); zs.setSrc(zipFile);/*from w w w .jav a2 s . c om*/ String[] includes = { "**/*.process" }; zs.setIncludes(includes); //zs.setCaseSensitive(true); zs.init(); zs.scan(); File originalProjlib = zipFile; // to be overwritten File tmpProjlib = new File(zipFile.getAbsolutePath() + ".tmp"); // to read FileUtils.copyFile(originalProjlib, tmpProjlib); ZipFile listZipFile = new ZipFile(tmpProjlib); ZipInputStream readZipFile = new ZipInputStream(new FileInputStream(tmpProjlib)); ZipOutputStream writeZipFile = new ZipOutputStream(new FileOutputStream(originalProjlib)); ZipEntry zipEntry; boolean keep; while ((zipEntry = readZipFile.getNextEntry()) != null) { keep = true; for (String filter : contentFilter) { keep = keep && !containsString(filter, listZipFile.getInputStream(zipEntry)); } // if (!containsString("<pd:type>com.tibco.pe.core.OnStartupEventSource</pd:type>", listZipFile.getInputStream(zipEntry)) // && !containsString("<pd:type>com.tibco.plugin.jms.JMSTopicEventSource</pd:type>", listZipFile.getInputStream(zipEntry))) { if (keep) { writeZipFile.putNextEntry(zipEntry); int len = 0; byte[] buf = new byte[1024]; while ((len = readZipFile.read(buf)) >= 0) { writeZipFile.write(buf, 0, len); } writeZipFile.closeEntry(); //getLog().info("written"); } else { getLog().info("removed " + zipEntry.getName()); } } writeZipFile.close(); readZipFile.close(); listZipFile.close(); originalProjlib.setLastModified(originalProjlib.lastModified() - 100000); }
From source file:net.sourceforge.jweb.maven.mojo.PropertiesOverideMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { if (disabled) { this.getLog().info("plugin was disabled"); return;/* w w w. jav a2s . c o m*/ } processConfiguration(); if (replacements.isEmpty()) { this.getLog().info("Nothing to replace with"); return; } String name = this.builddir.getAbsolutePath() + File.separator + this.finalName + "." + this.packing;//the final package this.getLog().debug("final artifact: " + name);// the final package try { File finalWarFile = new File(name); File tempFile = File.createTempFile(finalWarFile.getName(), null); tempFile.delete();//check deletion boolean renameOk = finalWarFile.renameTo(tempFile); if (!renameOk) { getLog().error("Can not rename file, please check."); return; } ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile)); ZipFile zipFile = new ZipFile(tempFile); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (acceptMime(entry)) { getLog().info("applying replacements for " + entry.getName()); InputStream inputStream = zipFile.getInputStream(entry); String src = IOUtils.toString(inputStream, encoding); //do replacement for (Entry<String, String> e : replacements.entrySet()) { src = src.replaceAll("#\\{" + e.getKey() + "}", e.getValue()); } out.putNextEntry(new ZipEntry(entry.getName())); IOUtils.write(src, out, encoding); inputStream.close(); } else { //not repalce, just put entry back to out zip out.putNextEntry(entry); InputStream inputStream = zipFile.getInputStream(entry); byte[] buf = new byte[512]; int len = -1; while ((len = inputStream.read(buf)) > 0) { out.write(buf, 0, len); } inputStream.close(); continue; } } zipFile.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.guvnor.m2repo.backend.server.GuvnorM2Repository.java
private File appendPOMToJar(final String pom, final String jarPath, final GAV gav) { File originalJarFile = new File(jarPath); File appendedJarFile = new File(jarPath + ".tmp"); try {/*from w w w. ja v a 2 s.co m*/ ZipFile war = new ZipFile(originalJarFile); ZipOutputStream append = new ZipOutputStream(new FileOutputStream(appendedJarFile)); // first, copy contents from existing war Enumeration<? extends ZipEntry> entries = war.entries(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); append.putNextEntry(e); if (!e.isDirectory()) { IOUtil.copy(war.getInputStream(e), append); } append.closeEntry(); } // append pom.xml ZipEntry e = new ZipEntry(getPomXmlPath(gav)); append.putNextEntry(e); append.write(pom.getBytes()); append.closeEntry(); // close war.close(); append.close(); } catch (ZipException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } return appendedJarFile; }
From source file:com.microsoft.tfs.client.common.ui.teambuild.commands.CreateUploadZipCommand.java
/** * Copy zip file and remove ignored files * * @param srcFile//from www. jav a 2s .com * @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:eionet.meta.exports.ods.Ods.java
/** * Zips file.//from www . ja v a 2 s. c o m * * @param fileToZip * file to zip (full path) * @param fileName * file name * @throws java.lang.Exception * if operation fails. */ private void zip(String fileToZip, String fileName) throws Exception { // get source file File src = new File(workingFolderPath + ODS_FILE_NAME); ZipFile zipFile = new ZipFile(src); // create temp file for output File tempDst = new File(workingFolderPath + ODS_FILE_NAME + ".zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tempDst)); // iterate on each entry in zip file Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = entries.nextElement(); BufferedInputStream bis; if (StringUtils.equals(fileName, zipEntry.getName())) { bis = new BufferedInputStream(new FileInputStream(new File(fileToZip))); } else { bis = new BufferedInputStream(zipFile.getInputStream(zipEntry)); } ZipEntry ze = new ZipEntry(zipEntry.getName()); zos.putNextEntry(ze); while (bis.available() > 0) { zos.write(bis.read()); } zos.closeEntry(); bis.close(); } zos.finish(); zos.close(); zipFile.close(); // rename file src.delete(); tempDst.renameTo(src); }