List of usage examples for java.util.zip ZipFile close
public void close() throws IOException
From source file:org.wise.portal.service.wiseup.impl.WiseUpServiceImpl.java
/** * @throws Exception /*from w ww . j a va2 s.c o m*/ * @see org.wise.portal.service.wiseup.WiseUpService#importExternalProject(net.sf.sail.webapp.domain.User, java.lang.String, java.lang.String) */ @Override public void importExternalProject(User newProjectOwner, String externalWiseInstanceId, String externalWiseProjectId) throws Exception { String exportProjectPath = wiseUpHubUrl + "/projectLibrary/exportProject.php" + "?wiseInstanceId=" + externalWiseInstanceId + "&wiseProjectId=" + externalWiseProjectId; // upload the zipfile to curriculum_base_dir String curriculumBaseDir = wiseProperties.getProperty("curriculum_base_dir"); File uploadDir = new File(curriculumBaseDir); if (!uploadDir.exists()) { throw new Exception("curriculum upload directory does not exist."); } // save the downloaded zip file temporarily in the curriculum folder. String sep = System.getProperty("file.separator"); long timeInMillis = Calendar.getInstance().getTimeInMillis(); String filename = ""; String newFilename = ""; String newFileFullPath = ""; File downloadedFile = null; try { URL url = new URL(exportProjectPath); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); URL downloadFileUrl = conn.getURL(); String downloadFileUrlString = downloadFileUrl.toString(); filename = downloadFileUrlString.substring(downloadFileUrlString.lastIndexOf("/") + 1, downloadFileUrlString.indexOf(".zip")); newFilename = filename; if (new File(curriculumBaseDir + sep + filename).exists()) { // if this directory already exists, add a date time in milliseconds to the filename to make it unique newFilename = filename + "-" + timeInMillis; } newFileFullPath = curriculumBaseDir + sep + newFilename + ".zip"; downloadedFile = new File(newFileFullPath); FileOutputStream out = new FileOutputStream(downloadedFile); byte[] b = new byte[1024]; int count; while ((count = in.read(b)) >= 0) { out.write(b, 0, count); } out.flush(); out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } // make a new folder where the contents of the zip should go String newFileFullDir = curriculumBaseDir + sep + newFilename; File newFileFullDirFile = new File(newFileFullDir); newFileFullDirFile.mkdir(); // unzip the zip file try { ZipFile zipFile = new ZipFile(newFileFullPath); Enumeration entries = zipFile.entries(); int i = 0; // index used later to check for first folder in the zip file while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.getName().startsWith("__MACOSX")) { // if this entry starts with __MACOSX, this zip file was created by a user using mac's "compress" feature. // ignore it. continue; } if (entry.isDirectory()) { // first check to see if the user has changed the zip file name and therefore the zipfile name // is no longer the same as the name of the first folder in the top-level of the zip file. // if this is the case, import will fail, so throw an error. if (i == 0) { if (!entry.getName().startsWith(filename)) { throw new Exception( "Zip file name does not match folder name. Do not change zip filename"); } i++; } // Assume directories are stored parents first then children. System.out.println("Extracting directory: " + entry.getName()); // This is not robust, just for demonstration purposes. (new File(entry.getName().replace(filename, newFileFullDir))).mkdir(); continue; } System.out.println("Extracting file: " + entry.getName()); copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream( new FileOutputStream(entry.getName().replaceFirst(filename, newFileFullDir)))); } zipFile.close(); } catch (IOException ioe) { System.err.println("Unhandled exception during project import. Project was not properly imported."); ioe.printStackTrace(); throw ioe; } // remove the temp zip file downloadedFile.delete(); // now create a project in the db with the new path String path = sep + newFilename + sep + "wise4.project.json"; String name = "hiroki's project 4.zip"; Set<User> owners = new HashSet<User>(); owners.add(newProjectOwner); CreateUrlModuleParameters cParams = new CreateUrlModuleParameters(); cParams.setUrl(path); Curnit curnit = curnitService.createCurnit(cParams); ProjectParameters pParams = new ProjectParameters(); pParams.setCurnitId(curnit.getId()); pParams.setOwners(owners); pParams.setProjectname(name); pParams.setProjectType(ProjectType.LD); ProjectMetadata metadata = null; // see if a file called wise4.project-meta.json exists. if yes, try parsing it. try { String projectMetadataFilePath = newFileFullDir + sep + "wise4.project-meta.json"; String projectMetadataStr = FileUtils.readFileToString(new File(projectMetadataFilePath)); JSONObject metadataJSONObj = new JSONObject(projectMetadataStr); metadata = new ProjectMetadataImpl(); metadata.populateFromJSON(metadataJSONObj); } catch (Exception e) { // if there is any error during the parsing of the metadata, set the metadata to null metadata = null; } // If metadata is null at this point, either wise4.project-meta.json was not // found in the zip file, or there was an error parsing. // Set a new fresh metadata object if (metadata == null) { metadata = new ProjectMetadataImpl(); metadata.setTitle(name); } pParams.setMetadata(metadata); Project project = projectService.createProject(pParams); }
From source file:it.greenvulcano.util.zip.ZipHelper.java
/** * Performs the uncompression of a <code>zip</code> file, whose name and * parent directory are passed as arguments, on the local filesystem. The * content of the <code>zip</code> file will be uncompressed within a * specified target directory.<br> * * @param srcDirectory//www . j a va2s.co m * the source parent directory of the file/s to be unzipped. Must * be an absolute pathname. * @param zipFilename * the name of the file to be unzipped. Cannot contain wildcards. * @param targetDirectory * the target directory in which the content of the * <code>zip</code> file will be unzipped. Must be an absolute * pathname. * @throws IOException * If any error occurs during file uncompression. * @throws IllegalArgumentException * if the arguments are invalid. */ public void unzipFile(String srcDirectory, String zipFilename, String targetDirectory) throws IOException { File srcDir = new File(srcDirectory); if (!srcDir.isAbsolute()) { throw new IllegalArgumentException( "The pathname of the source parent directory is NOT absolute: " + srcDirectory); } if (!srcDir.exists()) { throw new IllegalArgumentException( "Source parent directory " + srcDirectory + " NOT found on local filesystem."); } if (!srcDir.isDirectory()) { throw new IllegalArgumentException("Source parent directory " + srcDirectory + " is NOT a directory."); } File srcZipFile = new File(srcDirectory, zipFilename); if (!srcZipFile.exists()) { throw new IllegalArgumentException( "File to be unzipped (" + srcZipFile.getAbsolutePath() + ") NOT found on local filesystem."); } ZipFile zipFile = null; try { zipFile = new ZipFile(srcZipFile); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry currEntry = entries.nextElement(); if (currEntry.isDirectory()) { String targetSubdirPathname = currEntry.getName(); File dir = new File(targetDirectory, targetSubdirPathname); FileUtils.forceMkdir(dir); dir.setLastModified(currEntry.getTime()); } else { InputStream is = null; OutputStream os = null; File file = null; try { is = zipFile.getInputStream(currEntry); FileUtils.forceMkdir(new File(targetDirectory, currEntry.getName()).getParentFile()); file = new File(targetDirectory, currEntry.getName()); os = new FileOutputStream(file); IOUtils.copy(is, os); } finally { try { if (is != null) { is.close(); } if (os != null) { os.close(); } } catch (IOException exc) { // Do nothing } if (file != null) { file.setLastModified(currEntry.getTime()); } } } } } finally { try { if (zipFile != null) { zipFile.close(); } } catch (Exception exc) { // do nothing } } }
From source file:org.telscenter.sail.webapp.service.wiseup.impl.WiseUpServiceImpl.java
/** * @throws Exception /*from www . ja v a 2s . c o m*/ * @see org.telscenter.sail.webapp.service.wiseup.WiseUpService#importExternalProject(net.sf.sail.webapp.domain.User, java.lang.String, java.lang.String) */ @Override public void importExternalProject(User newProjectOwner, String externalWiseInstanceId, String externalWiseProjectId) throws Exception { String exportProjectPath = wiseUpHubUrl + "/projectLibrary/exportProject.php" + "?wiseInstanceId=" + externalWiseInstanceId + "&wiseProjectId=" + externalWiseProjectId; // upload the zipfile to curriculum_base_dir String curriculumBaseDir = portalProperties.getProperty("curriculum_base_dir"); File uploadDir = new File(curriculumBaseDir); if (!uploadDir.exists()) { throw new Exception("curriculum upload directory does not exist."); } // save the downloaded zip file temporarily in the curriculum folder. String sep = System.getProperty("file.separator"); long timeInMillis = Calendar.getInstance().getTimeInMillis(); String filename = ""; String newFilename = ""; String newFileFullPath = ""; File downloadedFile = null; try { URL url = new URL(exportProjectPath); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); URL downloadFileUrl = conn.getURL(); String downloadFileUrlString = downloadFileUrl.toString(); filename = downloadFileUrlString.substring(downloadFileUrlString.lastIndexOf("/") + 1, downloadFileUrlString.indexOf(".zip")); newFilename = filename; if (new File(curriculumBaseDir + sep + filename).exists()) { // if this directory already exists, add a date time in milliseconds to the filename to make it unique newFilename = filename + "-" + timeInMillis; } newFileFullPath = curriculumBaseDir + sep + newFilename + ".zip"; downloadedFile = new File(newFileFullPath); FileOutputStream out = new FileOutputStream(downloadedFile); byte[] b = new byte[1024]; int count; while ((count = in.read(b)) >= 0) { out.write(b, 0, count); } out.flush(); out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } // make a new folder where the contents of the zip should go String newFileFullDir = curriculumBaseDir + sep + newFilename; File newFileFullDirFile = new File(newFileFullDir); newFileFullDirFile.mkdir(); // unzip the zip file try { ZipFile zipFile = new ZipFile(newFileFullPath); Enumeration entries = zipFile.entries(); int i = 0; // index used later to check for first folder in the zip file while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.getName().startsWith("__MACOSX")) { // if this entry starts with __MACOSX, this zip file was created by a user using mac's "compress" feature. // ignore it. continue; } if (entry.isDirectory()) { // first check to see if the user has changed the zip file name and therefore the zipfile name // is no longer the same as the name of the first folder in the top-level of the zip file. // if this is the case, import will fail, so throw an error. if (i == 0) { if (!entry.getName().startsWith(filename)) { throw new Exception( "Zip file name does not match folder name. Do not change zip filename"); } i++; } // Assume directories are stored parents first then children. System.out.println("Extracting directory: " + entry.getName()); // This is not robust, just for demonstration purposes. (new File(entry.getName().replace(filename, newFileFullDir))).mkdir(); continue; } System.out.println("Extracting file: " + entry.getName()); copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream( new FileOutputStream(entry.getName().replaceFirst(filename, newFileFullDir)))); } zipFile.close(); } catch (IOException ioe) { System.err.println("Unhandled exception during project import. Project was not properly imported."); ioe.printStackTrace(); throw ioe; } // remove the temp zip file downloadedFile.delete(); // now create a project in the db with the new path String path = sep + newFilename + sep + "wise4.project.json"; String name = "hiroki's project 4.zip"; Set<User> owners = new HashSet<User>(); owners.add(newProjectOwner); CreateUrlModuleParameters cParams = new CreateUrlModuleParameters(); cParams.setUrl(path); Curnit curnit = curnitService.createCurnit(cParams); ProjectParameters pParams = new ProjectParameters(); pParams.setCurnitId(curnit.getId()); pParams.setOwners(owners); pParams.setProjectname(name); pParams.setProjectType(ProjectType.LD); ProjectMetadata metadata = null; // see if a file called wise4.project-meta.json exists. if yes, try parsing it. try { String projectMetadataFilePath = newFileFullDir + sep + "wise4.project-meta.json"; String projectMetadataStr = FileUtils.readFileToString(new File(projectMetadataFilePath)); JSONObject metadataJSONObj = new JSONObject(projectMetadataStr); metadata = new ProjectMetadataImpl(); metadata.populateFromJSON(metadataJSONObj); } catch (Exception e) { // if there is any error during the parsing of the metadata, set the metadata to null metadata = null; } // If metadata is null at this point, either wise4.project-meta.json was not // found in the zip file, or there was an error parsing. // Set a new fresh metadata object if (metadata == null) { metadata = new ProjectMetadataImpl(); metadata.setTitle(name); } pParams.setMetadata(metadata); Project project = projectService.createProject(pParams); }
From source file:com.ichi2.libanki.Media.java
/** * Extract zip data; return the number of files extracted. Unlike the python version, this method consumes a * ZipFile stored on disk instead of a String buffer. Holding the entire downloaded data in memory is not feasible * since some devices can have very limited heap space. * * This method closes the file before it returns. *///ww w . j a v a 2s .c o m public int addFilesFromZip(ZipFile z) throws IOException { try { List<Object[]> media = new ArrayList<Object[]>(); // get meta info first JSONObject meta = new JSONObject(Utils.convertStreamToString(z.getInputStream(z.getEntry("_meta")))); // then loop through all files int cnt = 0; for (ZipEntry i : Collections.list(z.entries())) { if (i.getName().equals("_meta")) { // ignore previously-retrieved meta continue; } else { String name = meta.getString(i.getName()); // normalize name for platform name = HtmlUtil.nfcNormalized(name); // save file String destPath = dir().concat(File.separator).concat(name); Utils.writeToFile(z.getInputStream(i), destPath); String csum = Utils.fileChecksum(destPath); // update db media.add(new Object[] { name, csum, _mtime(destPath), 0 }); cnt += 1; } } if (media.size() > 0) { mDb.executeMany("insert or replace into media values (?,?,?,?)", media); } return cnt; } catch (JSONException e) { throw new RuntimeException(e); } finally { z.close(); } }
From source file:org.paxle.core.doc.impl.BasicDocumentFactoryTest.java
public void testLoadUnmarshalledCommand() throws IOException, ParseException { final ZipFile zf = new ZipFile(new File("src/test/resources/command.zip")); // process attachments final Map<String, DataHandler> attachments = new HashMap<String, DataHandler>(); for (Enumeration<? extends ZipEntry> entries = zf.entries(); entries.hasMoreElements();) { final ZipEntry entry = entries.nextElement(); final String name = entry.getName(); if (name.equals("command.xml")) continue; // create a data-source to load the attachment final DataSource source = new DataSource() { private ZipFile zip = zf; private ZipEntry zipEntry = entry; public String getContentType() { return "application/x-java-serialized-object"; }//from www . j ava 2 s . c o m public InputStream getInputStream() throws IOException { return this.zip.getInputStream(this.zipEntry); } public String getName() { return this.zipEntry.getName(); } public OutputStream getOutputStream() throws IOException { throw new UnsupportedOperationException(); } }; final DataHandler handler = new DataHandler(source); attachments.put(name, handler); } // process command final ZipEntry commandEntry = zf.getEntry("command.xml"); final InputStream commandInput = zf.getInputStream(commandEntry); // marshal command TeeInputStream input = new TeeInputStream(commandInput, System.out); final ICommand cmd1 = this.docFactory.unmarshal(input, attachments); assertNotNull(cmd1); zf.close(); final ICommand cmd2 = this.createTestCommand(); assertEquals(cmd2, cmd1); }
From source file:com.edgenius.wiki.service.impl.BackupServiceImpl.java
public String getFileComment(File zipFile) { String comment = ""; ZipFile zip = null; try {// w w w .j a v a2 s . c o m zip = new ZipFile(zipFile); ZipEntry entry = zip.getEntry(COMMENT_FILE_NAME); if (entry != null) { comment = IOUtils.toString(zip.getInputStream(entry)); } } catch (Exception e) { log.info("backup/restore file comment not available:" + zipFile.getAbsolutePath()); } finally { if (zip != null) try { zip.close(); } catch (Exception e) { } } return comment; }
From source file:paulscode.android.mupen64plusae.GalleryActivity.java
private void ExtractFileIfNeeded(String md5, ConfigFile config, String romPath, String zipPath, boolean isExtracted) { final File romFile = new File(romPath); final RomHeader romHeader = new RomHeader(zipPath); final boolean isZip = romHeader.isZip; if (isZip && (!romFile.exists() || !isExtracted)) { boolean lbFound = false; try {//from ww w .j a va 2 s .c o m final ZipFile zipFile = new ZipFile(zipPath); final Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements() && !lbFound) { final ZipEntry zipEntry = entries.nextElement(); try { final InputStream zipStream = zipFile.getInputStream(zipEntry); final File destDir = new File(mGlobalPrefs.unzippedRomsDir); final String entryName = new File(zipEntry.getName()).getName(); File tempRomPath = new File(destDir, entryName); final boolean fileExisted = tempRomPath.exists(); if (!fileExisted) { tempRomPath = FileUtil.extractRomFile(destDir, zipEntry, zipStream); } final String computedMd5 = ComputeMd5Task.computeMd5(tempRomPath); lbFound = computedMd5.equals(md5); //only deleye the file if we extracted our selves if (!lbFound && !fileExisted) { tempRomPath.delete(); } zipStream.close(); } catch (final IOException e) { Log.w("CacheRomInfoTask", e); } } zipFile.close(); } catch (final IOException | ArrayIndexOutOfBoundsException e) { Log.w("GalleryActivity", e); } if (lbFound || romFile.exists()) { config.put(md5, "extracted", "true"); } } }
From source file:com.disney.opa.util.AttachmentUtils.java
/** * This method is to extract the zip files and creates attachment objects. * //from ww w . ja v a 2s. c o m * @param attachment * @param fileNames * @param fileLabels * @param errors * @return list of attachments from the zip file */ public List<Attachment> processZipFile(Attachment attachment, List<String> fileNames, List<String> fileLabels, List<String> errors) { ZipFile zipFile = null; List<Attachment> attachments = new ArrayList<Attachment>(); try { String zipFilePath = getOriginalAttachmentsPath(attachment.getProductID()) + File.separator + attachment.getFilename(); zipFile = new ZipFile(zipFilePath); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; } String fileName = entry.getName(); File destinationFile = new File( getOriginalAttachmentsPath(attachment.getProductID()) + File.separator + fileName); uploadFile(zipFile.getInputStream(entry), destinationFile); String label = createUniqueFileLabel(fileName, null, fileLabels); Attachment fileAttachment = getAttachment(fileName, label, attachment.getProductID(), attachment.getProductStateID(), attachment.getUserID()); if (fileAttachment.getFileSize() == 0L) { errors.add("File not found, file name: " + fileName + ", in zip file: " + attachment.getFilename()); } else { attachments.add(fileAttachment); } } } catch (Exception e) { errors.add( "Error while processing zip: " + attachment.getFilename() + ", title: " + attachment.getName()); log.error("Error while processing zip.", e); } finally { try { if (zipFile != null) { zipFile.close(); } } catch (IOException e) { } } return attachments; }
From source file:org.hammurapi.TaskBase.java
protected File processArchive() { if (archive == null) { return null; }/* w w w. j a v a 2 s . com*/ String tmpDirProperty = System.getProperty("java.io.tmpdir"); File tmpDir = tmpDirProperty == null ? new File(".") : new File(tmpDirProperty); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String prefix = "har_" + sdf.format(new Date()); File workDir = unpackDir == null ? new File(tmpDir, prefix) : unpackDir; for (int i = 0; unpackDir == null && workDir.exists(); i++) { workDir = new File(tmpDir, prefix + "_" + Integer.toString(i, Character.MAX_RADIX)); } if (workDir.exists() || workDir.mkdir()) { try { ZipFile zipFile = new ZipFile(archive); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.getName().endsWith("/")) { File outFile = new File(workDir, entry.getName().replace('/', File.separatorChar)); if (!outFile.getParentFile().exists() && !outFile.getParentFile().mkdirs()) { throw new BuildException("Directory does not exist and cannot be created: " + outFile.getParentFile().getAbsolutePath()); } log("Archive entry " + entry.getName() + " unpacked to " + outFile.getAbsolutePath(), Project.MSG_DEBUG); byte[] buf = new byte[4096]; int l; InputStream in = zipFile.getInputStream(entry); FileOutputStream fos = new FileOutputStream(outFile); while ((l = in.read(buf)) != -1) { fos.write(buf, 0, l); } in.close(); fos.close(); } } zipFile.close(); File configFile = new File(workDir, "config.xml"); if (configFile.exists() && configFile.isFile()) { Document configDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(configFile); processConfig(workDir, configDoc.getDocumentElement()); } else { throw new BuildException("Archive configuration file does not exist or is not a file"); } } catch (ZipException e) { throw new BuildException(e.toString(), e); } catch (IOException e) { throw new BuildException(e.toString(), e); } catch (SAXException e) { throw new BuildException(e.toString(), e); } catch (ParserConfigurationException e) { throw new BuildException(e.toString(), e); } catch (FactoryConfigurationError e) { throw new BuildException(e.toString(), e); } } else { throw new BuildException("Could not create directory " + workDir.getAbsolutePath()); } return unpackDir == null ? workDir : null; }
From source file:org.nuxeo.launcher.connect.ConnectBroker.java
protected Map<String, PackageDefinition> getDistributionDefinitions(List<String> md5Filenames) { Map<String, PackageDefinition> allDefinitions = new HashMap<>(); if (md5Filenames == null) { return allDefinitions; }//from w w w.j a va 2 s. c o m for (String md5Filename : md5Filenames) { File md5File = new File(distributionMPDir, md5Filename); if (!md5File.exists()) { // distribution file has been deleted continue; } ZipFile zipFile; try { zipFile = new ZipFile(md5File); } catch (ZipException e) { log.warn("Unzip error reading file " + md5File, e); continue; } catch (IOException e) { log.warn("Could not read file " + md5File, e); continue; } try { ZipEntry zipEntry = zipFile.getEntry("package.xml"); InputStream in = zipFile.getInputStream(zipEntry); PackageDefinition pd = NuxeoConnectClient.getPackageUpdateService().loadPackage(in); allDefinitions.put(md5Filename, pd); } catch (Exception e) { log.error("Could not read package description", e); continue; } finally { try { zipFile.close(); } catch (IOException e) { log.warn("Unexpected error closing file " + md5File, e); } } } return allDefinitions; }