List of usage examples for java.util.zip ZipInputStream closeEntry
public void closeEntry() throws IOException
From source file:com.ibm.jaggr.core.util.ZipUtil.java
/** * Extracts the specified zip file to the specified location. If {@code selector} is specified, * then only the entry specified by {@code selector} (if {@code selector} is a filename) or the * contents of the directory specified by {@code selector} (if {@code selector} is a directory * name) will be extracted. If {@code selector} specifies a directory, then the contents of the * directory in the zip file will be rooted at {@code destDir} when extracted. * * @param zipFile/*from w ww . j av a 2s . co m*/ * the {@link File} object for the file to unzip * @param destDir * the {@link File} object for the target directory * @param selector * The name of a file or directory to extract * @throws IOException */ public static void unzip(File zipFile, File destDir, String selector) throws IOException { final String sourceMethod = "unzip"; //$NON-NLS-1$ final boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(sourceClass, sourceMethod, new Object[] { zipFile, destDir }); } boolean selectorIsFolder = selector != null && selector.charAt(selector.length() - 1) == '/'; ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile)); try { ZipEntry entry = zipIn.getNextEntry(); // iterates over entries in the zip file while (entry != null) { String entryName = entry.getName(); if (selector == null || !selectorIsFolder && entryName.equals(selector) || selectorIsFolder && entryName.startsWith(selector) && entryName.length() != selector.length()) { if (selector != null) { if (selectorIsFolder) { // selector is a directory. Strip selected path entryName = entryName.substring(selector.length()); } else { // selector is a filename. Extract the filename portion of the path int idx = entryName.lastIndexOf("/"); //$NON-NLS-1$ if (idx != -1) { entryName = entryName.substring(idx + 1); } } } File file = new File(destDir, entryName.replace("/", File.separator)); //$NON-NLS-1$ if (!entry.isDirectory()) { // if the entry is a file, extract it extractFile(entry, zipIn, file); } else { // if the entry is a directory, make the directory extractDirectory(entry, file); } zipIn.closeEntry(); } entry = zipIn.getNextEntry(); } } finally { zipIn.close(); } if (isTraceLogging) { log.exiting(sourceClass, sourceMethod); } }
From source file:eu.esdihumboldt.hale.io.appschema.writer.AppSchemaFileWriterTest.java
private void checkArchive(File archive) throws IOException { final File tempFile = File.createTempFile(Long.toString(System.currentTimeMillis()), ".xml"); ZipInputStream zis = null; Document doc = null;//from w w w. j av a 2s . c o m try { zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(archive))); ZipEntry lcvWsDir = zis.getNextEntry(); checkDirEntry(lcvWsDir, "lcv/"); zis.closeEntry(); ZipEntry lcvWsFile = zis.getNextEntry(); checkFileEntry(lcvWsFile, "lcv/" + AppSchemaIO.WORKSPACE_FILE); doc = readDocument(zis); checkWorkspaceDocument(doc, "lcv_workspace", "lcv"); zis.closeEntry(); ZipEntry lcvNsFile = zis.getNextEntry(); checkFileEntry(lcvNsFile, "lcv/" + AppSchemaIO.NAMESPACE_FILE); doc = readDocument(zis); checkNamespaceDocument(doc, "lcv_namespace", "lcv", "http://inspire.ec.europa.eu/schemas/lcv/3.0"); zis.closeEntry(); ZipEntry lcvDataStoreDir = zis.getNextEntry(); checkDirEntry(lcvDataStoreDir, "lcv/LandCoverVector/"); zis.closeEntry(); ZipEntry lcvDataStoreFile = zis.getNextEntry(); checkFileEntry(lcvDataStoreFile, "lcv/LandCoverVector/" + AppSchemaIO.DATASTORE_FILE); doc = readDocument(zis); assertNotNull(doc); assertEquals("LandCoverVector_datastore", getFirstElementByTagName(doc.getDocumentElement(), "id").getTextContent()); assertEquals("LandCoverVector", getFirstElementByTagName(doc.getDocumentElement(), "name").getTextContent()); Element wsEl = getFirstElementByTagName(doc.getDocumentElement(), "workspace"); assertNotNull(wsEl); assertEquals("lcv_workspace", getFirstElementByTagName(wsEl, "id").getTextContent()); NodeList paramEntries = doc.getDocumentElement().getElementsByTagName("entry"); assertNotNull(paramEntries); assertEquals(3, paramEntries.getLength()); for (int i = 0; i < paramEntries.getLength(); i++) { Node param = paramEntries.item(i); Node key = param.getAttributes().getNamedItem("key"); if ("dbtype".equals(key.getTextContent())) { assertEquals("app-schema", param.getTextContent()); } else if ("namespace".equals(key.getTextContent())) { assertEquals("http://inspire.ec.europa.eu/schemas/lcv/3.0", param.getTextContent()); } else if ("url".equals(key.getTextContent())) { assertEquals("file:./workspaces/lcv/LandCoverVector/LandCoverVector.xml", param.getTextContent()); } else { fail("Unknown connection parameter found: " + key.getTextContent()); } } zis.closeEntry(); ZipEntry mappingFile = zis.getNextEntry(); checkFileEntry(mappingFile, "lcv/LandCoverVector/LandCoverVector.xml"); ByteStreams.copy(zis, new FileOutputStream(tempFile)); assertTrue(isMappingValid(tempFile)); zis.closeEntry(); ZipEntry unitFtDir = zis.getNextEntry(); checkDirEntry(unitFtDir, "lcv/LandCoverVector/LandCoverUnit/"); zis.closeEntry(); ZipEntry unitFtFile = zis.getNextEntry(); checkFileEntry(unitFtFile, "lcv/LandCoverVector/LandCoverUnit/" + AppSchemaIO.FEATURETYPE_FILE); doc = readDocument(zis); checkFeatureTypeDocument(doc, "LandCoverUnit"); zis.closeEntry(); ZipEntry unitLayerFile = zis.getNextEntry(); checkFileEntry(unitLayerFile, "lcv/LandCoverVector/LandCoverUnit/" + AppSchemaIO.LAYER_FILE); doc = readDocument(zis); checkLayerDocument(doc, "LandCoverUnit"); zis.closeEntry(); ZipEntry datasetFtDir = zis.getNextEntry(); checkDirEntry(datasetFtDir, "lcv/LandCoverVector/LandCoverDataset/"); zis.closeEntry(); ZipEntry datasetFtFile = zis.getNextEntry(); checkFileEntry(datasetFtFile, "lcv/LandCoverVector/LandCoverDataset/" + AppSchemaIO.FEATURETYPE_FILE); doc = readDocument(zis); checkFeatureTypeDocument(doc, "LandCoverDataset"); zis.closeEntry(); ZipEntry datasetLayerFile = zis.getNextEntry(); checkFileEntry(datasetLayerFile, "lcv/LandCoverVector/LandCoverDataset/" + AppSchemaIO.LAYER_FILE); doc = readDocument(zis); checkLayerDocument(doc, "LandCoverDataset"); zis.closeEntry(); ZipEntry baseWsDir = zis.getNextEntry(); checkDirEntry(baseWsDir, "base/"); zis.closeEntry(); ZipEntry baseWsFile = zis.getNextEntry(); checkFileEntry(baseWsFile, "base/" + AppSchemaIO.WORKSPACE_FILE); doc = readDocument(zis); checkWorkspaceDocument(doc, "base_workspace", "base"); zis.closeEntry(); ZipEntry baseNsFile = zis.getNextEntry(); checkFileEntry(baseNsFile, "base/" + AppSchemaIO.NAMESPACE_FILE); doc = readDocument(zis); checkNamespaceDocument(doc, "base_namespace", "base", "http://inspire.ec.europa.eu/schemas/base/3.3"); zis.closeEntry(); ZipEntry gmlWsDir = zis.getNextEntry(); checkDirEntry(gmlWsDir, "gml/"); zis.closeEntry(); ZipEntry gmlWsFile = zis.getNextEntry(); checkFileEntry(gmlWsFile, "gml/" + AppSchemaIO.WORKSPACE_FILE); doc = readDocument(zis); checkWorkspaceDocument(doc, "gml_workspace", "gml"); zis.closeEntry(); ZipEntry gmlNsFile = zis.getNextEntry(); checkFileEntry(gmlNsFile, "gml/" + AppSchemaIO.NAMESPACE_FILE); doc = readDocument(zis); checkNamespaceDocument(doc, "gml_namespace", "gml", "http://www.opengis.net/gml/3.2"); zis.closeEntry(); ZipEntry xlinkWsDir = zis.getNextEntry(); checkDirEntry(xlinkWsDir, "xlink/"); zis.closeEntry(); ZipEntry xlinkWsFile = zis.getNextEntry(); checkFileEntry(xlinkWsFile, "xlink/" + AppSchemaIO.WORKSPACE_FILE); doc = readDocument(zis); checkWorkspaceDocument(doc, "xlink_workspace", "xlink"); zis.closeEntry(); ZipEntry xlinkNsFile = zis.getNextEntry(); checkFileEntry(xlinkNsFile, "xlink/" + AppSchemaIO.NAMESPACE_FILE); doc = readDocument(zis); checkNamespaceDocument(doc, "xlink_namespace", "xlink", "http://www.w3.org/1999/xlink"); zis.closeEntry(); ZipEntry xsiWsDir = zis.getNextEntry(); checkDirEntry(xsiWsDir, "xsi/"); zis.closeEntry(); ZipEntry xsiWsFile = zis.getNextEntry(); checkFileEntry(xsiWsFile, "xsi/" + AppSchemaIO.WORKSPACE_FILE); doc = readDocument(zis); checkWorkspaceDocument(doc, "xsi_workspace", "xsi"); zis.closeEntry(); ZipEntry xsiNsFile = zis.getNextEntry(); checkFileEntry(xsiNsFile, "xsi/" + AppSchemaIO.NAMESPACE_FILE); doc = readDocument(zis); checkNamespaceDocument(doc, "xsi_namespace", "xsi", AppSchemaMappingUtils.XSI_URI); zis.closeEntry(); assertNull(zis.getNextEntry()); } catch (ZipException e) { fail("Exception reading generated ZIP archive: " + e.getMessage()); } finally { if (tempFile != null) tempFile.delete(); if (zis != null) zis.close(); } }
From source file:org.geoserver.wps.gs.download.DownloadMapProcessTest.java
public void testExecutMultiLayerKmz(String mime) throws Exception { String request = IOUtils.toString(getClass().getResourceAsStream("mapMultiLayer.xml")); request = request.replaceAll("image/png", mime); MockHttpServletResponse response = postAsServletResponse("wps", request); assertEquals(KMZMapOutputFormat.MIME_TYPE, response.getContentType()); assertEquals("inline; filename=result.kmz", response.getHeader("Content-disposition")); ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(response.getContentAsByteArray())); try {/*from w w w . ja v a2s . c om*/ // first entry, the kml document itself ZipEntry entry = zis.getNextEntry(); assertEquals("wms.kml", entry.getName()); byte[] data = IOUtils.toByteArray(zis); Document dom = dom(new ByteArrayInputStream(data)); // print(dom); assertXpathEvaluatesTo("1", "count(//kml:Folder/kml:GroundOverlay)", dom); String href = XMLUnit.newXpathEngine().evaluate("//kml:Folder/kml:GroundOverlay/kml:Icon/kml:href", dom); assertEquals("image.png", href); zis.closeEntry(); // the ground overlay for the raster layer entry = zis.getNextEntry(); assertEquals("image.png", entry.getName()); BufferedImage image = ImageIO.read(zis); zis.closeEntry(); assertNull(zis.getNextEntry()); // check the output, same as mapMultiName ImageAssert.assertEquals(new File(SAMPLES + "mapMultiName.png"), image, 100); } finally { zis.close(); } }
From source file:org.martin.ftp.net.FTPLinker.java
private void extractFile(FileOutputStream fos, ZipEntry entry, int ready, byte[] buffer, ZipInputStream zis) throws FileNotFoundException, IOException { fos = new FileOutputStream(entry.getName()); ready = 0;/*from w w w. j a v a 2 s . c o m*/ buffer = new byte[1024]; while ((ready = zis.read(buffer)) > 0) fos.write(buffer, 0, ready); fos.close(); zis.closeEntry(); }
From source file:org.eclipse.skalli.core.rest.admin.StatisticsBackupResource.java
@Put public Representation restore(Representation entity) { if (!Permits.isAllowed(getAction(), getPath())) { return createUnauthorizedRepresentation(); }//w ww . j a v a 2s . c o m ZipInputStream zipStream = null; try { zipStream = new ZipInputStream(entity.getStream()); ZipEntry entry = zipStream.getNextEntry(); try { String entryName = entry.getName(); if (!entryName.equals(ENTRY_NAME)) { return createErrorRepresentation(Status.CLIENT_ERROR_BAD_REQUEST, ERROR_ID_INVALID_BACKUP, "Invalid backup file: Expected entry ''statistics.xml'', but found ''{0}''", entryName); //$NON-NLS-1$ } ResourceRepresentation<Statistics> representation = new ResourceRepresentation<Statistics>(); addAliases(representation); Statistics.getDefault().restore(representation.read(zipStream, Statistics.class)); } finally { zipStream.closeEntry(); } } catch (IOException e) { return createIOErrorRepresentation(ERROR_ID_IO_ERROR, e); } catch (XStreamException e) { return createErrorRepresentation(Status.CLIENT_ERROR_BAD_REQUEST, ERROR_ID_PARSING_FAILED, "Invalid backup file: {0}", e.getMessage()); //$NON-NLS-1$ } catch (ClassCastException e) { return createErrorRepresentation(Status.CLIENT_ERROR_BAD_REQUEST, ERROR_ID_CLASS_MISMATCH, "Invalid backup file: {0}", e.getMessage()); //$NON-NLS-1$ } finally { IOUtils.closeQuietly(zipStream); } setStatus(Status.SUCCESS_NO_CONTENT); return null; }
From source file:org.theospi.portfolio.help.HelpManagerImpl.java
/** * Given a resource id, this parses out the GlossaryEntries from its input stream. * Once the enties are found, they are inserted into the given worksite. If a term exists * in the worksite, then execute based on the last parameter. * @param worksiteId Id// ww w. java 2 s .co m * @param resourceId an String * @param replaceExisting boolean */ public void importTermsResource(Id worksiteId, String resourceId, boolean replaceExisting) throws IOException, UnsupportedFileTypeException, JDOMException { Node node = getNode(idManager.getId(resourceId)); if (node.getMimeType().equals(new MimeType("text/xml")) || node.getMimeType().equals(new MimeType("application/x-osp")) || node.getMimeType().equals(new MimeType("application/xml"))) { importTermsStream(worksiteId, node.getInputStream(), replaceExisting); } else if (node.getMimeType().equals(new MimeType("application/zip")) || node.getMimeType().equals(new MimeType("application/x-zip-compressed"))) { ZipInputStream zis = new UncloseableZipInputStream(node.getInputStream()); ZipEntry currentEntry = zis.getNextEntry(); boolean found = false; while (currentEntry != null) { if (currentEntry.getName().endsWith("xml")) { importTermsStream(worksiteId, zis, replaceExisting); found = true; } zis.closeEntry(); currentEntry = zis.getNextEntry(); } if (!found) throw new UnsupportedFileTypeException("No glossary xml files were found"); } else { throw new UnsupportedFileTypeException("Unsupported file type"); } }
From source file:org.apache.sling.jcr.contentloader.internal.readers.ZipReader.java
/** * @see org.apache.sling.jcr.contentloader.ContentReader#parse(java.io.InputStream, org.apache.sling.jcr.contentloader.ContentCreator) *///from www .ja va 2 s . co m public void parse(InputStream ins, ContentCreator creator) throws IOException, RepositoryException { try { creator.createNode(null, NT_FOLDER, null); final ZipInputStream zis = new ZipInputStream(ins); ZipEntry entry; do { entry = zis.getNextEntry(); if (entry != null) { if (!entry.isDirectory()) { String name = entry.getName(); int pos = name.lastIndexOf('/'); if (pos != -1) { creator.switchCurrentNode(name.substring(0, pos), NT_FOLDER); } creator.createFileAndResourceNode(name, new CloseShieldInputStream(zis), null, entry.getTime()); creator.finishNode(); creator.finishNode(); if (pos != -1) { creator.finishNode(); } } zis.closeEntry(); } } while (entry != null); creator.finishNode(); } finally { if (ins != null) { try { ins.close(); } catch (IOException ignore) { } } } }
From source file:com.yifanlu.PSXperiaTool.Extractor.CrashBandicootExtractor.java
private void extractZip(File zipFile, File output, FileFilter filter) throws IOException { Logger.info("Extracting ZIP file: %s to: %s", zipFile.getPath(), output.getPath()); if (!output.exists()) output.mkdirs();//from w ww . j av a 2 s. co m ZipInputStream zip = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry entry; while ((entry = zip.getNextEntry()) != null) { File file = new File(output, entry.getName()); if (file.isDirectory()) continue; if (filter != null && !filter.accept(file)) continue; Logger.verbose("Unzipping %s", entry.getName()); FileUtils.touch(file); FileOutputStream out = new FileOutputStream(file.getPath()); int n; byte[] buffer = new byte[BLOCK_SIZE]; while ((n = zip.read(buffer)) != -1) { out.write(buffer, 0, n); } out.close(); zip.closeEntry(); Logger.verbose("Done extracting %s", entry.getName()); } zip.close(); Logger.debug("Done extracting ZIP."); }
From source file:net.wastl.webmail.config.ExtConfigListener.java
/** * @param baseDir//from w ww .j a v a 2s . co 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(); } }
From source file:org.apache.oodt.cas.workflow.misc.WingsTask.java
private void unZipIt(String zipFile, String outputFolder) { byte[] buffer = new byte[1024]; try {//from w w w . j a v a 2s. co m File folder = new File(outputFolder); if (!folder.exists()) { folder.mkdir(); } ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String fileName = ze.getName(); File newFile = new File(outputFolder + File.separator + fileName); new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); } catch (IOException ex) { ex.printStackTrace(); } }