List of usage examples for java.util.zip ZipFile ZipFile
public ZipFile(File file) throws ZipException, IOException
From source file:com.mirth.connect.server.controllers.DefaultExtensionController.java
@Override public InstallationResult extractExtension(InputStream inputStream) { Throwable cause = null;// w ww . ja va 2 s . c o m Set<MetaData> metaDataSet = new HashSet<MetaData>(); File installTempDir = new File(ExtensionController.getExtensionsPath(), "install_temp"); if (!installTempDir.exists()) { installTempDir.mkdir(); } File tempFile = null; FileOutputStream tempFileOutputStream = null; ZipFile zipFile = null; try { /* * create a new temp file (in the install temp dir) to store the zip file contents */ tempFile = File.createTempFile(ServerUUIDGenerator.getUUID(), ".zip", installTempDir); // write the contents of the multipart fileitem to the temp file try { tempFileOutputStream = new FileOutputStream(tempFile); IOUtils.copy(inputStream, tempFileOutputStream); } finally { IOUtils.closeQuietly(tempFileOutputStream); } // create a new zip file from the temp file zipFile = new ZipFile(tempFile); // get a list of all of the entries in the zip file Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName.endsWith("plugin.xml") || entryName.endsWith("destination.xml") || entryName.endsWith("source.xml")) { // parse the extension metadata xml file MetaData extensionMetaData = serializer .deserialize(IOUtils.toString(zipFile.getInputStream(entry)), MetaData.class); metaDataSet.add(extensionMetaData); if (!extensionLoader.isExtensionCompatible(extensionMetaData)) { if (cause == null) { cause = new VersionMismatchException("Extension \"" + entry.getName() + "\" is not compatible with this version of Mirth Connect."); } } } } if (cause == null) { // reset the entries and extract entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { /* * assume directories are stored parents first then children. * * TODO: this is not robust, just for demonstration purposes. */ File directory = new File(installTempDir, entry.getName()); directory.mkdir(); } else { // otherwise, write the file out to the install temp dir InputStream zipInputStream = zipFile.getInputStream(entry); OutputStream outputStream = new BufferedOutputStream( new FileOutputStream(new File(installTempDir, entry.getName()))); IOUtils.copy(zipInputStream, outputStream); IOUtils.closeQuietly(zipInputStream); IOUtils.closeQuietly(outputStream); } } } } catch (Throwable t) { cause = new ControllerException("Error extracting extension. " + t.toString(), t); } finally { if (zipFile != null) { try { zipFile.close(); } catch (Exception e) { cause = new ControllerException(e); } } // delete the temp file since it is no longer needed FileUtils.deleteQuietly(tempFile); } return new InstallationResult(cause, metaDataSet); }
From source file:au.com.gaiaresources.bdrs.controller.theme.ThemeControllerTest.java
@Test public void testEditThemeFile() throws Exception { ManagedFile mf = new ManagedFile(); mf.setContentType("application/zip"); mf.setFilename("testTheme.zip"); mf.setCredit(""); mf.setLicense(""); mf.setDescription(""); managedFileDAO.save(mf);/* w ww.ja v a2s .co m*/ fileService.createFile(mf.getClass(), mf.getId(), mf.getFilename(), createTestTheme(DEFAULT_CONFIG_VALUES)); Portal portal = getRequestContext().getPortal(); Map<String, ThemeElement> themeElementMap = new HashMap<String, ThemeElement>(); List<ThemeElement> themeElements = new ArrayList<ThemeElement>(DEFAULT_CONFIG_VALUES.size()); for (Map.Entry<String, String> entry : DEFAULT_CONFIG_VALUES.entrySet()) { ThemeElement te = new ThemeElement(); te.setKey(entry.getKey()); te.setDefaultValue(entry.getValue()); te.setCustomValue(entry.getValue()); te.setType(ThemeElementType.TEXT); te = themeDAO.save(te); themeElements.add(te); themeElementMap.put(te.getKey(), te); } Theme theme = new Theme(); theme.setActive(true); theme.setName("Test Theme"); theme.setThemeFileUUID(mf.getUuid()); theme.setCssFiles(new String[] { TEST_CSS_FILE_PATH }); theme.setJsFiles(new String[] { TEST_JS_FILE_PATH }); theme.setPortal(portal); theme.setThemeElements(themeElements); theme = themeDAO.save(theme); ZipUtils.decompressToDir(new ZipFile(fileService.getFile(mf, mf.getFilename()).getFile()), fileService.getTargetDirectory(theme, Theme.THEME_DIR_RAW, true)); login("root", "password", new String[] { Role.ROOT }); request.setMethod("GET"); request.setRequestURI("/bdrs/root/theme/editThemeFile.htm"); request.setParameter("themeId", theme.getId().toString()); request.setParameter("themeFileName", TEST_CSS_FILE_PATH); ModelAndView mv = handle(request, response); ModelAndViewAssert.assertViewName(mv, "themeFileEdit"); Assert.assertEquals(theme.getId(), ((Theme) (mv.getModel().get("editTheme"))).getId()); Assert.assertEquals(request.getParameter("themeFileName"), mv.getModel().get("themeFileName")); Assert.assertEquals(TEST_CSS_RAW_CONTENT.trim(), mv.getModel().get("content").toString().trim()); }
From source file:org.cloudfoundry.client.lib.rest.CloudControllerClientV1.java
private void doUploadApplicationZipFile(String appName, File file, UploadStatusCallback callback) throws IOException { ZipFile zipFile = new ZipFile(file); try {/*from w w w . j a va 2 s . c o m*/ ApplicationArchive archive = new ZipApplicationArchive(zipFile); uploadApplication(appName, archive, callback); } finally { zipFile.close(); } }
From source file:hudson.model.DirectoryBrowserSupportSEC904Test.java
private List<String> getListOfEntriesInDownloadedZip(UnexpectedPage zipPage) throws Exception { List<String> result; File zipfile = null;//w w w. j a v a 2 s. c o m ZipFile readzip = null; try { zipfile = download(zipPage); readzip = new ZipFile(zipfile); result = readzip.stream().map(ZipEntry::getName).collect(Collectors.toList()); } finally { if (readzip != null) { readzip.close(); } if (zipfile != null) { zipfile.delete(); } } return result; }
From source file:com.fluidops.iwb.luxid.LuxidExtractor.java
/** * extracts a zip-file and returns references to the unziped files. If the file passed to this method * is not a zip-file, a reference to the file is returned. * /*from www. j a v a 2s .c o m*/ * @param fileName * @return * @throws Exception */ public static Set<File> extractZip(String fileName) throws Exception { File zipf = new File((new StringBuilder("luxid/")).append(fileName).toString()); Set<File> toBeUploaded = new HashSet<File>(); if (zipf.getName().endsWith(".zip")) { ZipFile zip = new ZipFile(zipf); for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { logger.info((new StringBuilder("Extracting directory: ")).append(entry.getName()).toString()); GenUtil.mkdir(new File(entry.getName())); } else { logger.info((new StringBuilder("Extracting file: ")).append(entry.getName()).toString()); String entryPath = "luxid/" + entry.getName(); FileOutputStream fileOutputStream = null; InputStream zipEntryStream = zip.getInputStream(entry); try { fileOutputStream = new FileOutputStream(entryPath); IOUtils.copy(zipEntryStream, fileOutputStream); } finally { closeQuietly(zipEntryStream); closeQuietly(fileOutputStream); } toBeUploaded.add(new File(entryPath)); } } zip.close(); } else { toBeUploaded.add(zipf); } return toBeUploaded; }
From source file:com.datamelt.nifi.processors.ExecuteRuleEngine.java
@OnScheduled public void onScheduled(final ProcessContext context) throws Exception { // faced problems when having \t as an attribute and could not find a solution // so using allowable values instead and translating them here if (context.getProperty(ATTRIBUTE_FIELD_SEPARATOR).getValue() .equals(FIELD_SEPARATOR_POSSIBLE_VALUE_COMMA)) { separator = SEPARATOR_COMMA;//ww w. j a va2s .c om } else if (context.getProperty(ATTRIBUTE_FIELD_SEPARATOR).getValue() .equals(FIELD_SEPARATOR_POSSIBLE_VALUE_SEMICOLON)) { separator = SEPARATOR_SEMICOLON; } else if (context.getProperty(ATTRIBUTE_FIELD_SEPARATOR).getValue() .equals(FIELD_SEPARATOR_POSSIBLE_VALUE_TAB)) { separator = SEPARATOR_TAB; } // just in case... else { separator = SEPARATOR_COMMA; } // if field names are specified if (context.getProperty(ATTRIBUTE_FIELD_NAMES) != null && !context.getProperty(ATTRIBUTE_FIELD_NAMES).getValue().equals("")) { // create a HeaderRow instance headerFromFieldNames = new HeaderRow(context.getProperty(ATTRIBUTE_FIELD_NAMES).getValue(), FIELD_NAMES_SEPARATOR); getLogger().debug("field names defined - fields found: [" + headerFromFieldNames.getNumberOfFields()); } // get the zip file, containing the business rules File file = new File(context.getProperty(ATTRIBUTE_RULEENGINE_ZIPFILE).getValue()); if (file.exists() && file.isFile()) { // put filename and last modified date into hashmap // so we have a reference which file is currently used with the processor HashMap<String, String> fileMap = new HashMap<String, String>(); fileMap.put(STATE_MANAGER_FILENAME, file.getName()); fileMap.put(STATE_MANAGER_FILENAME_LASTMODIFIED, new Date(file.lastModified()).toString()); // put the hashmap to statemanager context.getStateManager().setState(fileMap, Scope.LOCAL); // get the last modified date of the file Long fileLastModified = file.lastModified(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); String fileLastModifiedDateAsString = sdf.format(new Date(fileLastModified)); // the file should be a zip file containing the business logic ZipFile ruleEngineProjectFile = new ZipFile(file); getLogger().debug( "using project zip file: " + context.getProperty(ATTRIBUTE_RULEENGINE_ZIPFILE).getValue()); try { // create ruleengine instance with the zip file ruleEngine = new BusinessRulesEngine(ruleEngineProjectFile); // output basic info about the ruleengine initialization getLogger().info("initialized business rule engine version: " + BusinessRulesEngine.getVersion() + " using " + context.getProperty(ATTRIBUTE_RULEENGINE_ZIPFILE).getValue() + ", last modified: [" + fileLastModifiedDateAsString + "]"); // display the field seperator used getLogger().debug("field separator to split row into fields: " + context.getProperty(ATTRIBUTE_FIELD_SEPARATOR).getValue()); // we display the number of rulegroups contained in the zip file getLogger().debug("number of rulegroups in project zip file: " + ruleEngine.getNumberOfGroups()); // we do not want to keep the detailed results if they are not needed (no detailed results) if (!context.getProperty(ATTRIBUTE_OUTPUT_DETAILED_RESULTS).getValue().equals("true")) { ruleEngine.setPreserveRuleExcecutionResults(false); } } catch (Exception ex) { // something went wrong // maybe the project zip file (contains xml files) could not be parsed ex.printStackTrace(); } } else { throw new Exception("the ruleengine project zip file was not found or is not a file"); } }
From source file:com.isomorphic.maven.packaging.Distribution.java
/** * Extract the relevant contents from each file in the distribution. Additionally creates ZIP/JAR * files from specified resources (e.g., javadoc). * // w ww . ja va2 s . c o m * @param to The directory to which each file should be extracted. * @throws IOException */ public void unpack(File to) throws IOException { outer: for (File file : files) { String ext = FilenameUtils.getExtension(file.getName()).toUpperCase(); //copy uncompressed files to target, renaming as necessary per 'contents' configuration if (!"ZIP".equals(ext)) { for (Map.Entry<String, AntPathMatcherFilter> filterEntry : content.entrySet()) { AntPathMatcherFilter filter = filterEntry.getValue(); if (filter.accept(file.getName())) { File target = FileUtils.getFile(to, ArchiveUtils.rewritePath(file.getName(), filterEntry.getKey())); FileUtils.copyFile(file, target); LOGGER.debug("Copied file '{}' to file '{}'", file.getName(), target.getAbsolutePath()); continue outer; } } FileUtils.copyFileToDirectory(file, new File(to, "lib")); continue outer; } //otherwise extract contents (again renaming / relocating contents as necessary) ZipFile zip = new ZipFile(file); Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; } for (Map.Entry<String, AntPathMatcherFilter> filterEntry : content.entrySet()) { AntPathMatcherFilter filter = filterEntry.getValue(); if (filter.accept(entry.getName())) { File target = FileUtils.getFile(to, ArchiveUtils.rewritePath(entry.getName(), filterEntry.getKey())); FileUtils.copyInputStreamToFile(zip.getInputStream(entry), target); LOGGER.debug("Copied input stream to file '{}'", target.getAbsolutePath()); } } } zip.close(); } /* * Create any number of assemblies by dropping their resources here. * Each subdirectory will get zipped up and then deleted */ File assembliesDir = new File(to, "assembly"); @SuppressWarnings("unchecked") Collection<File> assemblies = CollectionUtils.arrayToList(assembliesDir.listFiles(new FileFilter() { @Override public boolean accept(File arg0) { return arg0.isDirectory(); } })); for (File assembly : assemblies) { String name = FilenameUtils.getBaseName(assembly.getName()); LOGGER.debug("Copying resources for assembly '{}'", name); ArchiveUtils.zip(assembly, FileUtils.getFile(assembliesDir, name + ".zip")); FileUtils.deleteQuietly(assembly); } LOGGER.debug("Repackaging Javadoc..."); File docLib = new File(to, "doc/lib"); //TODO these paths should probably all be stuck in some constant File client = FileUtils.getFile(to, "doc/api/client"); if (client.exists()) { ArchiveUtils.jar(client, new File(docLib, "smartgwt-javadoc.jar")); } File server = FileUtils.getFile(to, "doc/api/server"); if (server.exists()) { ArchiveUtils.jar(server, new File(docLib, "isomorphic-javadoc.jar")); } }
From source file:com.netspective.sparx.navigate.NavigationControllerServlet.java
/** * Initializes the web resource locators to the following: * - APP_ROOT/resources/sparx (will only exist if user is overriding any defaults) * - APP_ROOT/sparx (will exist in ITE mode when sparx directory is inside application) * - [CLASS_PATH]/Sparx/resources (only useful during development in SDE, not production since it won't be found) * TODO: this method is _not_ thread-safe because two requests could call the method at the same time FIX IT *///from w w w.j a va 2 s . c o m protected UriAddressableFileLocator getResourceLocator(HttpServletRequest request) throws ServletException { if (resourceLocator != null) return resourceLocator; ServletContext servletContext = getServletContext(); try { String[] webAppLocations = TextUtils.getInstance().split(servletOptions.getSparxResourceLocators(), ",", false); List locators = new ArrayList(); for (int i = 0; i < webAppLocations.length; i++) { String webAppRelativePath = webAppLocations[i]; File webAppPhysicalDir = new File(servletContext.getRealPath(webAppRelativePath)); if (webAppPhysicalDir.exists() && webAppPhysicalDir.isDirectory()) locators.add(new UriAddressableInheritableFileResource( request.getContextPath() + webAppRelativePath, webAppPhysicalDir, isCacheComponents())); } // this will only match the SDE development environment FileFind.FileFindResults ffResults = FileFind.findInClasspath("Sparx/resources", FileFind.FINDINPATHFLAG_DEFAULT); if (ffResults.isFileFound() && ffResults.getFoundFile().isDirectory()) locators.add(new UriAddressableInheritableFileResource(request.getContextPath() + "/sparx", ffResults.getFoundFile(), isCacheComponents())); if (log.isDebugEnabled()) { for (int i = 0; i < locators.size(); i++) log.debug("Registered web resources locator " + locators.get(i)); } if (locators.size() == 0) System.err.println("Unable to register any web resource locators (" + TextUtils.getInstance().join(webAppLocations, ", ") + " were not found). Please use the SparxResourcesServlet for serving Sparx resources."); // this will allow serving up files directly from the JAR (assuming the SparxResourcesServlet is available for serving those files) final File jarFile = new File(servletContext.getRealPath("WEB-INF/lib/netspective-sparx.jar")); if (jarFile.exists()) locators.add(new UriAddressableSparxJarResourceLocator(request.getContextPath() + "/sparx", new ZipFile(jarFile))); resourceLocator = new MultipleUriAddressableFileLocators( (UriAddressableFileLocator[]) locators.toArray(new UriAddressableFileLocator[locators.size()]), isCacheComponents()); return resourceLocator; } catch (IOException e) { log.error("error initializing resource locator", e); throw new ServletException(e); } }
From source file:com.seajas.search.contender.service.modifier.ArchiveModifierService.java
/** * Store the not-already-cached files from the given URL and return their locations. * //w w w . j av a 2 s . co m * @param archive * @return Map<File, String> */ private Map<File, String> storeAndDecompressFiles(final Archive archive) { Map<File, String> result = new HashMap<File, String>(); // Create the FTP client FTPClient ftpClient = retrieveFtpClient(archive.getUri()); try { // Retrieve the directory listing List<ArchiveFile> files = retrieveFiles(archive.getUri().getPath(), ftpClient, archive.getExclusionExpression()); Integer archiveNumber = -1, archiveTotal = files.size(); logger.info("Archive with name '" + archive.getName() + "' produced " + archiveTotal + " files"); // An empty archive typically indicates failure if (archiveTotal == 0) logger.warn("The given archive produced no entries - something probably went wrong"); // Handle all archive files for (ArchiveFile archiveFile : files) { archiveNumber++; // Check whether the file already exists within the cache String baseUrl = (StringUtils.hasText(archive.getUri().getScheme()) ? archive.getUri().getScheme() + "://" : "") + archive.getUri().getHost() + (archive.getUri().getPort() != -1 ? ":" + archive.getUri().getPort() : ""); if (!cacheService.isArchived(baseUrl + archiveFile.getFullPath())) { logger.info("Started decompressing archive " + archiveNumber + "/" + archiveTotal + " with name " + archiveFile.getFullPath()); // Write out the archive to disk so we can determine the MIME type File archiveFileFolder = new File(archiveFile .getTranslatedPath(packagesLocation.replace("%1", String.valueOf(archive.getId())))); if (!archiveFileFolder.exists()) archiveFileFolder.mkdirs(); File archiveFileLocation = new File(archiveFileFolder, archiveFile.getFile().getName()); InputStream archiveInputStream = ftpClient.retrieveFileStream(archiveFile.getFullPath()); OutputStream archiveOutputStream = new FileOutputStream(archiveFileLocation); IOUtils.copy(archiveInputStream, archiveOutputStream); archiveInputStream.close(); ftpClient.completePendingCommand(); archiveOutputStream.flush(); archiveOutputStream.close(); // Now unpack the archive and transform each file InputStream compressedArchiveInputStream = new FileInputStream(archiveFileLocation); // Now determine the content type and create a reader in case of structured content MediaType archiveMediaType = autoDetectParser.getDetector() .detect(new BufferedInputStream(compressedArchiveInputStream), new Metadata()); if (!(archiveMediaType.getType().equals("application") && archiveMediaType.getSubtype().equals("zip"))) { logger.warn("Archive file " + archiveFile.getFullPath() + " contains " + archiveMediaType + " data, which is not yet supported"); compressedArchiveInputStream.close(); continue; } else compressedArchiveInputStream.close(); // Create a new ZIP file from the given archive and decompress it ZipFile zipFile = new ZipFile(archiveFileLocation); File resultsLocationFolder = new File(archiveFile .getTranslatedPath(resultsLocation.replace("%1", String.valueOf(archive.getId())))); if (!resultsLocationFolder.exists()) resultsLocationFolder.mkdirs(); File resultsLocation = new File(resultsLocationFolder, stripExtension(archiveFile.getFile().getName())); if (!resultsLocation.exists()) resultsLocation.mkdirs(); logger.info("Started processing archive with name " + archiveFile.getFullPath()); Enumeration<? extends ZipEntry> zipEnumerator = zipFile.entries(); while (zipEnumerator.hasMoreElements()) { ZipEntry entry = zipEnumerator.nextElement(); // Store it locally first File entryLocation = new File(resultsLocation, entry.getName()); try { InputStream entryInputStream = zipFile.getInputStream(entry); OutputStream entryOutputStream = new FileOutputStream(entryLocation); IOUtils.copy(entryInputStream, entryOutputStream); entryInputStream.close(); entryOutputStream.close(); } catch (IOException e) { logger.error("Could not store the compressed archive entry on disk", e); continue; } } zipFile.close(); // Add it to the results result.put(resultsLocation, baseUrl + archiveFile.getFullPath()); logger.info("Finished processing archive with name " + archiveFile.getFullPath()); } else if (logger.isDebugEnabled()) logger.debug("Skipping previously processed archive with name " + archiveFile.getFullPath()); } } catch (IOException e) { logger.error("Could not close input stream during archive processing", e); } finally { try { if (ftpClient.isConnected()) ftpClient.disconnect(); } catch (IOException e) { logger.error("Could not disconnect the FTP client", e); } } return result; }
From source file:com.adobe.phonegap.contentsync.Sync.java
private boolean isZipFile(File targetFile) { boolean success = true; try {//from www .j a v a2s .c om ZipFile zip = new ZipFile(targetFile); Log.d(LOG_TAG, "seems like a zip file"); } catch (IOException e) { Log.d(LOG_TAG, "not a zip file"); success = false; } return success; }