List of usage examples for java.util.zip ZipEntry getSize
public long getSize()
From source file:net.sf.zekr.engine.translation.TranslationData.java
private void loadAndVerify() throws TranslationException { ZipFile zf = null;/*from w w w.ja v a 2s .c o m*/ try { logger.info("Loading translation pack " + this + "..."); zf = new ZipFile(archiveFile); ZipEntry ze = zf.getEntry(file); if (ze == null) { logger.error("Load failed. No proper entry found in \"" + archiveFile.getName() + "\"."); return; } byte[] textBuf = new byte[(int) ze.getSize()]; if (!verify(zf.getInputStream(ze), textBuf)) logger.warn("Unauthorized translation data pack: " + this); // throw new TranslationException("INVALID_TRANSLATION_SIGNATURE", new String[] { name }); refineText(new String(textBuf, encoding)); logger.log("Translation pack " + this + " loaded successfully."); } catch (IOException e) { logger.error("Problem while loading translation pack " + this + "."); logger.log(e); throw new TranslationException(e); } finally { try { zf.close(); } catch (Exception e) { // do nothing } } }
From source file:org.stanwood.media.util.FileHelper.java
/** * Used to unzip a file to a directory//from w ww . j av a 2 s . c o m * @param is The input stream containing the file * @param destDir The directory to unzip to * @throws IOException Thrown if their are any problems */ public static void unzip(InputStream is, File destDir) throws IOException { ZipInputStream zis = null; try { zis = new ZipInputStream(is); ZipEntry entry = null; while ((entry = zis.getNextEntry()) != null) { File file = new File(destDir, entry.getName()); if (entry.isDirectory()) { if (!file.mkdir() && file.exists()) { throw new IOException("Unable to create directory: " + file); //$NON-NLS-1$ } } else { BufferedOutputStream out = null; try { int count; byte data[] = new byte[1000]; out = new BufferedOutputStream(new FileOutputStream(new File(destDir, entry.getName())), 1000); if (log.isDebugEnabled()) { log.debug("Unzipping " + entry.getName() + " with size " + entry.getSize()); //$NON-NLS-1$ //$NON-NLS-2$ } while ((count = zis.read(data, 0, 1000)) != -1) { out.write(data, 0, count); } out.flush(); } finally { if (out != null) { out.close(); } } } } } finally { if (zis != null) { zis.close(); } } }
From source file:com.haulmont.cuba.web.controllers.StaticContentController.java
protected LookupResult lookupNoCache(HttpServletRequest req) { final String path = getPath(req); if (isForbidden(path)) return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); ServletContext context = req.getSession().getServletContext(); final URL url; try {//from ww w. java2 s.com url = context.getResource(path); } catch (MalformedURLException e) { return new Error(HttpServletResponse.SC_BAD_REQUEST, "Malformed path"); } if (url == null) return new Error(HttpServletResponse.SC_NOT_FOUND, "Not found"); final String mimeType = getMimeType(path); final String realpath = context.getRealPath(path); if (realpath != null) { // Try as an ordinary file File f = new File(realpath); if (!f.isFile()) return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); else { return createLookupResult(req, f.lastModified(), mimeType, (int) f.length(), acceptsDeflate(req), url); } } else { try { // Try as a JAR Entry final ZipEntry ze = ((JarURLConnection) url.openConnection()).getJarEntry(); if (ze != null) { if (ze.isDirectory()) return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); else return createLookupResult(req, ze.getTime(), mimeType, (int) ze.getSize(), acceptsDeflate(req), url); } else // Unexpected? return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), url); } catch (ClassCastException e) { // Unknown resource type return createLookupResult(req, -1, mimeType, -1, acceptsDeflate(req), url); } catch (IOException e) { return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error"); } } }
From source file:com.xpn.xwiki.plugin.zipexplorer.ZipExplorerPlugin.java
/** * For ZIP URLs of the format <code>http://[...]/zipfile.zip/SomeDirectory/SomeFile.txt</code> return a new * attachment containing the file pointed to inside the ZIP. If the original attachment does not point to a ZIP file * or if it doesn't specify a location inside the ZIP then do nothing and return the original attachment. * /*from www. j a va2 s. c om*/ * @param attachment the original attachment * @param context the XWiki context, used to get the request URL corresponding to the download request * @return a new attachment pointing to the file pointed to by the URL inside the ZIP or the original attachment if * the requested URL doesn't specify a file inside a ZIP * @see com.xpn.xwiki.plugin.XWikiDefaultPlugin#downloadAttachment */ @Override public XWikiAttachment downloadAttachment(XWikiAttachment attachment, XWikiContext context) { String url = context.getRequest().getRequestURI(); // Verify if we should return the original attachment. This will happen if the requested // download URL doesn't point to a zip or if the URL doesn't point to a file inside the ZIP. if (!isValidZipURL(url, context.getAction().trim())) { return attachment; } String filename = getFileLocationFromZipURL(url, context.getAction().trim()); // Create the new attachment pointing to the file inside the ZIP XWikiAttachment newAttachment = new XWikiAttachment(); newAttachment.setDoc(attachment.getDoc()); newAttachment.setAuthor(attachment.getAuthor()); newAttachment.setDate(attachment.getDate()); InputStream stream = null; try { stream = new BufferedInputStream(attachment.getContentInputStream(context)); if (!isZipFile(stream)) { return attachment; } ZipInputStream zis = new ZipInputStream(stream); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String entryName = entry.getName(); if (entryName.equals(filename)) { newAttachment.setFilename(entryName); if (entry.getSize() == -1) { // Note: We're copying the content of the file in the ZIP in memory. This is // potentially going to cause an error if the file's size is greater than the // maximum size of a byte[] array in Java or if there's not enough memomry. byte[] data = IOUtils.toByteArray(zis); newAttachment.setContent(data); } else { newAttachment.setContent(zis, (int) entry.getSize()); } break; } } } catch (XWikiException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(stream); } return newAttachment; }
From source file:org.pentaho.reporting.libraries.repository.zipreader.ZipReadContentLocation.java
public ZipReadContentLocation(ZipReadRepository repository, ZipReadContentLocation parent, ZipEntry zipEntry) { if (repository == null) { throw new NullPointerException(); }// w w w . jav a 2 s .c o m if (parent == null) { throw new NullPointerException(); } if (zipEntry == null) { throw new NullPointerException(); } this.repository = repository; this.parent = parent; this.comment = zipEntry.getComment(); this.size = zipEntry.getSize(); this.time = zipEntry.getTime(); this.entries = new HashMap(); this.entryName = IOUtils.getInstance().getFileName(zipEntry.getName()); this.name = RepositoryUtilities.buildName(this, "/") + '/'; }
From source file:org.pentaho.platform.web.servlet.UploadFileUtils.java
/** * Gets the uncompressed file size of a .zip file. * // ww w .j a v a 2 s.c o m * @param theFile * @return long uncompressed file size. * @throws IOException * mbatchelor */ private long getUncompressedZipFileSize(File theFile) throws IOException { long rtn = 0; ZipFile zf = new ZipFile(theFile); try { Enumeration<? extends ZipEntry> zfEntries = zf.entries(); ZipEntry ze = null; while (zfEntries.hasMoreElements()) { ze = zfEntries.nextElement(); rtn += ze.getSize(); } } finally { try { zf.close(); } catch (Exception ignored) { //ignored } } return rtn; }
From source file:org.atombeat.xquery.functions.util.GetZipEntries.java
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { try {//from w ww.j a va 2 s. c o m String path = args[0].getStringValue(); ZipFile zf = new ZipFile(path); log.debug(zf.getName()); log.debug(zf.size()); log.debug(zf.hashCode()); ZipEntry e; Enumeration<? extends ZipEntry> entries = zf.entries(); ValueSequence s = new ValueSequence(); for (int i = 0; entries.hasMoreElements(); i++) { log.debug(i); e = entries.nextElement(); log.debug(e.getName()); log.debug(e.getComment()); log.debug(e.isDirectory()); log.debug(e.getCompressedSize()); log.debug(e.getCrc()); log.debug(e.getMethod()); log.debug(e.getSize()); log.debug(e.getTime()); if (!e.isDirectory()) s.add(new StringValue(e.getName())); } return s; } catch (Exception e) { throw new XPathException("error processing zip file: " + e.getLocalizedMessage(), e); } }
From source file:org.dspace.webmvc.controller.ResourceController.java
protected LookupResult lookupNoCache(HttpServletRequest req) { final String path = getPath(req); if (isForbidden(path)) { return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); }/*from ww w . j a va2 s . c o m*/ final URL url; try { url = req.getSession().getServletContext().getResource(path); } catch (MalformedURLException e) { return new Error(HttpServletResponse.SC_BAD_REQUEST, "Malformed path"); } final String mimeType = getMimeType(req, path); final String realpath = req.getSession().getServletContext().getRealPath(path); if (url != null && realpath != null) { // Try as an ordinary file File f = new File(realpath); if (!f.isFile()) { return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); } else { return new StaticFile(f.lastModified(), mimeType, (int) f.length(), acceptsDeflate(req), url); } } else { ClassPathResource cpr = new ClassPathResource(path); if (cpr.exists()) { URL cprURL = null; try { cprURL = cpr.getURL(); // Try as a JAR Entry final ZipEntry ze = ((JarURLConnection) cprURL.openConnection()).getJarEntry(); if (ze != null) { if (ze.isDirectory()) { return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); } else { return new StaticFile(ze.getTime(), mimeType, (int) ze.getSize(), acceptsDeflate(req), cprURL); } } else { // Unexpected? return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), cprURL); } } catch (ClassCastException e) { // Unknown resource type if (url != null) { return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), cprURL); } else { return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error"); } } catch (IOException e) { return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error"); } } else { return new Error(HttpServletResponse.SC_NOT_FOUND, "Not found"); } } }
From source file:nova.core.render.model.TechneModelProvider.java
@Override public void load(InputStream stream) { try {//w ww . j ava 2 s.c om Map<String, byte[]> zipContents = new HashMap<>(); ZipInputStream zipInput = new ZipInputStream(stream); ZipEntry entry; while ((entry = zipInput.getNextEntry()) != null) { byte[] data = new byte[(int) entry.getSize()]; // For some reason, using read(byte[]) makes reading stall upon reaching a 0x1E byte int i = 0; while (zipInput.available() > 0 && i < data.length) { data[i++] = (byte) zipInput.read(); } zipContents.put(entry.getName(), data); } byte[] modelXml = zipContents.get("model.xml"); if (modelXml == null) { throw new RenderException("Model " + name + " contains no model.xml file"); } DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(new ByteArrayInputStream(modelXml)); NodeList nodeListTechne = document.getElementsByTagName("Techne"); if (nodeListTechne.getLength() < 1) { throw new RenderException("Model " + name + " contains no Techne tag"); } NodeList nodeListModel = document.getElementsByTagName("Model"); if (nodeListModel.getLength() < 1) { throw new RenderException("Model " + name + " contains no Model tag"); } NamedNodeMap modelAttributes = nodeListModel.item(0).getAttributes(); if (modelAttributes == null) { throw new RenderException("Model " + name + " contains a Model tag with no attributes"); } NodeList textureSize = document.getElementsByTagName("TextureSize"); if (textureSize.getLength() == 0) throw new RenderException("Model has no texture size"); String[] textureDimensions = textureSize.item(0).getTextContent().split(","); double textureWidth = Integer.parseInt(textureDimensions[0]); double textureHeight = Integer.parseInt(textureDimensions[1]); NodeList shapes = document.getElementsByTagName("Shape"); for (int i = 0; i < shapes.getLength(); i++) { Node shape = shapes.item(i); NamedNodeMap shapeAttributes = shape.getAttributes(); if (shapeAttributes == null) { throw new RenderException("Shape #" + (i + 1) + " in " + name + " has no attributes"); } Node name = shapeAttributes.getNamedItem("name"); String shapeName = null; if (name != null) { shapeName = name.getNodeValue(); } if (shapeName == null) { shapeName = "Shape #" + (i + 1); } String shapeType = null; Node type = shapeAttributes.getNamedItem("type"); if (type != null) { shapeType = type.getNodeValue(); } if (shapeType != null && !cubeIDs.contains(shapeType)) { System.out.println( "Model shape [" + shapeName + "] in " + this.name + " is not a cube, ignoring"); continue; } boolean mirrored = false; String[] offset = new String[3]; String[] position = new String[3]; String[] rotation = new String[3]; String[] size = new String[3]; String[] textureOffset = new String[2]; NodeList shapeChildren = shape.getChildNodes(); for (int j = 0; j < shapeChildren.getLength(); j++) { Node shapeChild = shapeChildren.item(j); String shapeChildName = shapeChild.getNodeName(); String shapeChildValue = shapeChild.getTextContent(); if (shapeChildValue != null) { shapeChildValue = shapeChildValue.trim(); switch (shapeChildName) { case "IsMirrored": mirrored = !shapeChildValue.equals("False"); break; case "Offset": offset = shapeChildValue.split(","); break; case "Position": position = shapeChildValue.split(","); break; case "Rotation": rotation = shapeChildValue.split(","); break; case "Size": size = shapeChildValue.split(","); break; case "TextureOffset": textureOffset = shapeChildValue.split(","); break; } } } /* Generate new models Models in Techne are based on cubes. Each cube is, by default, skewed to the side. They are not centered. Everything is scaled by a factor of 16. The y coordinate is inversed, y = 24 is the surface The z coordinate is inverted, too. */ double positionX = Double.parseDouble(position[0]) / 16d; double positionY = (16 - Double.parseDouble(position[1])) / 16d; double positionZ = -Double.parseDouble(position[2]) / 16d; double sizeX = Double.parseDouble(size[0]) / 16d; double sizeY = Double.parseDouble(size[1]) / 16d; double sizeZ = Double.parseDouble(size[2]) / 16d; double offsetX = Double.parseDouble(offset[0]) / 16d; double offsetY = -Double.parseDouble(offset[1]) / 16d; double offsetZ = -Double.parseDouble(offset[2]) / 16d; double angleX = -Math.toRadians(Double.parseDouble(rotation[0])); double angleY = Math.toRadians(Double.parseDouble(rotation[1])); double angleZ = Math.toRadians(Double.parseDouble(rotation[2])); double textureOffsetU = Double.parseDouble(textureOffset[0]); double textureOffsetV = Double.parseDouble(textureOffset[1]); CubeTextureCoordinates textureCoordinates = new TechneCubeTextureCoordinates(textureWidth, textureHeight, textureOffsetU, textureOffsetV, sizeX, sizeY, sizeZ); final String modelName = shapeName; MeshModel modelPart = new MeshModel(modelName); BlockRenderPipeline.drawCube(modelPart, offsetX, offsetY - sizeY, offsetZ - sizeZ, offsetX + sizeX, offsetY, offsetZ, textureCoordinates); MatrixStack ms = new MatrixStack(); ms.translate(positionX, positionY, positionZ); ms.rotate(Vector3D.PLUS_J, angleY); ms.rotate(Vector3D.PLUS_I, angleX); ms.rotate(Vector3D.PLUS_K, angleZ); modelPart.matrix = ms; modelPart.textureOffset = new Vector2D(Integer.parseInt(textureOffset[0]), Integer.parseInt(textureOffset[1])); if (model.children.stream().anyMatch(m -> m.name.equals(modelName))) { throw new RenderException( "Model contained duplicate part name: '" + shapeName + "' node #" + i); } model.children.add(modelPart); } } catch (ZipException e) { throw new RenderException("Model " + name + " is not a valid zip file"); } catch (IOException e) { throw new RenderException("Model " + name + " could not be read", e); } catch (SAXException e) { throw new RenderException("Model " + name + " contains invalid XML", e); } catch (Exception e) { e.printStackTrace(); } }
From source file:biz.c24.io.spring.batch.reader.source.ZipFileSource.java
public void initialise(StepExecution stepExecution) { try {/*ww w . j a v a 2s . c o m*/ // Get an File and a name for where we're reading from // Use the Resource if supplied File source = null; if (resource != null) { name = resource.getDescription(); source = resource.getFile(); } else { // If no resource supplied, fallback to a Job parameter called input.file name = stepExecution.getJobParameters().getString("input.file"); // Remove any leading file:// if it exists if (name.startsWith("file://")) { name = name.substring("file://".length()); } source = new File(name); } zipFile = new ZipFile(source); zipEntries = zipFile.entries(); ZipEntry entry = getNextZipEntry(); if (entry != null) { // Prime the reader reader = getReader(entry); } // If we have a large number of ZipEntries and the first one looks relatively small, advise // callers to use a thread per reader if (entry != null && zipFile.size() > 20 && (entry.getSize() == -1 || entry.getSize() < 100000)) { useMultipleThreadsPerReader = false; } } catch (IOException e) { throw new RuntimeException(e); } }