List of usage examples for java.util.zip ZipFile ZipFile
public ZipFile(File file) throws ZipException, IOException
From source file:com.seajas.search.contender.service.modifier.FeedModifierService.java
/** * Retrieve the content of a result feed URL. * /*from w w w . j av a 2 s .c o m*/ * @param uri * @param encodingOverride * @param userAgent * @param resultHeaders * @return Reader */ private Reader getContent(final URI uri, final String encodingOverride, final String userAgent, final Map<String, String> resultHeaders) { Reader result = null; String contentType = null; // Retrieve the feed try { InputStream inputStream = null; if (uri.getScheme().equalsIgnoreCase("ftp") || uri.getScheme().equalsIgnoreCase("ftps")) { FTPClient ftpClient = uri.getScheme().equalsIgnoreCase("ftps") ? new FTPSClient() : new FTPClient(); try { ftpClient.connect(uri.getHost(), uri.getPort() != -1 ? uri.getPort() : 21); if (StringUtils.hasText(uri.getUserInfo())) { if (uri.getUserInfo().contains(":")) ftpClient.login(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(":")), uri.getUserInfo().substring(uri.getUserInfo().indexOf(":") + 1)); else ftpClient.login(uri.getUserInfo(), ""); inputStream = ftpClient.retrieveFileStream(uri.getPath()); } } finally { ftpClient.disconnect(); } } else if (uri.getScheme().equalsIgnoreCase("file")) { File file = new File(uri); if (!file.isDirectory()) inputStream = new FileInputStream(uri.getPath()); else inputStream = RSSDirectoryBuilder.build(file); } else if (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https")) { try { HttpGet method = new HttpGet(uri.toString()); if (resultHeaders != null) for (Entry<String, String> resultHeader : resultHeaders.entrySet()) method.setHeader(new BasicHeader(resultHeader.getKey(), resultHeader.getValue())); if (userAgent != null) method.setHeader(CoreProtocolPNames.USER_AGENT, userAgent); SizeRestrictedHttpResponse response = httpClient.execute(method, new SizeRestrictedResponseHandler(maximumContentLength, uri)); try { if (response != null) { inputStream = new ByteArrayInputStream(response.getResponse()); contentType = response.getContentType() != null ? response.getContentType().getValue() : null; } else return null; } catch (RuntimeException e) { method.abort(); throw e; } } catch (IllegalArgumentException e) { logger.error("Invalid URL " + uri.toString() + " - not returning content", e); return null; } } else { logger.error("Unknown protocol " + uri.getScheme() + ". Skipping feed."); return null; } // Guess the character encoding using ROME's reader, then buffer it so we can discard the input stream (and close the connection) InputStream readerInputStream = new BufferedInputStream(inputStream); MediaType mediaType = autoDetectParser.getDetector().detect(readerInputStream, new Metadata()); try { Reader reader = null; if (mediaType.getType().equals("application")) { if (mediaType.getSubtype().equals("x-gzip")) { GZIPInputStream gzipInputStream = new GZIPInputStream(readerInputStream); if (encodingOverride != null) reader = readerToBuffer(new StringBuffer(), new InputStreamReader(gzipInputStream, encodingOverride), false); else reader = readerToBuffer(new StringBuffer(), contentType != null ? new XmlHtmlReader(gzipInputStream, contentType, true) : new XmlReader(gzipInputStream, true), false); gzipInputStream.close(); } else if (mediaType.getSubtype().equals("zip")) { ZipFile zipFile = null; // ZipInputStream can't do read-aheads, so we have to use a temporary on-disk file instead File temporaryFile = File.createTempFile("profiler-", ".zip"); try { FileOutputStream zipOutputStream = new FileOutputStream(temporaryFile); IOUtils.copy(readerInputStream, zipOutputStream); readerInputStream.close(); zipOutputStream.flush(); zipOutputStream.close(); // Create a new entry and process it zipFile = new ZipFile(temporaryFile); Enumeration<? extends ZipEntry> zipEnumeration = zipFile.entries(); ZipEntry zipEntry = zipEnumeration.nextElement(); if (zipEntry == null || zipEntry.isDirectory() || zipEnumeration.hasMoreElements()) { logger.error( "ZIP files are currently expected to contain one and only one entry, which is to be a file"); return null; } // We currently only perform prolog stripping for ZIP files InputStream zipInputStream = new BufferedInputStream(zipFile.getInputStream(zipEntry)); if (encodingOverride != null) reader = readerToBuffer(new StringBuffer(), new InputStreamReader( new BufferedInputStream(zipInputStream), encodingOverride), true); else result = readerToBuffer(new StringBuffer(), contentType != null ? new XmlHtmlReader(new BufferedInputStream(zipInputStream), contentType, true) : new XmlReader(new BufferedInputStream(zipInputStream), true), true); } catch (Exception e) { logger.error("An error occurred during ZIP file processing", e); return null; } finally { if (zipFile != null) zipFile.close(); if (!temporaryFile.delete()) logger.error("Unable to delete temporary file"); } } } if (result == null) { if (encodingOverride != null) result = readerToBuffer(new StringBuffer(), reader != null ? reader : new InputStreamReader(readerInputStream, encodingOverride), false); else result = readerToBuffer(new StringBuffer(), reader != null ? reader : contentType != null ? new XmlHtmlReader(readerInputStream, contentType, true) : new XmlReader(readerInputStream, true), false); } } catch (Exception e) { logger.error("An error occurred during stream processing", e); return null; } finally { inputStream.close(); } } catch (IOException e) { logger.error("Could not retrieve the given feed: " + e.getMessage(), e); return null; } return result; }
From source file:edu.stanford.epad.common.util.EPADFileUtils.java
/** * Unzip the specified file.// www . j a v a2s .c o m * * @param zipFilePath String path to zip file. * @throws IOException during zip or read process. */ public static void extractFolder(String zipFilePath) throws IOException { ZipFile zipFile = null; try { int BUFFER = 2048; File file = new File(zipFilePath); zipFile = new ZipFile(file); String newPath = zipFilePath.substring(0, zipFilePath.length() - 4); makeDirs(new File(newPath)); Enumeration<?> zipFileEntries = zipFile.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = new File(newPath, currentEntry); File destinationParent = destFile.getParentFile(); // create the parent directory structure if needed makeDirs(destinationParent); InputStream is = null; BufferedInputStream bis = null; FileOutputStream fos = null; BufferedOutputStream bos = null; try { if (destFile.exists() && destFile.isDirectory()) continue; if (!entry.isDirectory()) { int currentByte; byte data[] = new byte[BUFFER]; is = zipFile.getInputStream(entry); bis = new BufferedInputStream(is); fos = new FileOutputStream(destFile); bos = new BufferedOutputStream(fos, BUFFER); while ((currentByte = bis.read(data, 0, BUFFER)) != -1) { bos.write(data, 0, currentByte); } bos.flush(); } } finally { IOUtils.closeQuietly(bis); IOUtils.closeQuietly(is); IOUtils.closeQuietly(bos); IOUtils.closeQuietly(fos); } if (currentEntry.endsWith(".zip")) { extractFolder(destFile.getAbsolutePath()); } } } catch (Exception e) { log.warning("Failed to unzip: " + zipFilePath, e); throw new IllegalStateException(e); } finally { if (zipFile != null) zipFile.close(); } }
From source file:com.t3.persistence.PackedFile.java
private ZipFile getZipFile() throws IOException { if (zFile == null) zFile = new ZipFile(file); return zFile; }
From source file:com.yunmel.syncretic.utils.io.IOUtils.java
/** * ZIPZIPdescFileName// www .j a v a 2s . c om * * @param zipFileName ?ZIP * @param descFileName */ public static boolean unZipFiles(String zipFileName, String descFileName) { String descFileNames = descFileName; if (!descFileNames.endsWith(File.separator)) { descFileNames = descFileNames + File.separator; } try { // ?ZIPZipFile ZipFile zipFile = new ZipFile(zipFileName); ZipEntry entry = null; String entryName = null; String descFileDir = null; byte[] buf = new byte[4096]; int readByte = 0; // ?ZIPentry @SuppressWarnings("rawtypes") Enumeration enums = zipFile.entries(); // ??entry while (enums.hasMoreElements()) { entry = (ZipEntry) enums.nextElement(); // entry?? entryName = entry.getName(); descFileDir = descFileNames + entryName; if (entry.isDirectory()) { // entry new File(descFileDir).mkdirs(); continue; } else { // entry new File(descFileDir).getParentFile().mkdirs(); } File file = new File(descFileDir); // ? OutputStream os = new FileOutputStream(file); // ZipFileentry? InputStream is = zipFile.getInputStream(entry); while ((readByte = is.read(buf)) != -1) { os.write(buf, 0, readByte); } os.close(); is.close(); } zipFile.close(); log.debug("?!"); return true; } catch (Exception e) { log.debug("" + e.getMessage()); return false; } }
From source file:it.unimi.di.big.mg4j.document.SimpleCompressedDocumentCollection.java
private void initFiles(final String basename, final boolean rethrow) throws IOException { try {/*from w w w .j av a 2 s . c o m*/ documentsInputBitStream = documentsByteBufferInputStream != null ? new InputBitStream(documentsByteBufferInputStream) : new InputBitStream(basename + DOCUMENTS_EXTENSION); termsInputStream = new FastBufferedInputStream( termsByteBufferInputStream != null ? termsByteBufferInputStream : new FileInputStream(basename + TERMS_EXTENSION)); nonTermsInputStream = exact ? new FastBufferedInputStream( nonTermsByteBufferInputStream != null ? nonTermsByteBufferInputStream : new FileInputStream(basename + NONTERMS_EXTENSION)) : null; zipFile = hasNonText ? new ZipFile(basename + ZipDocumentCollection.ZIP_EXTENSION) : null; fileOpenOk = true; } catch (IOException e) { // We leave the possibility for a filename() to fix the problem and load the right files. if (rethrow) throw e; } }
From source file:com.cubeia.maven.plugin.firebase.FirebaseRunPlugin.java
private void unzipDirsToTmpDir(File zipFile, File tempDir) throws MojoExecutionException { try {/*w w w .ja v a 2 s . c o m*/ ZipFile zip = new ZipFile(zipFile); explode(zip, tempDir); } catch (IOException e) { throw new MojoExecutionException("Failed to unzip distribution", e); } }
From source file:com.samczsun.helios.Helios.java
private static boolean ensureJavaRtSet0(boolean forceCheck) { String javaRtLocation = Settings.RT_LOCATION.get().asString(); if (javaRtLocation.isEmpty()) { SWTUtil.showMessage("You need to set the location of Java's rt.jar", true); setLocationOf(Settings.RT_LOCATION); javaRtLocation = Settings.RT_LOCATION.get().asString(); }/*from www . j av a2 s . c o m*/ if (javaRtLocation.isEmpty()) { return false; } if (javaRtVerified == null || forceCheck) { ZipFile zipFile = null; try { File rtjar = new File(javaRtLocation); if (rtjar.exists()) { zipFile = new ZipFile(rtjar); ZipEntry object = zipFile.getEntry("java/lang/Object.class"); if (object != null) { javaRtVerified = true; } } } catch (Throwable t) { StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); SWTUtil.showMessage("The selected Java rt.jar is invalid." + Constants.NEWLINE + Constants.NEWLINE + sw.toString()); t.printStackTrace(); javaRtVerified = false; } finally { IOUtils.closeQuietly(zipFile); if (javaRtVerified == null) { javaRtVerified = false; } } } return javaRtVerified; }
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 w w .ja v a2 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:dalma.container.ClassLoaderImpl.java
/** * Returns an inputstream to a given resource in the given file which may * either be a directory or a zip file.//ww w.j ava2 s . c om * * @param file the file (directory or jar) in which to search for the * resource. Must not be <code>null</code>. * @param resourceName The name of the resource for which a stream is * required. Must not be <code>null</code>. * * @return a stream to the required resource or <code>null</code> if * the resource cannot be found in the given file. */ private InputStream getResourceStream(File file, String resourceName) { try { if (!file.exists()) { return null; } if (file.isDirectory()) { File resource = new File(file, resourceName); if (resource.exists()) { return new FileInputStream(resource); } } else { // is the zip file in the cache ZipFile zipFile = zipFiles.get(file); if (zipFile == null) { zipFile = new ZipFile(file); zipFiles.put(file, zipFile); } ZipEntry entry = zipFile.getEntry(resourceName); if (entry != null) { return zipFile.getInputStream(entry); } } } catch (Exception e) { logger.fine("Ignoring Exception " + e.getClass().getName() + ": " + e.getMessage() + " reading resource " + resourceName + " from " + file); } return null; }
From source file:nl.edia.sakai.tool.skinmanager.impl.SkinFileSystemServiceImpl.java
protected void validateSkinZip(File file) throws SkinException { ZipFile myZipFile = null;/*from w w w . j av a 2s . com*/ try { boolean isToolFound = false; boolean isPortalFound = false; boolean isImagesFound = false; myZipFile = new ZipFile(file); Enumeration<? extends ZipEntry> myEntries = myZipFile.entries(); while (myEntries.hasMoreElements()) { ZipEntry myZipEntry = (ZipEntry) myEntries.nextElement(); String myName = myZipEntry.getName(); if (myName.contains("..") || myName.startsWith("/")) { throw new SkinException("Illegal file name found in zip file '" + myName + "'"); } if (!myZipEntry.isDirectory()) { if (myName.equals("tool.css")) { isToolFound = true; } else if (myName.equals("portal.css")) { isPortalFound = true; } else if (PATTERN_IMAGES_DIR_CONTENT.matcher(myName).matches()) { isImagesFound = true; } } else { if (PATTERN_IMAGES_DIR_EMPTY.matcher(myName).matches()) { isImagesFound = true; } } } if (!isPortalFound) { throw getMissingResourceException("portal.css", false); } if (!isToolFound) { throw getMissingResourceException("tool.css", false); } if (!isImagesFound) { throw getMissingResourceException("images", true); } } catch (ZipException z) { throw new SkinException("Error reading zip file", z); } catch (IOException e) { throw new SkinException("IO Error reading zip file", e); } finally { if (myZipFile != null) { try { myZipFile.close(); } catch (IOException e) { // ignore } } } }