List of usage examples for java.util.zip ZipFile ZipFile
public ZipFile(File file) throws ZipException, IOException
From source file:eu.diversify.disco.experiments.testing.Tester.java
private void unzipDistribution(String archiveName) throws IOException { String fileName = escape(archiveName); ZipFile zipFile = new ZipFile(fileName); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (!entry.isDirectory()) { File entryDestination = new File("target/", entry.getName()); entryDestination.getParentFile().mkdirs(); InputStream in = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(entryDestination); IOUtils.copy(in, out);/* ww w . ja v a 2s . c o m*/ IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } }
From source file:org.openmrs.module.owa.web.controller.OwaRestController.java
@RequestMapping(value = "/rest/owa/addapp", method = RequestMethod.POST) @ResponseBody//from w w w. j a va 2 s . com public List<App> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException { List<App> appList = new ArrayList<>(); if (Context.hasPrivilege("Manage OWA")) { String message; HttpSession session = request.getSession(); if (!file.isEmpty()) { String fileName = file.getOriginalFilename(); File uploadedFile = new File(file.getOriginalFilename()); file.transferTo(uploadedFile); try (ZipFile zip = new ZipFile(uploadedFile)) { if (zip.size() == 0) { message = messageSourceService.getMessage("owa.blank_zip"); log.warn("Zip file is empty"); session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message); response.sendError(500, message); } else { ZipEntry entry = zip.getEntry("manifest.webapp"); if (entry == null) { message = messageSourceService.getMessage("owa.manifest_not_found"); log.warn("Manifest file could not be found in app"); uploadedFile.delete(); session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message); response.sendError(500, message); } else { String contextPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); appManager.installApp(uploadedFile, fileName, contextPath); message = messageSourceService.getMessage("owa.app_installed"); session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, message); } } } catch (Exception e) { message = messageSourceService.getMessage("owa.not_a_zip"); log.warn("App is not a zip archive"); uploadedFile.delete(); session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message); response.sendError(500, message); } } appManager.reloadApps(); appList = appManager.getApps(); } return appList; }
From source file:com.vvote.verifierlibrary.utils.io.IOUtils.java
/** * Utility class to extract a zip file/*from w ww .j a va 2 s . c o m*/ * * @param filepath * @return the location of the extract zip file * @throws IOException */ public static String extractZipFile(String filepath) throws IOException { if (IOUtils.checkExtension(FileType.ZIP, filepath)) { try (ZipFile zipFile = new ZipFile(filepath)) { // files in zip file Enumeration<? extends ZipEntry> entries = zipFile.entries(); // current zip directory File zipDirectory = new File(filepath); // output directory - doesn't include the .zip extension File outputDirectory = new File( IOUtils.join(zipDirectory.getParent(), IOUtils.getFileNameWithoutExtension(filepath))); // make directory if not exists if (!outputDirectory.exists()) { outputDirectory.mkdir(); } InputStream is = null; FileOutputStream fos = null; byte[] bytes = null; int length = 0; // loop over each file in zip file while (entries.hasMoreElements()) { ZipEntry zipEntry = entries.nextElement(); String entryName = zipEntry.getName(); // current output file File file = new File(IOUtils.join(outputDirectory.getPath(), entryName)); File currentOutputFile = new File(getFilePathWithoutExtension(file.getPath())); if (currentOutputFile.exists()) { if (getFileNameWithoutExtension(entryName) .contains(CommitFileNames.WBB_UPLOAD.getFileName())) { try (ZipFile currentZipFile = new ZipFile(file)) { Enumeration<? extends ZipEntry> currentZipEntries = currentZipFile.entries(); long currentUncompressedZipSize = currentZipEntries.nextElement().getSize(); long currentDirectorySize = FileUtils.sizeOfDirectory(currentOutputFile); if (currentUncompressedZipSize == currentDirectorySize) { continue; } } } } // if directory make it if (entryName.endsWith("/")) { file.mkdirs(); } else { // write current input zip file to output location is = zipFile.getInputStream(zipEntry); fos = new FileOutputStream(file); bytes = new byte[1024]; while ((length = is.read(bytes)) >= 0) { fos.write(bytes, 0, length); } is.close(); fos.close(); } } return outputDirectory.getPath(); } } logger.error("Provided filepath: {} does not point to a valid zip file", filepath); throw new IOException("Provided filepath: " + filepath + " does not point to a valid zip file"); }
From source file:com.eviware.soapui.integration.exporter.ProjectExporter.java
public static List<String> getZipContents(String archive) { List<String> contents = new ArrayList<String>(); try {//from ww w . ja va2 s . c o m ZipFile zipFile = new ZipFile(archive); for (Enumeration<? extends ZipEntry> em1 = zipFile.entries(); em1.hasMoreElements();) { contents.add(em1.nextElement().toString()); } } catch (ZipException ze) { SoapUI.logError(ze); } catch (IOException e) { SoapUI.logError(e); } return contents; }
From source file:com.netflix.nicobar.core.utils.ClassPathUtils.java
/** * Get all of the directory paths in a zip/jar file * @param pathToJarFile location of the jarfile. can also be a zipfile * @return set of directory paths relative to the root of the jar *///w ww . j a va 2 s . c om public static Set<Path> getDirectoriesFromJar(Path pathToJarFile) throws IOException { Set<Path> result = new HashSet<Path>(); ZipFile jarfile = new ZipFile(pathToJarFile.toFile()); try { final Enumeration<? extends ZipEntry> entries = jarfile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { result.add(Paths.get(entry.getName())); } } jarfile.close(); } finally { IOUtils.closeQuietly(jarfile); } return result; }
From source file:com.google.gwt.dev.resource.impl.ZipFileClassPathEntry.java
private ZipFileClassPathEntry(File zipFile) throws IOException { assert zipFile.isAbsolute(); this.lastModified = zipFile.lastModified(); this.zipFile = new ZipFile(zipFile); this.location = zipFile.toURI().toString(); }
From source file:org.geowe.server.upload.FileUploadZipServlet.java
private ZipFile createZipFile(FileItemStream item) { ZipFile zipFile = null;//w ww. j a v a 2s. c o m try { File f = new File("zipFile"); InputStream inputStream = item.openStream(); OutputStream outputStream = new FileOutputStream(f); int len; byte[] buffer = new byte[1000000]; while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) { outputStream.write(buffer, 0, len); } outputStream.close(); inputStream.close(); zipFile = new ZipFile(f); } catch (Exception e) { LOG.error(e.getMessage()); } return zipFile; }
From source file:azkaban.execapp.FlowPreparer.java
/** * Prepare the project directory.//from w w w . jav a2 s . c om * * @param pv ProjectVersion object * @throws ProjectManagerException * @throws IOException */ @VisibleForTesting void setupProject(final ProjectVersion pv) throws ProjectManagerException, IOException { final int projectId = pv.getProjectId(); final int version = pv.getVersion(); final String projectDir = String.valueOf(projectId) + "." + String.valueOf(version); if (pv.getInstalledDir() == null) { pv.setInstalledDir(new File(projectsDir, projectDir)); } // If directory exists. Assume its prepared and skip. if (pv.getInstalledDir().exists()) { log.info("Project already cached. Skipping download. " + pv); return; } log.info("Preparing Project: " + pv); File tempDir = new File(projectsDir, "_temp." + projectDir + "." + System.currentTimeMillis()); // TODO Why mkdirs? This path should be already set up. tempDir.mkdirs(); ProjectFileHandler projectFileHandler = null; try { projectFileHandler = requireNonNull(projectLoader.getUploadedFile(projectId, version)); checkState("zip".equals(projectFileHandler.getFileType())); log.info("Downloading zip file."); final File zipFile = requireNonNull(projectFileHandler.getLocalFile()); final ZipFile zip = new ZipFile(zipFile); Utils.unzip(zip, tempDir); Files.move(tempDir.toPath(), pv.getInstalledDir().toPath(), StandardCopyOption.ATOMIC_MOVE); log.warn(String.format("Project Preparation complete. [%s]", pv)); } finally { if (projectFileHandler != null) { projectFileHandler.deleteLocalFile(); } // Clean up: Remove tempDir if exists FileUtils.deleteDirectory(tempDir); } }
From source file:de.egore911.versioning.deployer.performer.PerformExtraction.java
private static boolean extract(String uri, List<ExtractionPair> extractions) { URL url;/* w ww.j ava 2s . c o m*/ try { url = new URL(uri); } catch (MalformedURLException e) { LOG.error("Invalid URI: {}", e.getMessage(), e); return false; } try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int response = connection.getResponseCode(); int lastSlash = uri.lastIndexOf('/'); if (lastSlash < 0) { LOG.error("Invalid URI: {}", uri); return false; } int lastDot = uri.lastIndexOf('.'); if (lastDot < 0) { LOG.error("Invalid URI: {}", uri); return false; } File downloadFile = File.createTempFile(uri.substring(lastSlash + 1), uri.substring(lastDot + 1)); downloadFile.deleteOnExit(); if (response == HttpURLConnection.HTTP_OK) { try (InputStream in = connection.getInputStream(); FileOutputStream out = new FileOutputStream(downloadFile)) { IOUtils.copy(in, out); } LOG.debug("Downloaded {} to {}", url, downloadFile.getAbsolutePath()); Set<ExtractionPair> usedExtractions = new HashSet<>(); // Perform extractions try (ZipFile zipFile = new ZipFile(downloadFile)) { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); // Only extract files if (entry.isDirectory()) { continue; } for (ExtractionPair extraction : extractions) { String sourcePattern = extraction.source; if (FilenameUtils.wildcardMatch(entry.getName(), sourcePattern)) { usedExtractions.add(extraction); LOG.debug("Found matching file {} for source pattern {}", entry.getName(), sourcePattern); String filename = getSourcePatternMatch(entry.getName(), sourcePattern); // Workaround: If there is no matcher in 'sourcePattern' it will return the // complete path. Strip it down to the filename if (filename.equals(entry.getName())) { int lastIndexOf = filename.lastIndexOf('/'); if (lastIndexOf >= 0) { filename = filename.substring(lastIndexOf + 1); } } String name = UrlUtil.concatenateUrlWithSlashes(extraction.destination, filename); FileUtils.forceMkdir(new File(name).getParentFile()); try (InputStream in = zipFile.getInputStream(entry); FileOutputStream out = new FileOutputStream(name)) { IOUtils.copy(in, out); } LOG.debug("Extracted {} to {} from {}", entry.getName(), name, uri); } } } } for (ExtractionPair extraction : extractions) { if (!usedExtractions.contains(extraction)) { LOG.debug("Extraction {} to {} not used on {}", extraction.source, extraction.destination, uri); } } return true; } else { LOG.error("Could not download file: {}", uri); return false; } } catch (IOException e) { LOG.error("Could not download file: {}", e.getMessage(), e); return false; } }
From source file:de.tudarmstadt.ukp.clarin.webanno.project.page.ImportUtil.java
/** * Check if the zip file is webanno compatible * /* w ww.java2 s . c o m*/ * @param aZipFile the file. * @return if it is valid. * @throws ZipException if the ZIP file is corrupt. * @throws IOException if an I/O error occurs. * */ @SuppressWarnings({ "rawtypes" }) public static boolean isZipValidWebanno(File aZipFile) throws ZipException, IOException { boolean isZipValidWebanno = false; ZipFile zip = new ZipFile(aZipFile); for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) { ZipEntry entry = (ZipEntry) zipEnumerate.nextElement(); if (entry.toString().replace("/", "").startsWith(ImportUtil.EXPORTED_PROJECT) && entry.toString().replace("/", "").endsWith(".json")) { isZipValidWebanno = true; break; } } return isZipValidWebanno; }