List of usage examples for java.util.zip ZipFile close
public void close() throws IOException
From source file:dalma.container.ClassLoaderImpl.java
/** * Add a file to the path. This classloader reads the manifest, if * available, and adds any additional class path jars specified in the * manifest.// w ww .ja v a 2 s . co m * * @param pathComponent the file which is to be added to the path for * this class loader * * @throws IOException if data needed from the file cannot be read. */ public void addPathFile(File pathComponent) throws IOException { pathComponents.addElement(pathComponent); if (pathComponent.isDirectory()) { return; } String absPathPlusTimeAndLength = pathComponent.getAbsolutePath() + pathComponent.lastModified() + "-" + pathComponent.length(); String classpath = pathMap.get(absPathPlusTimeAndLength); if (classpath == null) { ZipFile jarFile = null; InputStream manifestStream = null; try { jarFile = new ZipFile(pathComponent); manifestStream = jarFile.getInputStream(new ZipEntry("META-INF/MANIFEST.MF")); if (manifestStream == null) { return; } Manifest manifest = new Manifest(manifestStream); classpath = manifest.getMainAttributes().getValue("Class-Path"); } finally { if (manifestStream != null) { manifestStream.close(); } if (jarFile != null) { jarFile.close(); } } if (classpath == null) { classpath = ""; } pathMap.put(absPathPlusTimeAndLength, classpath); } if (!"".equals(classpath)) { URL baseURL = pathComponent.toURL(); StringTokenizer st = new StringTokenizer(classpath); while (st.hasMoreTokens()) { String classpathElement = st.nextToken(); URL libraryURL = new URL(baseURL, classpathElement); if (!libraryURL.getProtocol().equals("file")) { logger.fine("Skipping jar library " + classpathElement + " since only relative URLs are supported by this" + " loader"); continue; } File libraryFile = new File(libraryURL.getFile()); if (libraryFile.exists() && !isInPath(libraryFile)) { addPathFile(libraryFile); } } } }
From source file:org.openmrs.module.moduledistro.api.impl.ModuleDistroServiceImpl.java
/** * @see org.openmrs.module.moduledistro.api.ModuleDistroService#uploadDistro(java.io.File) *///from ww w . ja v a 2s . c om @Override public List<String> uploadDistro(File distributionZip, ServletContext servletContext) { // get all omods included in the zip file, by their original filename List<UploadedModule> includedOmods = new ArrayList<ModuleDistroServiceImpl.UploadedModule>(); ZipFile zf = null; try { zf = new ZipFile(distributionZip); for (@SuppressWarnings("rawtypes") Enumeration e = zf.entries(); e.hasMoreElements();) { ZipEntry entry = (ZipEntry) e.nextElement(); if (entry.getName().endsWith("/")) continue; if (!entry.getName().endsWith(".omod")) { throw new RuntimeException("This ZIP is only allowed to contain omod files, but this contains: " + entry.getName()); } File file = File.createTempFile("distributionOmod", ".omod"); file.deleteOnExit(); FileUtils.copyInputStreamToFile(zf.getInputStream(entry), file); String originalName = simpleFilename(entry.getName()); includedOmods.add(new UploadedModule(originalName, file)); } } catch (IOException ex) { // TODO something prettier throw new RuntimeException("Error reading zip file", ex); } finally { try { zf.close(); } catch (Exception ex) { } } // determine which omods we want to install for (UploadedModule candidate : includedOmods) { try { log.debug("about to inspect " + candidate); populateFields(candidate); log.debug("inspected " + candidate); } catch (IOException ex) { throw new RuntimeException("Error inspecting " + candidate.getOriginalFilename(), ex); } } // apply those actions (and log them) List<String> log = new ArrayList<String>(); List<ModuleAction> actions = determineActions(includedOmods); while (!actions.isEmpty()) { ModuleAction action = removeNextAction(actions); if (Action.SKIP.equals(action.getAction())) { UploadedModule info = (UploadedModule) action.getTarget(); log.add(info.getOriginalFilename() + ": skipped because " + info.getSkipReason()); } else if (Action.STOP.equals(action.getAction())) { Module module = (Module) action.getTarget(); module.clearStartupError(); List<Module> dependentModulesStopped = ModuleFactory.stopModule(module, false, true); for (Module depMod : dependentModulesStopped) { if (servletContext != null) WebModuleUtil.stopModule(depMod, servletContext); log.add("Stopped depended module " + depMod.getModuleId() + " version " + depMod.getVersion()); // if any modules were stopped that we're not already planning to start, we need to start them if (!scheduledToStart(actions, depMod.getModuleId())) { actions.add(new ModuleAction(Action.START, depMod)); } } if (servletContext != null) WebModuleUtil.stopModule(module, servletContext); log.add("Stopped " + module.getModuleId() + " version " + module.getVersion()); } else if (Action.REMOVE.equals(action.getAction())) { Module module = (Module) action.getTarget(); ModuleFactory.unloadModule(module); log.add("Removed " + module.getModuleId() + " version " + module.getVersion()); } else if (Action.INSTALL.equals(action.getAction())) { UploadedModule info = (UploadedModule) action.getTarget(); File inserted; try { inserted = ModuleUtil.insertModuleFile(new FileInputStream(info.getData()), info.getOriginalFilename()); } catch (FileNotFoundException ex) { throw new RuntimeException("Unexpected FileNotFoundException", ex); } Module loaded = ModuleFactory.loadModule(inserted); log.add("Installed " + info.getModuleId() + " version " + info.getModuleVersion()); // if we installed a module, we also need to start it later if (!scheduledToStart(actions, loaded.getModuleId())) { actions.add(new ModuleAction(Action.START, loaded)); } } else if (Action.START.equals(action.getAction())) { Module module = (Module) action.getTarget(); // TODO document a core bug, that the next line does not throw the promised ModuleException ModuleFactory.startModule(module); if (module.getStartupErrorMessage() != null) throw new RuntimeException( "Failed to start module " + module + " because of: " + module.getStartupErrorMessage()); if (servletContext != null) WebModuleUtil.startModule(module, servletContext, false); // TODO figure out how to delay context refresh log.add("Started " + module.getModuleId() + " version " + module.getVersion()); } else { throw new RuntimeException( "Programming Error: don't know how to handle action: " + action.getAction()); } } return log; }
From source file:brut.androlib.res.AndrolibResources.java
public void installFramework(File frameFile, String tag) throws AndrolibException { InputStream in = null;//from ww w . j av a2 s . c om ZipOutputStream out = null; try { ZipFile zip = new ZipFile(frameFile); ZipEntry entry = zip.getEntry("resources.arsc"); if (entry == null) { throw new AndrolibException("Can't find resources.arsc file"); } in = zip.getInputStream(entry); byte[] data = IOUtils.toByteArray(in); ARSCData arsc = ARSCDecoder.decode(new ByteArrayInputStream(data), true, true); publicizeResources(data, arsc.getFlagsOffsets()); File outFile = new File(getFrameworkDir(), String.valueOf(arsc.getOnePackage().getId()) + (tag == null ? "" : '-' + tag) + ".apk"); out = new ZipOutputStream(new FileOutputStream(outFile)); out.setMethod(ZipOutputStream.STORED); CRC32 crc = new CRC32(); crc.update(data); entry = new ZipEntry("resources.arsc"); entry.setSize(data.length); entry.setCrc(crc.getValue()); out.putNextEntry(entry); out.write(data); zip.close(); LOGGER.info("Framework installed to: " + outFile); } catch (IOException ex) { throw new AndrolibException(ex); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
From source file:org.adempiere.webui.install.WTranslationDialog.java
private void unZipAndProcess(InputStream istream) throws AdempiereException { FileOutputStream ostream = null; File file = null;//from w ww. j a va 2s. c o m try { file = File.createTempFile("trlImport", ".zip"); ostream = new FileOutputStream(file); byte[] buffer = new byte[1024]; int read; while ((read = istream.read(buffer)) != -1) { ostream.write(buffer, 0, read); } } catch (Throwable e) { throw new AdempiereException("Copy zip failed", e); } finally { if (ostream != null) { try { ostream.close(); } catch (Exception e2) { } } } // create temp folder File tempfolder; try { tempfolder = File.createTempFile(m_AD_Language.getValue(), ".trl"); tempfolder.delete(); tempfolder.mkdir(); } catch (IOException e1) { throw new AdempiereException("Problem creating temp folder", e1); } String suffix = "_" + m_AD_Language.getValue() + ".xml"; ZipFile zipFile = null; boolean validfile = false; try { zipFile = new ZipFile(file); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { // ignore folders log.warning("Imported zip must not contain folders, ignored folder" + entry.getName()); continue; } if (!entry.getName().endsWith(suffix)) { // not valid file log.warning("Ignored file " + entry.getName()); continue; } if (log.isLoggable(Level.INFO)) log.info("Extracting file: " + entry.getName()); copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream( new FileOutputStream(tempfolder.getPath() + File.separator + entry.getName()))); validfile = true; } } catch (Throwable e) { throw new AdempiereException("Uncompress zip failed", e); } finally { if (zipFile != null) try { zipFile.close(); } catch (IOException e) { } } if (!validfile) { throw new AdempiereException("ZIP file invalid, doesn't contain *" + suffix + " files"); } callImportProcess(tempfolder.getPath()); file.delete(); try { FileUtils.deleteDirectory(tempfolder); } catch (IOException e) { } }
From source file:de.tuebingen.uni.sfs.germanet.api.GermaNet.java
/** * Constructs a new <code>GermaNet</code> object by loading the the data * files in the specified directory/archive File. * @param dir location of the GermaNet data files * @param ignoreCase if true ignore case on lookups, otherwise do case * sensitive searches// w w w.j a v a 2s . co m * @throws java.io.FileNotFoundException * @throws javax.xml.stream.XMLStreamException * @throws javax.xml.stream.IOException */ public GermaNet(File dir, boolean ignoreCase) throws FileNotFoundException, XMLStreamException, IOException { checkMemory(); this.ignoreCase = ignoreCase; this.inputStreams = null; this.synsets = new TreeSet<Synset>(); this.iliRecords = new ArrayList<IliRecord>(); this.wiktionaryParaphrases = new ArrayList<WiktionaryParaphrase>(); this.synsetID = new HashMap<Integer, Synset>(); this.lexUnitID = new HashMap<Integer, LexUnit>(); this.wordCategoryMap = new EnumMap<WordCategory, HashMap<String, ArrayList<LexUnit>>>(WordCategory.class); this.wordCategoryMapAllOrthForms = new EnumMap<WordCategory, HashMap<String, ArrayList<LexUnit>>>( WordCategory.class); if (!dir.isDirectory() && isZipFile(dir)) { ZipFile zipFile = new ZipFile(dir); Enumeration entries = zipFile.entries(); List<InputStream> inputStreamList = new ArrayList<InputStream>(); List<String> nameList = new ArrayList<String>(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); String entryName = entry.getName(); if (entryName.split(File.separator).length > 1) { entryName = entryName.split(File.separator)[entryName.split(File.separator).length - 1]; } nameList.add(entryName); InputStream stream = zipFile.getInputStream(entry); inputStreamList.add(stream); } inputStreams = inputStreamList; xmlNames = nameList; zipFile.close(); } else { this.dir = dir; } load(); }
From source file:fr.gouv.finances.dgfip.xemelios.importers.archives.ArchiveImporter.java
protected FileInfo doApplyAction(Element action) throws Exception { // l'action peut provenir d'un manifeste import ou d'un manifeste neuf, // il faut grer les deux namespaces String className = action.getAttributeValue("class"); Class clazz = Class.forName(className); Object instance = clazz.newInstance(); if (!(instance instanceof AbstractImportPatcherImpl)) { throw new Exception(className + " n'est pas un AbstractImportPatcherImpl"); }// w w w . j a va2s. c o m AbstractImportPatcherImpl patcher = (AbstractImportPatcherImpl) instance; Nodes parameters = action.query("parameter | m:parameter", getNamespaceCtx()); for (int i = 0; i < parameters.size(); i++) { Element param = (Element) parameters.get(i); String paramName = param.getAttributeValue("name"); String type = param.getAttributeValue("type"); if ("java.io.File".equals(type) && !"index.file".equals(paramName)) { String value = (String) param.query("text()").get(0).getValue(); String volume = null; try { volume = action.getDocument().query("//document[@path = '" + value + "']/@volume").get(0) .getValue(); } catch (Exception ex) { volume = action.getDocument() .query("//m:document[@path = '" + value + "']/@volume", getNamespaceCtx()).get(0) .getValue(); } if (volume == null) { volume = action.getDocument() .query("//m:document[@path = '" + value + "']/@volume", getNamespaceCtx()).get(0) .getValue(); } String archiveFileName = null; try { archiveFileName = action.getDocument().query("//volume[@num = '" + volume + "']/@fichier") .get(0).getValue(); } catch (Exception ex) { archiveFileName = action.getDocument() .query("//m:volume[@num = '" + volume + "']/@fichier", getNamespaceCtx()).get(0) .getValue(); } if (archiveFileName == null) archiveFileName = action.getDocument() .query("//m:volume[@num = '" + volume + "']/@fichier", getNamespaceCtx()).get(0) .getValue(); File archiveFile = new File(fileToImport.getParentFile(), archiveFileName); ZipFile zf = new ZipFile(archiveFile); // ca ne peut pas marcher, il faudrait une rfrence au numro de volume //ZipEntry ze = zf.getEntry(value); File f = null; try { f = extractFileFromZip(zf, value); } catch (Exception ex) { throw new RuntimeException(ex); } if (f != null) { filesToDrop.add(f); patcher.setParameter(paramName, f); } zf.close(); } else if ("java.io.File".equals(type) && "index.file".equals(paramName)) { // Pour les patchs de liasses edmn String value = (String) param.query("text()").get(0).getValue(); int nbVolumes = action.getDocument().query("//volume").size(); String archiveFileName = null; try { archiveFileName = action.getDocument().query("//volume[@num = '" + nbVolumes + "']/@fichier") .get(0).getValue(); } catch (Exception ex) { archiveFileName = action.getDocument() .query("//m:volume[@num = '" + nbVolumes + "']/@fichier", getNamespaceCtx()).get(0) .getValue(); } if (archiveFileName == null) archiveFileName = action.getDocument() .query("//m:volume[@num = '" + nbVolumes + "']/@fichier", getNamespaceCtx()).get(0) .getValue(); File archiveFile = new File(fileToImport.getParentFile(), archiveFileName); ZipFile zf = new ZipFile(archiveFile); // ca ne peut pas marcher, il faudrait une rfrence au numro de volume //ZipEntry ze = zf.getEntry(value); File f = null; try { f = extractFileFromZip(zf, value); } catch (Exception ex) { throw new RuntimeException(ex); } if (f != null) { filesToDrop.add(f); patcher.setParameter(paramName, f); } zf.close(); } else if ("java.lang.String".equals(type)) { String value = param.getAttributeValue("value"); if (value == null) { value = param.query("text()").get(0).getValue(); } patcher.setParameter(paramName, value); } else if ("java.lang.Integer".equals(type)) { String value = param.getAttributeValue("value"); if (value == null) { value = param.query("text()").get(0).getValue(); } patcher.setParameter(paramName, Integer.valueOf(value)); } } patcher.setImportServiceProvider(importServiceProvider); FileInfo info = patcher.run(); return info; }
From source file:org.b3log.solo.processor.CaptchaProcessor.java
/** * Loads captcha.//from w ww .j a v a 2s . co m */ private synchronized void loadCaptchas() { LOGGER.info("Loading captchas...."); try { captchas = new Image[CAPTCHA_COUNT]; ZipFile zipFile; if (RuntimeEnv.LOCAL == Latkes.getRuntimeEnv()) { final InputStream inputStream = SoloServletListener.class.getClassLoader() .getResourceAsStream("captcha_static.zip"); final File file = File.createTempFile("b3log_captcha_static", null); final OutputStream outputStream = new FileOutputStream(file); IOUtils.copy(inputStream, outputStream); zipFile = new ZipFile(file); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } else { final URL captchaURL = SoloServletListener.class.getClassLoader().getResource("captcha_static.zip"); zipFile = new ZipFile(captchaURL.getFile()); } final Enumeration<? extends ZipEntry> entries = zipFile.entries(); int i = 0; while (entries.hasMoreElements()) { final ZipEntry entry = entries.nextElement(); final BufferedInputStream bufferedInputStream = new BufferedInputStream( zipFile.getInputStream(entry)); final byte[] captchaCharData = new byte[bufferedInputStream.available()]; bufferedInputStream.read(captchaCharData); bufferedInputStream.close(); final Image image = IMAGE_SERVICE.makeImage(captchaCharData); image.setName(entry.getName().substring(0, entry.getName().lastIndexOf('.'))); captchas[i] = image; i++; } zipFile.close(); } catch (final Exception e) { LOGGER.error("Can not load captchs!"); throw new IllegalStateException(e); } LOGGER.info("Loaded captch images"); }
From source file:it.readbeyond.minstrel.librarian.FormatHandlerABZ.java
public Publication parseFile(File file) { Publication p = super.parseFile(file); Format format = new Format(ABZ_FORMAT); try {//from ww w.ja v a 2 s . c o m ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ); Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries(); boolean foundMetadataFile = false; boolean foundCover = false; boolean foundPlaylist = false; String zeCover = null; String zePlaylist = null; List<String> assets = new ArrayList<String>(); while (zipFileEntries.hasMoreElements()) { ZipEntry ze = zipFileEntries.nextElement(); String name = ze.getName(); String lower = name.toLowerCase(); if (lower.endsWith(ABZ_DEFAULT_COVER_JPG) || lower.endsWith(ABZ_DEFAULT_COVER_PNG)) { zeCover = name; } else if (lower.endsWith(ABZ_EXTENSION_PLAYLIST)) { zePlaylist = name; } else if (this.fileHasAllowedExtension(lower, ABZ_AUDIO_EXTENSIONS)) { p.isValid(true); assets.add(name); } else if (lower.endsWith(ABZ_FILE_METADATA)) { p.isValid(true); foundMetadataFile = true; if (this.parseMetadataFile(zipFile, ze, format)) { if (format.getMetadatum("internalPathPlaylist") != null) { foundPlaylist = true; } if (format.getMetadatum("internalPathCover") != null) { foundCover = true; } } } // end if metadata } // end while zipFile.close(); // set cover if ((!foundCover) && (zeCover != null)) { format.addMetadatum("internalPathCover", zeCover); } // default playlist found? if ((!foundPlaylist) && (zePlaylist != null)) { format.addMetadatum("internalPathPlaylist", zePlaylist); } // set number of assets format.addMetadatum("numberOfAssets", "" + assets.size()); } catch (Exception e) { // invalidate publication, so it will not be added to library p.isValid(false); } // end try p.addFormat(format); // extract cover super.extractCover(file, format, p.getID()); return p; }
From source file:org.talend.utils.io.FilesUtils.java
/** * Unzip the component file to the user folder. * /*from www.j ava2 s . co m*/ * @param zipFile The component zip file * @param targetFolder The user folder * @param fileSuffixes Case-insensitive Suffixes , if these parameter are set, only the files named with these * suffixes will be extracted * @return * @throws Exception */ @SuppressWarnings("unchecked") public static void unzip(String zipFile, String targetFolder, String... fileSuffixes) throws Exception { Exception exception = null; ZipFile zip = new ZipFile(zipFile); byte[] buf = new byte[8192]; try { Enumeration<ZipEntry> enumeration = (Enumeration<ZipEntry>) zip.entries(); while (enumeration.hasMoreElements()) { ZipEntry entry = enumeration.nextElement(); File file = new File(targetFolder, entry.getName()); if (entry.isDirectory()) { if (!file.exists()) { file.mkdir(); } } else { if (fileSuffixes.length > 0 && !isReservedFile(file.getName(), fileSuffixes)) { continue; } if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } InputStream zin = zip.getInputStream(entry); OutputStream fout = new FileOutputStream(file); // check if parent folder exists File dir = file.getParentFile(); if (dir.isDirectory() && !dir.exists()) { dir.mkdirs(); } try { while (true) { int bytesRead = zin.read(buf); if (bytesRead == -1) { // end of file break; } fout.write(buf, 0, bytesRead); } fout.flush(); } catch (Exception e) { exception = e; // stop looping return; } finally { zin.close(); fout.close(); } } } } catch (Exception e) { exception = e; } finally { zip.close(); if (exception != null) { // notify caller with exception throw exception; } } }
From source file:org.onehippo.repository.bootstrap.util.BootstrapUtils.java
public static ImportResult initializeNodecontent(Session session, String parentAbsPath, InputStream in, URL url, boolean pckg) throws RepositoryException { log.debug("Initializing content from {} to {}", url, parentAbsPath); File tempFile = null;//from ww w . jav a2 s . c o m ZipFile zipFile = null; InputStream esvIn = null; FileOutputStream out = null; try { if (in == null) { in = url.openStream(); } if (session instanceof HippoSession) { HippoSession hippoSession = (HippoSession) session; int uuidBehaviour = ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW; int referenceBehaviour = ImportReferenceBehavior.IMPORT_REFERENCE_NOT_FOUND_REMOVE; if (pckg) { tempFile = File.createTempFile("package", ".zip"); out = new FileOutputStream(tempFile); IOUtils.copy(in, out); out.close(); out = null; zipFile = new ZipFile(tempFile); ContentResourceLoader contentResourceLoader = new ZipFileContentResourceLoader(zipFile); esvIn = contentResourceLoader.getResourceAsStream("esv.xml"); return hippoSession.importEnhancedSystemViewXML(parentAbsPath, esvIn, uuidBehaviour, referenceBehaviour, contentResourceLoader); } else { ContentResourceLoader contentResourceLoader = null; if (url != null) { int offset = url.getFile().indexOf(".jar!"); if (offset != -1) { zipFile = new ZipFile(getBaseZipFileFromURL(url)); contentResourceLoader = new ZipFileContentResourceLoader(zipFile); } else if (url.getProtocol().equals("file")) { File sourceFile = new File(url.toURI()); contentResourceLoader = new FileContentResourceLoader(sourceFile.getParentFile()); } } return hippoSession.importEnhancedSystemViewXML(parentAbsPath, in, uuidBehaviour, referenceBehaviour, contentResourceLoader); } } else { throw new IllegalStateException("Not a HippoSession"); } } catch (IOException | URISyntaxException e) { throw new RepositoryException( "Error initializing content for " + url + " in '" + parentAbsPath + "': " + e, e); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); IOUtils.closeQuietly(esvIn); if (zipFile != null) { try { zipFile.close(); } catch (Exception ignore) { } } FileUtils.deleteQuietly(tempFile); } }