List of usage examples for java.util.zip ZipInputStream closeEntry
public void closeEntry() throws IOException
From source file:de.intranda.goobi.plugins.CSICMixedImport.java
/** * Unzip a zip archive and write results into Array of Strings * /* ww w. j a v a 2 s.c om*/ * @param source * @return */ private HashMap<String, byte[]> unzipFile(File source) { ArrayList<String> filenames = new ArrayList<String>(); HashMap<String, byte[]> contentMap = new HashMap<String, byte[]>(); FileInputStream fis = null; BufferedInputStream bis = null; ZipInputStream in = null; try { fis = new FileInputStream(source); bis = new BufferedInputStream(fis); in = new ZipInputStream(bis); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { filenames.add(entry.getName()); logger.debug("Unzipping file " + entry.getName() + " from archive " + source.getName()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream out = new BufferedOutputStream(baos); int size; byte[] buffer = new byte[2048]; while ((size = in.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, size); } if (entry != null) in.closeEntry(); if (out != null) { out.close(); } if (baos != null) { baos.close(); } contentMap.put(entry.getName(), baos.toByteArray()); } } catch (IOException e) { logger.error(e.toString(), e); } finally { try { if (fis != null) { fis.close(); } if (bis != null) { bis.close(); } if (in != null) { in.close(); } } catch (IOException e) { logger.error(e.toString(), e); } } return contentMap; }
From source file:pl.psnc.synat.wrdz.zmd.object.parser.ObjectModificationParser.java
/** * Parses the request provided as ZIP.//from w w w .j a va 2 s . c o m * * @param identifier * identifier of the object * @param zis * input stream of the zip request * @return internal representation of the request * @throws IncompleteDataException * when some data are missing * @throws InvalidDataException * when some data are invalid */ public ObjectModificationRequest parse(String identifier, ZipInputStream zis) throws IncompleteDataException, InvalidDataException { ObjectModificationRequestBuilder requestBuilder = new ObjectModificationRequestBuilder(identifier); requestBuilder.setDeleteAllContent(true); if (!new File(root).mkdir()) { logger.error("Root folder " + root + " creation failed."); throw new WrdzRuntimeException("Root folder " + root + " creation failed."); } ZipEntry entry = null; try { while ((entry = zis.getNextEntry()) != null) { logger.debug("unzipping: " + entry.getName() + " - is directory: " + entry.isDirectory()); if (entry.isDirectory()) { if (!new File(root + "/" + entry.getName()).mkdir()) { logger.error("folder " + entry.getName() + " creation failed."); throw new WrdzRuntimeException("Folder " + entry.getName() + " creation failed."); } } else { BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(root + "/" + entry.getName()), 1024); int len; byte[] buffer = new byte[1024]; while ((len = zis.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.flush(); bos.close(); if (entry.getName().toLowerCase().startsWith("metadata/")) { String metadataName = entry.getName().substring(new String("metadata/").length()); if (metadataName.contains("/")) { requestBuilder.addInputFileToAddMetadataFile( metadataName.substring(0, metadataName.lastIndexOf('/')), ObjectManagerRequestHelper.makeUri(root, entry.getName())); } else { requestBuilder.addObjectMetadataToAdd( ObjectManagerRequestHelper.makeUri(root, entry.getName())); } } else { String contentName = entry.getName(); if (contentName.toLowerCase().startsWith("content/")) { contentName = contentName.substring(new String("content/").length()); } requestBuilder.setInputFileToAddSource(contentName, ObjectManagerRequestHelper.makeUri(root, entry.getName())); requestBuilder.setInputFileToAddDestination(contentName, contentName); } } zis.closeEntry(); } zis.close(); } catch (FileNotFoundException e) { logger.error("Saving the file " + entry.getName() + " failed!"); throw new WrdzRuntimeException(e.getMessage()); } catch (IOException e) { logger.error("Uncorrect zip file.", e); FileUtils.deleteQuietly(new File(root)); throw new InvalidDataException(e.getMessage()); } return requestBuilder.build(); }
From source file:org.olat.core.util.ZipUtil.java
/** * Unzip an inputstream to a directory using the versioning system of VFS * @param zipLeaf The file to unzip/* www . jav a2s .c o m*/ * @param targetDir The directory to unzip the file to * @param the identity of who unzip the file * @param versioning enabled or not * @return True if successfull, false otherwise */ private static boolean unzip(InputStream in, VFSContainer targetDir, Identity identity, boolean versioning) { ZipInputStream oZip = new ZipInputStream(in); try { // unzip files ZipEntry oEntr = oZip.getNextEntry(); while (oEntr != null) { if (oEntr.getName() != null && !oEntr.getName().startsWith(DIR_NAME__MACOSX)) { if (oEntr.isDirectory()) { // skip MacOSX specific metadata directory // create directories getAllSubdirs(targetDir, oEntr.getName(), identity, true); } else { // create file VFSContainer createIn = targetDir; String name = oEntr.getName(); // check if entry has directories which did not show up as // directories above int dirSepIndex = name.lastIndexOf('/'); if (dirSepIndex == -1) { // try it windows style, backslash is also valid format dirSepIndex = name.lastIndexOf('\\'); } if (dirSepIndex > 0) { // create subdirs createIn = getAllSubdirs(targetDir, name.substring(0, dirSepIndex), identity, true); if (createIn == null) { if (log.isDebug()) log.debug( "Error creating directory structure for zip entry: " + oEntr.getName()); return false; } name = name.substring(dirSepIndex + 1); } if (versioning) { VFSLeaf newEntry = (VFSLeaf) createIn.resolve(name); if (newEntry == null) { newEntry = createIn.createChildLeaf(name); OutputStream out = newEntry.getOutputStream(false); if (!FileUtils.copy(oZip, out)) return false; FileUtils.closeSafely(out); } else if (newEntry instanceof Versionable) { Versionable versionable = (Versionable) newEntry; if (versionable.getVersions().isVersioned()) { versionable.getVersions().addVersion(identity, "", oZip); } } if (newEntry instanceof MetaTagged) { MetaInfo info = ((MetaTagged) newEntry).getMetaInfo(); if (info != null) { info.setAuthor(identity); info.write(); } } } else { VFSLeaf newEntry = createIn.createChildLeaf(name); if (newEntry != null) { OutputStream out = newEntry.getOutputStream(false); if (!FileUtils.copy(oZip, out)) return false; FileUtils.closeSafely(out); } if (newEntry instanceof MetaTagged) { MetaInfo info = ((MetaTagged) newEntry).getMetaInfo(); if (info != null && identity != null) { info.setAuthor(identity); info.write(); } } } } } oZip.closeEntry(); oEntr = oZip.getNextEntry(); } } catch (IOException e) { return false; } finally { FileUtils.closeSafely(oZip); } return true; }
From source file:org.olat.core.util.ZipUtil.java
/** * Unzip with jazzlib// w ww . ja v a 2s .c om * @param in * @param targetDir * @param identity * @param versioning * @return */ private static boolean unzipNonStrict(InputStream in, VFSContainer targetDir, Identity identity, boolean versioning) { net.sf.jazzlib.ZipInputStream oZip = new net.sf.jazzlib.ZipInputStream(in); try { // unzip files net.sf.jazzlib.ZipEntry oEntr = oZip.getNextEntry(); while (oEntr != null) { if (oEntr.getName() != null && !oEntr.getName().startsWith(DIR_NAME__MACOSX)) { if (oEntr.isDirectory()) { // skip MacOSX specific metadata directory // create directories getAllSubdirs(targetDir, oEntr.getName(), identity, true); } else { // create file VFSContainer createIn = targetDir; String name = oEntr.getName(); // check if entry has directories which did not show up as // directories above int dirSepIndex = name.lastIndexOf('/'); if (dirSepIndex == -1) { // try it windows style, backslash is also valid format dirSepIndex = name.lastIndexOf('\\'); } if (dirSepIndex > 0) { // create subdirs createIn = getAllSubdirs(targetDir, name.substring(0, dirSepIndex), identity, true); if (createIn == null) { if (log.isDebug()) log.debug( "Error creating directory structure for zip entry: " + oEntr.getName()); return false; } name = name.substring(dirSepIndex + 1); } if (versioning) { VFSLeaf newEntry = (VFSLeaf) createIn.resolve(name); if (newEntry == null) { newEntry = createIn.createChildLeaf(name); OutputStream out = newEntry.getOutputStream(false); if (!FileUtils.copy(oZip, out)) return false; FileUtils.closeSafely(out); } else if (newEntry instanceof Versionable) { Versionable versionable = (Versionable) newEntry; if (versionable.getVersions().isVersioned()) { versionable.getVersions().addVersion(identity, "", oZip); } } if (newEntry instanceof MetaTagged) { MetaInfo info = ((MetaTagged) newEntry).getMetaInfo(); if (info != null) { info.setAuthor(identity); info.write(); } } } else { VFSLeaf newEntry = createIn.createChildLeaf(name); if (newEntry != null) { OutputStream out = newEntry.getOutputStream(false); if (!FileUtils.copy(oZip, out)) return false; FileUtils.closeSafely(out); } if (newEntry instanceof MetaTagged) { MetaInfo info = ((MetaTagged) newEntry).getMetaInfo(); if (info != null && identity != null) { info.setAuthor(identity); info.write(); } } } } } oZip.closeEntry(); oEntr = oZip.getNextEntry(); } } catch (IOException e) { return false; } finally { FileUtils.closeSafely(oZip); } return true; }
From source file:io.fabric8.tooling.archetype.generator.ArchetypeHelper.java
/** * Main method which extracts given Maven Archetype in destination directory * * @return//from w w w .j a v a2s. c o m */ public int execute() throws IOException { outputDir.mkdirs(); if (packageName == null || packageName.length() == 0) { packageName = groupId + "." + artifactId; } String packageDir = packageName.replace('.', '/'); info("Creating archetype using Maven groupId: " + groupId + ", artifactId: " + artifactId + ", version: " + version + " in directory: " + outputDir); Map<String, String> replaceProperties = new HashMap<String, String>(); ZipInputStream zip = null; try { zip = new ZipInputStream(archetypeIn); boolean ok = true; while (ok) { ZipEntry entry = zip.getNextEntry(); if (entry == null) { ok = false; } else { if (!entry.isDirectory()) { String fullName = entry.getName(); if (fullName != null && fullName.startsWith(zipEntryPrefix)) { String name = replaceFileProperties(fullName.substring(zipEntryPrefix.length()), replaceProperties); debug("Processing resource: " + name); int idx = name.lastIndexOf('/'); Matcher matcher = sourcePathRegexPattern.matcher(name); String dirName; if (packageName.length() > 0 && idx > 0 && matcher.matches()) { String prefix = matcher.group(1); dirName = prefix + packageDir + "/" + name.substring(prefix.length()); } else if (packageName.length() > 0 && name.startsWith(webInfResources)) { dirName = "src/main/webapp/WEB-INF/" + packageDir + "/resources" + name.substring(webInfResources.length()); } else { dirName = name; } // lets replace properties... File file = new File(outputDir, dirName); file.getParentFile().mkdirs(); FileOutputStream out = null; try { out = new FileOutputStream(file); boolean isBinary = false; for (String suffix : binarySuffixes) { if (name.endsWith(suffix)) { isBinary = true; break; } } if (isBinary) { // binary file? don't transform. copy(zip, out); } else { // text file... ByteArrayOutputStream bos = new ByteArrayOutputStream(); copy(zip, bos); String text = new String(bos.toByteArray(), "UTF-8"); out.write(transformContents(text, replaceProperties).getBytes()); } } finally { if (out != null) { out.close(); } } } else if (fullName != null && fullName.equals("META-INF/maven/archetype-metadata.xml")) { // we assume that this resource will be first in Archetype's ZIP // this way we can find out what are the required properties before we will actually use them parseReplaceProperties(zip, replaceProperties); replaceProperties.putAll(overrideProperties); } } zip.closeEntry(); } } } catch (Exception e) { throw new IOException(e.getMessage(), e); } finally { if (zip != null) { zip.close(); } } info("Using replace properties: " + replaceProperties); // now lets replace all the properties in the pom.xml if (!replaceProperties.isEmpty()) { File pom = new File(outputDir, "pom.xml"); FileReader reader = new FileReader(pom); String text = IOUtils.toString(reader); IOUtils.closeQuietly(reader); for (Map.Entry<String, String> e : replaceProperties.entrySet()) { text = replaceVariable(text, e.getKey(), e.getValue()); } FileWriter writer = new FileWriter(pom); IOUtils.write(text, writer); IOUtils.closeQuietly(writer); } // now lets create the default directories if (createDefaultDirectories) { File srcDir = new File(outputDir, "src"); File mainDir = new File(srcDir, "main"); File testDir = new File(srcDir, "test"); String srcDirName = "java"; // Who needs Scala in 2014? // if (new File(mainDir, "scala").exists() || new File(textDir, "scala").exists()) { // srcDirName = "scala"; // } for (File dir : new File[] { mainDir, testDir }) { for (String name : new String[] { srcDirName + "/" + packageDir, "resources" }) { new File(dir, name).mkdirs(); } } } return 0; }
From source file:org.openmeetings.servlet.outputhandler.BackupImportController.java
public void performImport(InputStream is, String current_dir) throws Exception { File working_dir = new File(current_dir, OpenmeetingsVariables.UPLOAD_DIR + File.separatorChar + "import"); if (!working_dir.exists()) { working_dir.mkdir();// ww w . j av a2 s .com } File f = new File(working_dir, "import_" + CalendarPatterns.getTimeForStreamId(new Date())); int recursiveNumber = 0; do { if (f.exists()) { f = new File(f.getAbsolutePath() + (recursiveNumber++)); } } while (f.exists()); f.mkdir(); log.debug("##### WRITE FILE TO: " + f); ZipInputStream zipinputstream = new ZipInputStream(is); byte[] buf = new byte[1024]; ZipEntry zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { // for each entry to be extracted int n; FileOutputStream fileoutputstream; File fentryName = new File(f, zipentry.getName()); if (zipentry.isDirectory()) { if (!fentryName.mkdir()) { break; } zipentry = zipinputstream.getNextEntry(); continue; } File fparent = new File(fentryName.getParent()); if (!fparent.exists()) { File fparentparent = new File(fparent.getParent()); if (!fparentparent.exists()) { File fparentparentparent = new File(fparentparent.getParent()); if (!fparentparentparent.exists()) { fparentparentparent.mkdir(); fparentparent.mkdir(); fparent.mkdir(); } else { fparentparent.mkdir(); fparent.mkdir(); } } else { fparent.mkdir(); } } fileoutputstream = new FileOutputStream(fentryName); while ((n = zipinputstream.read(buf, 0, 1024)) > -1) { fileoutputstream.write(buf, 0, n); } fileoutputstream.close(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } // while zipinputstream.close(); /* * ##################### Import Organizations */ File orgFile = new File(f, "organizations.xml"); if (!orgFile.exists()) { throw new Exception("organizations.xml missing"); } this.importOrganizsations(orgFile); log.info("Organizations import complete, starting user import"); /* * ##################### Import Users */ File userFile = new File(f, "users.xml"); if (!userFile.exists()) { throw new Exception("users.xml missing"); } this.importUsers(userFile); log.info("Users import complete, starting room import"); /* * ##################### Import Rooms */ File roomFile = new File(f, "rooms.xml"); if (!roomFile.exists()) { throw new Exception("rooms.xml missing"); } this.importRooms(roomFile); log.info("Room import complete, starting room organizations import"); /* * ##################### Import Room Organisations */ File orgRoomListFile = new File(f, "rooms_organisation.xml"); if (!orgRoomListFile.exists()) { throw new Exception("rooms_organisation.xml missing"); } this.importOrgRooms(orgRoomListFile); log.info("Room organizations import complete, starting appointement import"); /* * ##################### Import Appointements */ File appointementListFile = new File(f, "appointements.xml"); if (!appointementListFile.exists()) { throw new Exception("appointements.xml missing"); } this.importAppointements(appointementListFile); log.info("Appointement import complete, starting meeting members import"); /* * ##################### Import MeetingMembers * * Reminder Invitations will be NOT send! */ File meetingmembersListFile = new File(f, "meetingmembers.xml"); if (!meetingmembersListFile.exists()) { throw new Exception("meetingmembersListFile missing"); } this.importMeetingmembers(meetingmembersListFile); log.info("Meeting members import complete, starting ldap config import"); /* * ##################### Import LDAP Configs */ File ldapConfigListFile = new File(f, "ldapconfigs.xml"); if (!ldapConfigListFile.exists()) { log.debug("meetingmembersListFile missing"); // throw new Exception // ("meetingmembersListFile missing"); } else { this.importLdapConfig(ldapConfigListFile); } log.info("Ldap config import complete, starting recordings import"); /* * ##################### Import Recordings */ File flvRecordingsListFile = new File(f, "flvRecordings.xml"); if (!flvRecordingsListFile.exists()) { log.debug("flvRecordingsListFile missing"); // throw new Exception // ("meetingmembersListFile missing"); } else { this.importFlvRecordings(flvRecordingsListFile); } log.info("FLVrecording import complete, starting private message folder import"); /* * ##################### Import Private Message Folders */ File privateMessageFoldersFile = new File(f, "privateMessageFolder.xml"); if (!privateMessageFoldersFile.exists()) { log.debug("privateMessageFoldersFile missing"); // throw new Exception // ("meetingmembersListFile missing"); } else { this.importPrivateMessageFolders(privateMessageFoldersFile); } log.info("Private message folder import complete, starting private message import"); /* * ##################### Import Private Messages */ File privateMessagesFile = new File(f, "privateMessages.xml"); if (!privateMessagesFile.exists()) { log.debug("privateMessagesFile missing"); // throw new Exception // ("meetingmembersListFile missing"); } else { this.importPrivateMessages(privateMessagesFile); } log.info("Private message import complete, starting usercontact import"); /* * ##################### Import User Contacts */ File userContactsFile = new File(f, "userContacts.xml"); if (!userContactsFile.exists()) { log.debug("userContactsFile missing"); // throw new Exception // ("meetingmembersListFile missing"); } else { this.importUserContacts(userContactsFile); } log.info("Usercontact import complete, starting file explorer item import"); /* * ##################### Import File-Explorer Items */ File fileExplorerListFile = new File(f, "fileExplorerItems.xml"); if (!fileExplorerListFile.exists()) { log.debug("fileExplorerListFile missing"); // throw new Exception // ("meetingmembersListFile missing"); } else { this.importFileExplorerItems(fileExplorerListFile); } log.info("File explorer item import complete, starting file poll import"); /* * ##################### Import Room Polls */ File roomPollListFile = new File(f, "roompolls.xml"); if (!roomPollListFile.exists()) { log.debug("roomPollListFile missing"); } else { this.importRoomPolls(roomPollListFile); } log.info("Poll import complete, starting configs import"); /* * ##################### Import Configs */ File configsFile = new File(f, "configs.xml"); if (!configsFile.exists()) { log.debug("configsFile missing"); } else { importConfigs(configsFile); } log.info("Configs import complete, starting asteriskSipUsersFile import"); /* * ##################### Import AsteriskSipUsers */ File asteriskSipUsersFile = new File(f, "asterisksipusers.xml"); if (!asteriskSipUsersFile.exists()) { log.debug("asteriskSipUsersFile missing"); } else { importAsteriskSipUsers(asteriskSipUsersFile); } log.info("AsteriskSipUsers import complete, starting extensions import"); /* * ##################### Import Extensions */ File extensionsFile = new File(f, "extensions.xml"); if (!extensionsFile.exists()) { log.debug("extensionsFile missing"); } else { importExtensions(extensionsFile); } log.info("Extensions import complete, starting members import"); /* * ##################### Import Extensions */ File membersFile = new File(f, "members.xml"); if (!membersFile.exists()) { log.debug("membersFile missing"); } else { importMembers(membersFile); } log.info("Members import complete, starting copy of files and folders"); /* * ##################### Import real files and folders */ importFolders(current_dir, f); log.info("File explorer item import complete, clearing temp files"); deleteDirectory(f); }
From source file:org.sakaiproject.tool.assessment.contentpackaging.ImportService.java
public String unzipImportFile(String filename) { FileInputStream fileInputStream = null; FileOutputStream ofile = null; ZipInputStream zipStream = null; ZipEntry entry = null;/*from w w w. j a v a 2s .c om*/ ExternalContext external = FacesContext.getCurrentInstance().getExternalContext(); StringBuilder unzipLocation = new StringBuilder( (String) ((ServletContext) external.getContext()).getAttribute("FILEUPLOAD_REPOSITORY_PATH")); log.debug("****" + unzipLocation); unzipLocation.append("/jsf/upload_tmp/qti_imports/"); unzipLocation.append(AgentFacade.getAgentString()); unzipLocation.append("/unzip_files/"); unzipLocation.append(Long.toString(new java.util.Date().getTime())); try { fileInputStream = new FileInputStream(new File(filename)); byte[] data = new byte[fileInputStream.available()]; fileInputStream.read(data, 0, fileInputStream.available()); File dir = new File(unzipLocation.toString()); // directory where file would be saved if (!dir.exists()) { if (!dir.mkdirs()) { log.error("unable to mkdir " + dir.getPath()); } } Set dirsMade = new TreeSet(); zipStream = new ZipInputStream(new ByteArrayInputStream(data)); entry = (ZipEntry) zipStream.getNextEntry(); // Get the name of the imported zip file name. The value of "filename" has timestamp append to it. String tmpName = filename.substring(filename.lastIndexOf("/") + 1); qtiFilename = "exportAssessment.xml"; ArrayList xmlFilenames = new ArrayList(); while (entry != null) { String zipName = entry.getName(); int ix = zipName.lastIndexOf('/'); if (ix > 0) { String dirName = zipName.substring(0, ix); if (!dirsMade.contains(dirName)) { File d = new File(dir.getPath() + "/" + dirName); // If it already exists as a dir, don't do anything if (!(d.exists() && d.isDirectory())) { // Try to create the directory, warn if it fails if (!d.mkdirs()) { log.error("unable to mkdir " + dir.getPath() + "/" + dirName); } dirsMade.add(dirName); } } } File zipEntryFile = new File(dir.getPath() + "/" + entry.getName()); if (!zipEntryFile.isDirectory()) { ofile = new FileOutputStream(zipEntryFile); byte[] buffer = new byte[1024 * 10]; int bytesRead; while ((bytesRead = zipStream.read(buffer)) != -1) { ofile.write(buffer, 0, bytesRead); } } // Now try to get the QTI xml file name from the imsmanifest.xml if ("imsmanifest.xml".equals(entry.getName())) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(zipEntryFile); doc.getDocumentElement().normalize(); NodeList nodeLst = doc.getElementsByTagName("resource"); Node fstNode = nodeLst.item(0); NamedNodeMap namedNodeMap = fstNode.getAttributes(); qtiFilename = namedNodeMap.getNamedItem("href").getNodeValue(); } catch (Exception e) { log.error("error parsing imsmanifest.xml"); } } else if (entry.getName() != null && entry.getName().trim().endsWith(".xml")) { xmlFilenames.add(entry.getName().trim()); } zipStream.closeEntry(); entry = zipStream.getNextEntry(); } // If the QTI file doesn't exist in the zip, // we guess the name might be either exportAssessment.xml or the same as the zip file name if (!xmlFilenames.contains(qtiFilename.trim())) { if (xmlFilenames.contains("exportAssessment.xml")) { qtiFilename = "exportAssessment.xml"; } else { qtiFilename = tmpName.substring(0, tmpName.lastIndexOf("_")) + ".xml"; } } } catch (FileNotFoundException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); e.printStackTrace(); } finally { if (ofile != null) { try { ofile.close(); } catch (IOException e) { log.error(e.getMessage()); } } if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { log.error(e.getMessage()); } } if (zipStream != null) { try { zipStream.close(); } catch (IOException e) { log.error(e.getMessage()); } } } return unzipLocation.toString(); }
From source file:org.openremote.controller.service.Deployer.java
/** * Extracts an OpenRemote deployment archive into a given target file directory. * * @param inputStream Input stream for reading the ZIP archive. Note that this method will * attempt to close the stream on exiting. * * @param targetDir URI that points to the root directory where the extracted files should * be placed. Note that the URI must be an absolute file URI. * * @throws ConfigurationException If target file URI cannot be resolved, or if the target * file path does not exist * * @throws IOException If there was an unrecovable I/O error reading or extracting * the ZIP archive. Note that errors on individual files within * the archive may not generate exceptions but be logged as * errors or warnings instead. *//*from ww w. ja va2s . c om*/ private void unzip(InputStream inputStream, URI targetDir) throws ConfigurationException, IOException { if (targetDir == null || targetDir.getPath().equals("") || !targetDir.isAbsolute()) { throw new ConfigurationException( "Target dir must be absolute file: protocol URI, got '" + targetDir + +'.'); } File checkedTargetDir = new File(targetDir); if (!checkedTargetDir.exists()) { throw new ConfigurationException("The path ''{0}'' doesn't exist.", targetDir); } ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream)); ZipEntry zipEntry = null; BufferedOutputStream fileOutputStream = null; try { while ((zipEntry = zipInputStream.getNextEntry()) != null) { if (zipEntry.isDirectory()) { continue; } try { URI extractFileURI = targetDir.resolve(new URI(null, null, zipEntry.getName(), null)); log.debug("Resolved URI to ''{0}''", extractFileURI); File zippedFile = new File(extractFileURI); log.debug("Attempting to extract ''{0}'' to ''{1}''.", zipEntry, zippedFile); try { fileOutputStream = new BufferedOutputStream(new FileOutputStream(zippedFile)); int b; while ((b = zipInputStream.read()) != -1) { fileOutputStream.write(b); } } catch (FileNotFoundException e) { log.error("Could not extract ''{0}'' -- file ''{1}'' could not be created : {2}", e, zipEntry.getName(), zippedFile, e.getMessage()); } catch (IOException e) { log.warn("Zip extraction of ''{0}'' to ''{1}'' failed : {2}", e, zipEntry, zippedFile, e.getMessage()); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); log.debug("Extraction of ''{0}'' to ''{1}'' completed.", zipEntry, zippedFile); } catch (Throwable t) { log.warn("Failed to close file ''{0}'' : {1}", t, zippedFile, t.getMessage()); } } if (zipInputStream != null) { if (zipEntry != null) { try { zipInputStream.closeEntry(); } catch (IOException e) { log.warn("Failed to close ZIP file entry ''{0}'' : {1}", e, zipEntry, e.getMessage()); } } } } } catch (URISyntaxException e) { log.warn("Cannot extract {0} from zip : {1}", e, zipEntry, e.getMessage()); } } } finally { try { if (zipInputStream != null) { zipInputStream.close(); } } catch (IOException e) { log.warn("Failed to close zip file : {0}", e, e.getMessage()); } if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { log.warn("Failed to close file : {0}", e, e.getMessage()); } } } }
From source file:org.opencms.workplace.tools.database.CmsHtmlImport.java
/** * This function reads the zip-file and saved the files and directories in a new * temporary-folder.<p>/*from ww w .jav a2s.c o m*/ * * @return the temporary-folder where the files from the zip-file are saved */ private File unzipStream() { ZipInputStream importZip = null; File folder = null; try { // read the zip file importZip = new ZipInputStream(new FileInputStream(m_httpDir)); // create a temporary-folder, where to unzip the zip file folder = createTempFolder("import_html"); ZipEntry entry = null; byte[] buffer = null; while (true) { try { // get the next entry entry = importZip.getNextEntry(); if (entry == null) { break; } String name = entry.getName(); // make a report for the user m_report.print(Messages.get().container(Messages.RPT_HTML_UNZIP_0), I_CmsReport.FORMAT_NOTE); m_report.print(org.opencms.report.Messages.get() .container(org.opencms.report.Messages.RPT_ARGUMENT_1, name)); m_report.print( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0)); // replace the VFS separator with the separator of the file system name = name.replace('/', File.separatorChar); String path = folder + File.separator + name; if (entry.isDirectory()) { // create a directory File importFile = new File(path); importFile.mkdirs(); } else { // create a file and read the content int size = new Long(entry.getSize()).intValue(); if (size == -1) { buffer = CmsFileUtil.readFully(importZip, false); } else { buffer = CmsFileUtil.readFully(importZip, size, false); } // create a new temporary file File importFile = new File(path); File parent = importFile.getParentFile(); if (parent != null) { parent.mkdirs(); } importFile.createNewFile(); // write the content in the file FileOutputStream fileOutput = new FileOutputStream(importFile.getAbsoluteFile()); fileOutput.write(buffer); fileOutput.close(); } importZip.closeEntry(); m_report.println( org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0), I_CmsReport.FORMAT_OK); } catch (Exception ex) { String name = (entry != null ? entry.getName() : ""); if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.ERR_ZIPFILE_UNZIP_1, name), ex); } m_report.println(Messages.get().container(Messages.ERR_ZIPFILE_UNZIP_1, name), I_CmsReport.FORMAT_ERROR); } entry = null; } } catch (Exception ex) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.ERR_ZIPFILE_READ_1, m_httpDir), ex); } m_report.println(Messages.get().container(Messages.ERR_ZIPFILE_READ_1, m_httpDir), I_CmsReport.FORMAT_ERROR); } finally { closeStream(importZip); } return folder; }
From source file:org.ejbca.ui.web.admin.certprof.CertProfilesBean.java
public void importProfilesFromZip(byte[] filebuffer) throws CertificateProfileExistsException, AuthorizationDeniedException, NumberFormatException, IOException { if (filebuffer.length == 0) { throw new IllegalArgumentException("No input file"); }//ww w . jav a 2s . c om String importedFiles = ""; String ignoredFiles = ""; int nrOfFiles = 0; ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(filebuffer)); ZipEntry ze = zis.getNextEntry(); if (ze == null) { String msg = uploadFile.getName() + " is not a zip file."; log.info(msg); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, null)); return; } do { nrOfFiles++; String filename = ze.getName(); if (log.isDebugEnabled()) { log.debug("Importing file: " + filename); } if (ignoreFile(filename)) { ignoredFiles += filename + ", "; continue; } try { filename = URLDecoder.decode(filename, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 was not a known character encoding", e); } int index1 = filename.indexOf("_"); int index2 = filename.lastIndexOf("-"); int index3 = filename.lastIndexOf(".xml"); String profilename = filename.substring(index1 + 1, index2); int profileid = 0; try { profileid = Integer.parseInt(filename.substring(index2 + 1, index3)); } catch (NumberFormatException e) { if (log.isDebugEnabled()) { log.debug("NumberFormatException parsing certificate profile id: " + e.getMessage()); } ignoredFiles += filename + ", "; continue; } if (log.isDebugEnabled()) { log.debug("Extracted profile name '" + profilename + "' and profile ID '" + profileid + "'"); } if (ignoreProfile(filename, profilename, profileid)) { ignoredFiles += filename + ", "; continue; } if (getEjbcaWebBean().getEjb().getCertificateProfileSession() .getCertificateProfile(profileid) != null) { log.warn("Certificate profile id '" + profileid + "' already exist in database. Adding with a new profile id instead."); profileid = -1; // means we should create a new id when adding the cert profile } byte[] filebytes = new byte[102400]; int i = 0; while ((zis.available() == 1) && (i < filebytes.length)) { filebytes[i++] = (byte) zis.read(); } final CertificateProfile certificateProfile = getCertProfileFromByteArray(profilename, filebytes); if (certificateProfile == null) { String msg = "Faulty XML file '" + filename + "'. Failed to read Certificate Profile."; log.info(msg + " Ignoring file."); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, null)); continue; } certificateProfile.setAvailableCAs(getEjbcaWebBean().getInformationMemory().getAuthorizedCAIds()); getEjbcaWebBean().getEjb().getCertificateProfileSession().addCertificateProfile(getAdmin(), profilename, certificateProfile); getEjbcaWebBean().getInformationMemory().certificateProfilesEdited(); importedFiles += filename + ", "; log.info("Added Certificate profile: " + profilename); } while ((ze = zis.getNextEntry()) != null); zis.closeEntry(); zis.close(); String msg = uploadFile.getName() + " contained " + nrOfFiles + " files. "; log.info(msg); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null)); if (StringUtils.isNotEmpty(importedFiles)) { importedFiles = importedFiles.substring(0, importedFiles.length() - 2); } msg = "Imported Certificate Profiles from files: " + importedFiles; if (log.isDebugEnabled()) { log.debug(msg); } FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null)); if (StringUtils.isNotEmpty(ignoredFiles)) { ignoredFiles = ignoredFiles.substring(0, ignoredFiles.length() - 2); } msg = "Ignored files: " + ignoredFiles; if (log.isDebugEnabled()) { log.debug(msg); } FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null)); }