List of usage examples for java.util.zip ZipEntry getSize
public long getSize()
From source file:io.personium.core.eventlog.ArchiveLogCollection.java
/** * ????./*from www .j a v a2 s.c o m*/ */ public void createFileInformation() { File archiveDir = new File(this.directoryPath); // ??????????????????? if (!archiveDir.exists()) { return; } File[] fileList = archiveDir.listFiles(); for (File file : fileList) { // ?? long fileUpdated = file.lastModified(); // ?????? if (this.updated < fileUpdated) { this.updated = fileUpdated; } BasicFileAttributes attr = null; ZipFile zipFile = null; long fileCreated = 0L; long size = 0L; try { // ??? attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class); fileCreated = attr.creationTime().toMillis(); // ????API??????????????????? zipFile = new ZipFile(file); Enumeration<? extends ZipEntry> emu = zipFile.entries(); while (emu.hasMoreElements()) { ZipEntry entry = (ZipEntry) emu.nextElement(); if (null == entry) { log.info("Zip file entry is null."); throw PersoniumCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN; } size += entry.getSize(); } } catch (ZipException e) { log.info("ZipException", e); throw PersoniumCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN; } catch (IOException e) { log.info("IOException", e); throw PersoniumCoreException.Event.ARCHIVE_FILE_CANNOT_OPEN; } finally { IOUtils.closeQuietly(zipFile); } // ??????API???????????????(.zip)?????? String fileName = file.getName(); String fileNameWithoutZip = fileName.substring(0, fileName.length() - ".zip".length()); String fileUrl = this.url + "/" + fileNameWithoutZip; ArchiveLogFile archiveFile = new ArchiveLogFile(fileCreated, fileUpdated, size, fileUrl); this.archivefileList.add(archiveFile); log.info(String.format("filename:%s created:%d updated:%d size:%d", file.getName(), fileCreated, fileUpdated, size)); } }
From source file:com.marklogic.contentpump.CompressedDocumentReader.java
@Override public boolean nextKeyValue() throws IOException, InterruptedException { if (zipIn == null) { hasNext = false;/*from ww w .j av a 2 s . c o m*/ return false; } if (codec == CompressionCodec.ZIP) { ZipEntry zipEntry; ZipInputStream zis = (ZipInputStream) zipIn; while (true) { try { zipEntry = zis.getNextEntry(); if (zipEntry == null) { break; } if (zipEntry.getSize() == 0) { continue; } subId = zipEntry.getName(); String uri = makeURIForZipEntry(file, subId); if (setKey(uri, 0, 0, true)) { return true; } setValue(zipEntry.getSize()); return true; } catch (IllegalArgumentException e) { LOG.warn("Skipped a zip entry in : " + file.toUri() + ", reason: " + e.getMessage()); } } } else if (codec == CompressionCodec.GZIP) { setValue(0); zipIn.close(); zipIn = null; hasNext = false; return true; } else { return false; } if (iterator != null && iterator.hasNext()) { close(); initStream(iterator.next()); return nextKeyValue(); } else { hasNext = false; return false; } }
From source file:org.gradle.api.plugins.buildcomparison.outcome.internal.archive.entry.FileToArchiveEntrySetTransformer.java
private ImmutableSet<ArchiveEntry> walk(InputStream archiveInputStream, ImmutableSet.Builder<ArchiveEntry> allEntries, ImmutableList<String> parentPaths) { ImmutableSet.Builder<ArchiveEntry> entries = ImmutableSet.builder(); ZipInputStream zipStream = new ZipInputStream(archiveInputStream); try {/*from ww w . j a va2 s . c o m*/ ZipEntry entry = zipStream.getNextEntry(); while (entry != null) { ArchiveEntry.Builder builder = new ArchiveEntry.Builder(); builder.setParentPaths(parentPaths); builder.setPath(entry.getName()); builder.setCrc(entry.getCrc()); builder.setDirectory(entry.isDirectory()); builder.setSize(entry.getSize()); if (!builder.isDirectory() && (zipStream.available() == 1)) { boolean zipEntry; final BufferedInputStream bis = new BufferedInputStream(zipStream) { @Override public void close() throws IOException { } }; bis.mark(Integer.MAX_VALUE); zipEntry = new ZipInputStream(bis).getNextEntry() != null; bis.reset(); if (zipEntry) { ImmutableList<String> nextParentPaths = ImmutableList.<String>builder().addAll(parentPaths) .add(entry.getName()).build(); ImmutableSet<ArchiveEntry> subEntries = walk(bis, allEntries, nextParentPaths); builder.setSubEntries(subEntries); } } ArchiveEntry archiveEntry = builder.build(); entries.add(archiveEntry); allEntries.add(archiveEntry); zipStream.closeEntry(); entry = zipStream.getNextEntry(); } } catch (IOException e) { throw new UncheckedIOException(e); } finally { IOUtils.closeQuietly(zipStream); } return entries.build(); }
From source file:edu.umd.cs.marmoset.utilities.ZipExtractor.java
/** * Extract the zip file.// w ww. ja va 2s. 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:org.openmrs.module.openconceptlab.client.OclClient.java
@SuppressWarnings("resource") public OclResponse unzipResponse(InputStream response, Date date) throws IOException { ZipInputStream zip = new ZipInputStream(response); boolean foundEntry = false; try {/*w w w.j ava2 s . c om*/ ZipEntry entry = zip.getNextEntry(); while (entry != null) { if (entry.getName().equals("export.json")) { foundEntry = true; return new OclResponse(zip, entry.getSize(), date); } entry = zip.getNextEntry(); } zip.close(); } finally { if (!foundEntry) { IOUtils.closeQuietly(zip); } } throw new IOException("Unsupported format of response. Expected zip with export.json."); }
From source file:pcgen.system.PluginClassLoader.java
private void loadClasses(final File pluginJar) throws IOException { try (JarClassLoader loader = new JarClassLoader(pluginJar.toURI().toURL()); ZipFile file = new ZipFile(pluginJar)) { final Collection<String> classList = new LinkedList<>(); Enumeration<? extends ZipEntry> entries = file.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); if (!name.endsWith(".class")) { continue; }// www . ja v a2 s. c o m name = StringUtils.removeEnd(name, ".class").replace('/', '.'); int size = (int) entry.getSize(); byte[] buffer = new byte[size]; InputStream in = file.getInputStream(entry); int rb = 0; int chunk; while ((size - rb) > 0) { chunk = in.read(buffer, rb, size - rb); if (chunk == -1) { break; } rb += chunk; } in.close(); loader.storeClassDef(name, buffer); classList.add(name); } file.close(); /* * Loading files and loading classes can both be lengthy processes. This splits the tasks * so that class loading occurs in another thread thus allowing both processes to * operate at the same time. */ dispatcher.execute(new Runnable() { @Override public void run() { boolean pluginFound = false; for (final String string : classList) { try { pluginFound |= processClass(Class.forName(string, true, loader)); } catch (ClassNotFoundException | NoClassDefFoundError ex) { Logging.errorPrint("Error occurred while loading plugin: " + pluginJar.getName(), ex); } } if (!pluginFound) { Logging.log(Logging.WARNING, "Plugin not found in " + pluginJar.getName()); } progress++; setProgress(progress); } }); } }
From source file:org.sakaiproject.portal.charon.handlers.StaticHandler.java
/** * serve a registered static file/* w w w. j av a 2 s . c o m*/ * * @param req * @param res * @param parts * @throws IOException */ public void doStatic(HttpServletRequest req, HttpServletResponse res, String[] parts) throws IOException { try { StaticCache[] staticCache = staticCacheHolder.get(); if (staticCache == null) { staticCache = new StaticCache[100]; staticCacheHolder.set(staticCache); } String path = URLUtils.getSafePathInfo(req); if (path.indexOf("..") >= 0) { res.sendError(404); return; } InputStream inputStream; String filename = path.substring(path.lastIndexOf("/")); long lastModified = -1; long length = -1; String realPath = servletContext.getRealPath(path); if (realPath == null) { // We not uncompressing the webapps. URL url = servletContext.getResource(path); inputStream = url.openStream(); if (url != null) { try { ZipEntry zipEntry = ((JarURLConnection) url.openConnection()).getJarEntry(); lastModified = zipEntry.getLastModifiedTime().toMillis(); length = zipEntry.getSize(); } catch (ClassCastException cce) { // Can't get extra data, but should all work. log.debug("We don't seem to be a JAR either.", cce); } } else { res.sendError(404); return; } } else { File f = new File(realPath); inputStream = new FileInputStream(f); lastModified = f.lastModified(); length = f.length(); } if (length >= 0 && length < MAX_SIZE_KB * 1024) { for (int i = 0; i < staticCache.length; i++) { StaticCache sc = staticCache[i]; if (sc != null && path.equals(sc.path)) { // If we don't have a good last modified time it's cached forever if (lastModified > sc.lastModified) { sc.buffer = loadFileBuffer(inputStream, (int) length); sc.path = path; sc.lastModified = lastModified; sc.contenttype = getContentType(filename); sc.added = System.currentTimeMillis(); } // send the output sendContent(res, sc); return; } } // not found in cache, find the oldest or null and evict // this is thread Safe, since the cache is per thread. StaticCache sc = null; for (int i = 1; i < staticCache.length; i++) { StaticCache current = staticCache[i]; if (sc == null) { sc = current; } if (current == null) { sc = new StaticCache(); staticCache[i] = sc; break; } if (sc.added < current.added) { sc = current; } } sc.buffer = loadFileBuffer(inputStream, (int) length); sc.path = path; sc.lastModified = lastModified; sc.contenttype = getContentType(filename); sc.added = System.currentTimeMillis(); sendContent(res, sc); return; } else { res.setContentType(getContentType(filename)); res.addDateHeader("Last-Modified", lastModified); res.setContentLength((int) length); sendContent(res, inputStream); return; } } catch (IOException ex) { log.info("Failed to send portal content"); if (log.isDebugEnabled()) { log.debug("Full detail of exception is:", ex); } res.sendError(404, URLUtils.getSafePathInfo(req)); } }
From source file:org.pentaho.reporting.engine.classic.demo.ancient.demo.swingicons.SwingIconsDemoTableModel.java
/** * Reads the icon data from the jar file. * * @param in the input stream.//from w w w. j a v a 2 s. co m */ private boolean readData(final InputStream in) { try { final ZipInputStream iconJar = new ZipInputStream(in); ZipEntry ze = iconJar.getNextEntry(); while (ze != null) { final String fullName = ze.getName(); if (fullName.endsWith(".gif")) { final String category = getCategory(fullName); final String name = getName(fullName); final Image image = getImage(iconJar); final Long bytes = new Long(ze.getSize()); //logger.debug ("Add Icon: " + name); addIconEntry(name, category, image, bytes); } iconJar.closeEntry(); ze = iconJar.getNextEntry(); } } catch (IOException e) { logger.warn("Unable to load the Icons", e); return false; } return true; }
From source file:org.mycore.iview2.frontend.MCRTileCombineServlet.java
private void sendThumbnail(final File iviewFile, final HttpServletResponse response) throws IOException { try (ZipFile zipFile = new ZipFile(iviewFile);) { final ZipEntry ze = zipFile.getEntry("0/0/0.jpg"); if (ze != null) { response.setHeader("Cache-Control", "max-age=" + MCRTileServlet.MAX_AGE); response.setContentType("image/jpeg"); response.setContentLength((int) ze.getSize()); try (ServletOutputStream out = response.getOutputStream(); InputStream zin = zipFile.getInputStream(ze);) { IOUtils.copy(zin, out);/*from w ww. j a v a2 s.c o m*/ } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } }
From source file:net.sf.zekr.engine.translation.TranslationData.java
/** * Verify the zip archive and close the zip file handle finally. * /* ww w . j av a 2s. c om*/ * @return <code>true</code> if translation verified, <code>false</code> otherwise. * @throws IOException */ public boolean verify() throws IOException { ZipFile zf = new ZipFile(archiveFile); ZipEntry ze = zf.getEntry(file); if (ze == null) { logger.error("Load failed. No proper entry found in \"" + archiveFile.getName() + "\"."); return false; } byte[] textBuf = new byte[(int) ze.getSize()]; boolean result; result = verify(zf.getInputStream(ze), textBuf); zf.close(); return result; }