List of usage examples for java.util.zip ZipInputStream close
public void close() throws IOException
From source file:edu.isi.wings.portal.classes.StorageHandler.java
public static String unzipFile(File f, String todirname, String toDirectory) { File todir = new File(toDirectory); if (!todir.exists()) todir.mkdirs();//from ww w. j a v a 2 s. co m try { // Check if the zip file contains only one directory ZipFile zfile = new ZipFile(f); String topDir = null; boolean isOneDir = true; for (Enumeration<? extends ZipEntry> e = zfile.entries(); e.hasMoreElements();) { ZipEntry ze = e.nextElement(); String name = ze.getName().replaceAll("/.+$", ""); name = name.replaceAll("/$", ""); // OSX Zips carry an extra __MACOSX directory. Ignore it if (name.equals("__MACOSX")) continue; if (topDir == null) topDir = name; else if (!topDir.equals(name)) { isOneDir = false; break; } } zfile.close(); // Delete existing directory (if any) FileUtils.deleteDirectory(new File(toDirectory + File.separator + todirname)); // Unzip file(s) into toDirectory/todirname ZipInputStream zis = new ZipInputStream(new FileInputStream(f)); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String fileName = ze.getName(); // OSX Zips carry an extra __MACOSX directory. Ignore it if (fileName.startsWith("__MACOSX")) { ze = zis.getNextEntry(); continue; } // Get relative file path translated to 'todirname' if (isOneDir) fileName = fileName.replaceFirst(topDir, todirname); else fileName = todirname + File.separator + fileName; // Create directories File newFile = new File(toDirectory + File.separator + fileName); if (ze.isDirectory()) newFile.mkdirs(); else newFile.getParentFile().mkdirs(); try { // Copy file FileOutputStream fos = new FileOutputStream(newFile); IOUtils.copy(zis, fos); fos.close(); String mime = new Tika().detect(newFile); if (mime.equals("application/x-sh") || mime.startsWith("text/")) FileUtils.writeLines(newFile, FileUtils.readLines(newFile)); // Set all files as executable for now newFile.setExecutable(true); } catch (FileNotFoundException fe) { // Silently ignore //fe.printStackTrace(); } ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); return toDirectory + File.separator + todirname; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.joliciel.csvLearner.CSVEventListReader.java
/** * Scan a feature directory and all of its sub-directories, and add the * contents of the feature files to the event map. * /*w w w. ja va 2 s .com*/ * @param featureDir * @throws IOException */ void scanFeatureDir(File featureDir, boolean grouped) throws IOException { LOG.debug("Scanning feature directory " + featureDir.getPath()); File[] files = featureDir.listFiles(); if (files == null) { LOG.debug("Not a directory!"); return; } for (File file : files) { if (file.isDirectory()) { // recursively scan this feature sub-directory this.scanFeatureDir(file, grouped); } else { String fileName = file.getName(); LOG.debug("Scanning file " + fileName); Map<String, GenericEvent> currentEventMap = eventMap; if (eventFileMap != null) { currentEventMap = new TreeMap<String, GenericEvent>(); // copy the results to the event map for (GenericEvent event : eventMap.values()) { GenericEvent eventClone = new GenericEvent(event.getIdentifier()); eventClone.setTest(event.isTest()); eventClone.setOutcome(event.getOutcome()); currentEventMap.put(event.getIdentifier(), eventClone); } eventFileMap.put(fileName, currentEventMap); } InputStream inputStream = null; try { if (fileName.endsWith(".dsc_limits.csv") || fileName.endsWith(".nrm_limits.csv")) { LOG.trace("Ignoring limits file: " + fileName); } else if (fileName.endsWith(".csv")) { inputStream = new FileInputStream(file); this.scanCSVFile(inputStream, true, grouped, fileName, currentEventMap); } else if (fileName.endsWith(".zip")) { inputStream = new FileInputStream(file); ZipInputStream zis = new ZipInputStream(inputStream); ZipEntry zipEntry; while ((zipEntry = zis.getNextEntry()) != null) { LOG.debug("Scanning zip entry " + zipEntry.getName()); this.scanCSVFile(zis, false, grouped, fileName, currentEventMap); zis.closeEntry(); } zis.close(); } else { throw new RuntimeException("Bad file extension in feature directory: " + file.getName()); } } finally { if (inputStream != null) inputStream.close(); } } // file or directory? } // next file }
From source file:com.nkapps.billing.services.BankStatementServiceImpl.java
@Override public File extractedFile(File file) throws Exception { File extractedFile = null;/*from w ww.ja v a 2s . c o m*/ byte[] buffer = new byte[1024]; ZipInputStream zis = new ZipInputStream(new FileInputStream(file)); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String extFileName = ze.getName(); extractedFile = new File(getUploadDir() + File.separator + extFileName); if (!extractedFile.exists()) { extractedFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(extractedFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); return extractedFile; }
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/* w w w . j av a 2 s.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: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 w w. j a v a 2 s . c om*/ 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:de.knowwe.jspwiki.JSPWikiConnector.java
private List<WikiAttachment> getZipEntryAttachments(Attachment attachment) throws IOException, ProviderException { if (!attachment.getFileName().endsWith(".zip")) return Collections.emptyList(); List<WikiAttachment> zipEntryAttachments = zipAttachmentCache.get(attachment.getName()); AttachmentManager attachmentManager = this.engine.getAttachmentManager(); if (attachment.getVersion() == WikiProvider.LATEST_VERSION) { // little hack for JSPWiki 2.8.4 not always providing a correct // version number and we need it here. WikiAttachmentProvider currentProvider = attachmentManager.getCurrentProvider(); // there only are two possible providers, the // BasicAttachmentProvider and the CachingAttachmentProvider // the BasicAttachmentProvider has a correct version number if (currentProvider instanceof CachingAttachmentProvider) { currentProvider = ((CachingAttachmentProvider) currentProvider).getRealProvider(); }/*w w w . ja v a 2 s .c om*/ Attachment attachmentInfo = currentProvider.getAttachmentInfo( new WikiPage(engine, attachment.getParentName()), attachment.getFileName(), WikiProvider.LATEST_VERSION); // this attachmentInfo will have the correct version number, so // we set it for the actual attachment attachment.setVersion(attachmentInfo.getVersion()); } if (zipEntryAttachments != null) { // we check if the attachments are outdated int cachedVersion = zipEntryAttachments.get(0).getVersion(); int currentVersion = attachment.getVersion(); if (cachedVersion != currentVersion) { zipEntryAttachments = null; } } if (zipEntryAttachments == null) { zipEntryAttachments = new ArrayList<>(); InputStream attachmentStream = attachmentManager.getAttachmentStream(attachment); ZipInputStream zipStream = new ZipInputStream(attachmentStream); for (ZipEntry e; (e = zipStream.getNextEntry()) != null;) { zipEntryAttachments.add(new JSPWikiZipAttachment(e.getName(), attachment, attachmentManager)); } zipStream.close(); if (!zipEntryAttachments.isEmpty()) { zipAttachmentCache.put(attachment.getName(), zipEntryAttachments); } } return zipEntryAttachments; }
From source file:com.seer.datacruncher.spring.ValidateFilePopupController.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { String idSchema = request.getParameter("idSchema"); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multipartFile = multipartRequest.getFile("file"); String resMsg = ""; if (multipartFile.getOriginalFilename().endsWith(FileExtensionType.ZIP.getAbbreviation())) { // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one ZipInputStream inStream = null; try {/*from w w w . j av a 2s . c o m*/ inStream = new ZipInputStream(multipartFile.getInputStream()); ZipEntry entry; while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) { if (!entry.isDirectory()) { DatastreamsInput datastreamsInput = new DatastreamsInput(); datastreamsInput.setUploadedFileName(entry.getName()); byte[] byteInput = IOUtils.toByteArray(inStream); resMsg += datastreamsInput.datastreamsInput(new String(byteInput), Long.parseLong(idSchema), byteInput); } inStream.closeEntry(); } } catch (IOException ex) { resMsg = "Error occured during fetch records from ZIP file."; } finally { if (inStream != null) inStream.close(); } } else { // Case 1: When user upload a single file. In this cae just validate a single stream String datastream = new String(multipartFile.getBytes()); DatastreamsInput datastreamsInput = new DatastreamsInput(); datastreamsInput.setUploadedFileName(multipartFile.getOriginalFilename()); resMsg = datastreamsInput.datastreamsInput(datastream, Long.parseLong(idSchema), multipartFile.getBytes()); } String msg = resMsg.replaceAll("'", "\"").replaceAll("\\n", " "); msg = msg.trim(); response.setContentType("text/html"); ServletOutputStream out = null; out = response.getOutputStream(); out.write(("{success: " + true + " , message:'" + msg + "', " + "}").getBytes()); out.flush(); out.close(); return null; }
From source file:org.jahia.utils.maven.plugin.DeployMojo.java
private void hotSwap(File deployedJar) { int colonIndex = address.indexOf(':'); String connectorName = address.substring(0, colonIndex); if (connectorName.equals("socket")) connectorName = "com.sun.jdi.SocketAttach"; else if (connectorName.equals("shmem")) connectorName = "com.sun.jdi.SharedMemoryAttach"; String argumentsString = address.substring(colonIndex + 1); AttachingConnector connector = (AttachingConnector) findConnector(connectorName); Map<String, Argument> arguments = connector.defaultArguments(); StringTokenizer st = new StringTokenizer(argumentsString, ","); while (st.hasMoreTokens()) { String pair = st.nextToken(); int index = pair.indexOf('='); String name = pair.substring(0, index); String value = pair.substring(index + 1); Connector.Argument argument = (Connector.Argument) arguments.get(name); if (argument != null) { argument.setValue(value);/* ww w.ja va 2s.co m*/ } } Map<String, Long> dates = new HashMap<String, Long>(); try { ZipInputStream z = new ZipInputStream(new FileInputStream(deployedJar)); ZipEntry entry; while ((entry = z.getNextEntry()) != null) { dates.put(entry.getName(), entry.getTime()); } z.close(); } catch (IOException e) { e.printStackTrace(); } VirtualMachine vm = null; try { vm = connector.attach(arguments); getLog().info("Connected to " + vm.name() + " " + vm.version()); Map<String, File> files = new HashMap<String, File>(); parse(new File(output, "classes"), dates, "", files); getLog().debug("Classes : " + files.keySet()); if (!files.isEmpty()) { reload(vm, files); } } catch (ConnectException e) { getLog().warn("Cannot hotswap classes : " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); } catch (IllegalConnectorArgumentsException e) { e.printStackTrace(); } finally { if (vm != null) { vm.dispose(); } } }
From source file:org.jahia.test.utils.TestHelper.java
public static JahiaSite createSite(String name, String serverName, String templateSet, String prepackedZIPFile, String siteZIPName, String[] modulesToDeploy) throws Exception { modulesToDeploy = (modulesToDeploy == null) ? new String[0] : modulesToDeploy; JahiaUser admin = JahiaAdminUser.getAdminUser(null); JahiaSitesService service = ServicesRegistry.getInstance().getJahiaSitesService(); JahiaSite site = service.getSiteByKey(name); if (site != null) { service.removeSite(site);//from www. ja va2 s . co m } File siteZIPFile = null; File sharedZIPFile = null; try { if (!StringUtils.isEmpty(prepackedZIPFile)) { ZipInputStream zis = null; OutputStream os = null; try { zis = new ZipInputStream(new FileInputStream(new File(prepackedZIPFile))); ZipEntry z = null; while ((z = zis.getNextEntry()) != null) { if (siteZIPName.equalsIgnoreCase(z.getName()) || "users.zip".equals(z.getName())) { File zipFile = File.createTempFile("import", ".zip"); os = new FileOutputStream(zipFile); byte[] buf = new byte[4096]; int r; while ((r = zis.read(buf)) > 0) { os.write(buf, 0, r); } os.close(); if ("users.zip".equals(z.getName())) { sharedZIPFile = zipFile; } else { siteZIPFile = zipFile; } } } } catch (IOException e) { logger.error(e.getMessage(), e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } if (zis != null) { try { zis.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } } } if (sharedZIPFile != null) { try { ImportExportBaseService.getInstance().importSiteZip( sharedZIPFile != null ? new FileSystemResource(sharedZIPFile) : null, null, null); } catch (RepositoryException e) { logger.warn("shared.zip could not be imported", e); } } if (templateSet != null) { site = service.addSite(admin, name, serverName, name, name, SettingsBean.getInstance().getDefaultLocale(), templateSet, modulesToDeploy, siteZIPFile == null ? "noImport" : "fileImport", siteZIPFile != null ? new FileSystemResource(siteZIPFile) : null, null, false, false, null); } else { site = addSiteWithoutTemplates(admin, name, serverName, SettingsBean.getInstance().getDefaultLocale()); } site = service.getSiteByKey(name); } finally { if (sharedZIPFile != null) { sharedZIPFile.delete(); } if (siteZIPFile != null) { siteZIPFile.delete(); } } return site; }
From source file:org.exoplatform.services.cms.impl.Utils.java
/** * get data from the version history file * * @param importHistorySourceStream//from w w w . j a va 2 s . c o m * @return * @throws Exception */ public static Map<String, String> getMapImportHistory(InputStream importHistorySourceStream) throws Exception { ZipInputStream zipInputStream = new ZipInputStream(importHistorySourceStream); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] data = new byte[1024]; ZipEntry entry = zipInputStream.getNextEntry(); Map<String, String> mapHistoryValue = new HashMap<String, String>(); while (entry != null) { int available = -1; if (entry.getName().equals(MAPPING_FILE)) { while ((available = zipInputStream.read(data, 0, 1024)) > -1) { out.write(data, 0, available); } InputStream inputStream = new ByteArrayInputStream(out.toByteArray()); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String strLine; // Read File Line By Line while ((strLine = br.readLine()) != null) { // Put the history information into list if (strLine.indexOf("=") > -1) { mapHistoryValue.put(strLine.split("=")[0], strLine.split("=")[1]); } } // Close the input stream inputStream.close(); zipInputStream.closeEntry(); break; } entry = zipInputStream.getNextEntry(); } out.close(); zipInputStream.close(); return mapHistoryValue; }