List of usage examples for java.util.zip ZipFile entries
public Enumeration<? extends ZipEntry> entries()
From source file:com.app.server.SARDeployer.java
/** * This method extracts the SAR archive and configures for the SAR and starts the services * @param file/*from w ww .j a v a2s .c o m*/ * @param warDirectoryPath * @throws IOException */ public void extractSarDeploy(ClassLoader cL, Object... args) throws IOException { CopyOnWriteArrayList classPath = null; File file = null; String fileName = ""; String fileWithPath = ""; if (args[0] instanceof File) { classPath = new CopyOnWriteArrayList(); file = (File) args[0]; fileWithPath = file.getAbsolutePath(); ZipFile zip = new ZipFile(file); ZipEntry ze = null; fileName = file.getName(); fileName = fileName.substring(0, fileName.indexOf('.')); fileName += "sar"; String fileDirectory; Enumeration<? extends ZipEntry> entries = zip.entries(); int numBytes; while (entries.hasMoreElements()) { ze = entries.nextElement(); // //log.info("Unzipping " + ze.getName()); String filePath = serverConfig.getDeploydirectory() + "/" + fileName + "/" + ze.getName(); if (!ze.isDirectory()) { fileDirectory = filePath.substring(0, filePath.lastIndexOf('/')); } else { fileDirectory = filePath; } // //log.info(fileDirectory); createDirectory(fileDirectory); if (!ze.isDirectory()) { FileOutputStream fout = new FileOutputStream(filePath); byte[] inputbyt = new byte[8192]; InputStream istream = zip.getInputStream(ze); while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) { fout.write(inputbyt, 0, numBytes); } fout.close(); istream.close(); if (ze.getName().endsWith(".jar")) { classPath.add(filePath); } } } zip.close(); } else if (args[0] instanceof FileObject) { FileObject fileObj = (FileObject) args[0]; fileName = fileObj.getName().getBaseName(); try { fileWithPath = fileObj.getURL().toURI().toString(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } fileName = fileName.substring(0, fileName.indexOf('.')); fileName += "sar"; classPath = unpack(fileObj, new File(serverConfig.getDeploydirectory() + "/" + fileName + "/"), (StandardFileSystemManager) args[1]); } URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = loader.getURLs(); WebClassLoader sarClassLoader; if (cL != null) { sarClassLoader = new WebClassLoader(urls, cL); } else { sarClassLoader = new WebClassLoader(urls); } for (int index = 0; index < classPath.size(); index++) { // log.info("file:"+classPath.get(index)); sarClassLoader.addURL(new URL("file:" + classPath.get(index))); } sarClassLoader.addURL(new URL("file:" + serverConfig.getDeploydirectory() + "/" + fileName + "/")); //log.info(sarClassLoader.geturlS()); sarsMap.put(fileWithPath, sarClassLoader); try { Sar sar = (Sar) sardigester.parse(new InputSource(new FileInputStream( serverConfig.getDeploydirectory() + "/" + fileName + "/META-INF/" + "mbean-service.xml"))); CopyOnWriteArrayList mbeans = sar.getMbean(); //log.info(mbeanServer); ObjectName objName, classLoaderObjectName = new ObjectName("com.app.server:classLoader=" + fileName); if (!mbeanServer.isRegistered(classLoaderObjectName)) { mbeanServer.registerMBean(sarClassLoader, classLoaderObjectName); } else { mbeanServer.unregisterMBean(classLoaderObjectName); mbeanServer.registerMBean(sarClassLoader, classLoaderObjectName); ; } for (int index = 0; index < mbeans.size(); index++) { Mbean mbean = (Mbean) mbeans.get(index); //log.info(mbean.getObjectname()); //log.info(mbean.getCls()); objName = new ObjectName(mbean.getObjectname()); Class service = sarClassLoader.loadClass(mbean.getCls()); if (mbeanServer.isRegistered(objName)) { //mbs.invoke(objName, "stopService", null, null); //mbs.invoke(objName, "destroy", null, null); mbeanServer.unregisterMBean(objName); } mbeanServer.createMBean(service.getName(), objName, classLoaderObjectName); //mbs.registerMBean(obj, objName); CopyOnWriteArrayList attrlist = mbean.getMbeanAttribute(); if (attrlist != null) { for (int count = 0; count < attrlist.size(); count++) { MBeanAttribute attr = (MBeanAttribute) attrlist.get(count); Attribute mbeanattribute = new Attribute(attr.getName(), attr.getValue()); mbeanServer.setAttribute(objName, mbeanattribute); } } Attribute mbeanattribute = new Attribute("ObjectName", objName); mbeanServer.setAttribute(objName, mbeanattribute); if (((String) mbeanServer.getAttribute(objName, "Deployer")).equals("true")) { mbeanServer.invoke(objName, "init", new Object[] { deployerList }, new String[] { Vector.class.getName() }); } mbeanServer.invoke(objName, "init", new Object[] { serviceList, serverConfig, mbeanServer }, new String[] { Vector.class.getName(), ServerConfig.class.getName(), MBeanServer.class.getName() }); mbeanServer.invoke(objName, "start", null, null); serviceListObjName.put(fileWithPath, objName); } } catch (Exception e) { log.error("Could not able to deploy sar archive " + fileWithPath, e); // TODO Auto-generated catch block //e.printStackTrace(); } }
From source file:org.apache.taverna.scufl2.ucfpackage.TestUCFPackage.java
@Test public void mimeTypePosition() throws Exception { UCFPackage container = new UCFPackage(); container.setPackageMediaType(UCFPackage.MIME_EPUB); assertEquals(UCFPackage.MIME_EPUB, container.getPackageMediaType()); container.save(tmpFile);//from w w w .j a va 2 s . c om assertTrue(tmpFile.exists()); ZipFile zipFile = new ZipFile(tmpFile); // Must be first entry ZipEntry mimeEntry = zipFile.entries().nextElement(); assertEquals("First zip entry is not 'mimetype'", "mimetype", mimeEntry.getName()); assertEquals("mimetype should be uncompressed, but compressed size mismatch", mimeEntry.getCompressedSize(), mimeEntry.getSize()); assertEquals("mimetype should have STORED method", ZipEntry.STORED, mimeEntry.getMethod()); assertEquals("Wrong mimetype", UCFPackage.MIME_EPUB, IOUtils.toString(zipFile.getInputStream(mimeEntry), "ASCII")); // Check position 30++ according to // http://livedocs.adobe.com/navigator/9/Navigator_SDK9_HTMLHelp/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Navigator_SDK9_HTMLHelp&file=Appx_Packaging.6.1.html#1522568 byte[] expected = ("mimetype" + UCFPackage.MIME_EPUB + "PK").getBytes("ASCII"); FileInputStream in = new FileInputStream(tmpFile); byte[] actual = new byte[expected.length]; try { assertEquals(MIME_OFFSET, in.skip(MIME_OFFSET)); assertEquals(expected.length, in.read(actual)); } finally { in.close(); } assertArrayEquals(expected, actual); }
From source file:com.disney.opa.util.AttachmentUtils.java
/** * This method is to extract the zip files and creates attachment objects. * /*from www .j a v a 2 s .c o m*/ * @param attachment * @param fileNames * @param fileLabels * @param errors * @return list of attachments from the zip file */ public List<Attachment> processZipFile(Attachment attachment, List<String> fileNames, List<String> fileLabels, List<String> errors) { ZipFile zipFile = null; List<Attachment> attachments = new ArrayList<Attachment>(); try { String zipFilePath = getOriginalAttachmentsPath(attachment.getProductID()) + File.separator + attachment.getFilename(); zipFile = new ZipFile(zipFilePath); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; } String fileName = entry.getName(); File destinationFile = new File( getOriginalAttachmentsPath(attachment.getProductID()) + File.separator + fileName); uploadFile(zipFile.getInputStream(entry), destinationFile); String label = createUniqueFileLabel(fileName, null, fileLabels); Attachment fileAttachment = getAttachment(fileName, label, attachment.getProductID(), attachment.getProductStateID(), attachment.getUserID()); if (fileAttachment.getFileSize() == 0L) { errors.add("File not found, file name: " + fileName + ", in zip file: " + attachment.getFilename()); } else { attachments.add(fileAttachment); } } } catch (Exception e) { errors.add( "Error while processing zip: " + attachment.getFilename() + ", title: " + attachment.getName()); log.error("Error while processing zip.", e); } finally { try { if (zipFile != null) { zipFile.close(); } } catch (IOException e) { } } return attachments; }
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//from w w w.ja v a2 s .c om * @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:org.b3log.solo.processor.CaptchaProcessor.java
/** * Loads captcha./*from w w w . j a v a2 s . c om*/ */ 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:com.htmlhifive.tools.wizard.download.DownloadModule.java
/** * ZIP?.//from w ww. j a v a 2 s. com * * @param libraryNode * @param perLibWork libWork * @param folder * @param monitor * @param logger . * @return ???????. * @throws IOException IO * @throws CoreException */ private boolean downloadZip(LibraryNode libraryNode, int perLibWork, IContainer folder, IProgressMonitor monitor, ResultStatus logger) throws IOException, CoreException { boolean result = true; boolean addStatus = false; ZipFile cachedZipFile = null; String cachedSite = null; Library library = libraryNode.getValue(); if (!library.getSite().isEmpty()) { int perSiteWork = Math.max(1, perLibWork / library.getSite().size()); for (Site site : library.getSite()) { String siteUrl = site.getUrl(); String path = H5IOUtils.getURLPath(siteUrl); if (path == null) { logger.log(Messages.SE0082, siteUrl); continue; } boolean setWorked = false; IContainer savedFolder = folder; if (site.getExtractPath() != null) { savedFolder = savedFolder.getFolder(Path.fromOSString(site.getExtractPath())); } // ?. IFile iFile = null; if (path.endsWith(".zip") || path.endsWith(".jar") || site.getFilePattern() != null) { // Zip // ?????????. if (!siteUrl.equals(cachedSite)) { cachedZipFile = download(monitor, perSiteWork, logger, null, siteUrl); setWorked = true; if (!lastDownloadStatus || cachedZipFile == null) { libraryNode.setInError(true); result = false; break; } cachedSite = siteUrl; } final ZipFile zipFile = cachedZipFile; // int perZipWork = Math.max(1, perSiteWork / zipFile.size()); // Zip. for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) { final ZipEntry zipEntry = e.nextElement(); if (site.getFilePattern() != null && !FilenameUtils.wildcardMatch(zipEntry.getName(), site.getFilePattern())) { // ???. continue; } IContainer savedFolder2 = savedFolder; String wildCardStr = StringUtils.defaultString(site.getFilePattern()); if (wildCardStr.contains("*") && wildCardStr.contains("/")) { // ??????. wildCardStr = StringUtils.substringBeforeLast(site.getFilePattern(), "/"); } String entryName = zipEntry.getName(); if (entryName.startsWith(wildCardStr + "/")) { entryName = entryName.substring(wildCardStr.length() + 1); } if (zipEntry.isDirectory()) { // zip?????. if (StringUtils.isNotEmpty(entryName)) { // ?. savedFolder2 = savedFolder2.getFolder(Path.fromOSString(entryName)); if (libraryNode.isAddable() && !savedFolder2.exists()) { logger.log(Messages.SE0091, savedFolder2.getFullPath()); H5IOUtils.createParentFolder(savedFolder2, null); logger.log(Messages.SE0092, savedFolder2.getFullPath()); } else if (libraryNode.getState() == LibraryState.REMOVE && savedFolder2.exists()) { // . logger.log(Messages.SE0095, savedFolder2.getFullPath()); H5IOUtils.createParentFolder(savedFolder2, null); logger.log(Messages.SE0096, savedFolder2.getFullPath()); } } } else { // zip. // ???. if (site.getReplaceFileName() != null) { iFile = savedFolder2.getFile(Path.fromOSString(site.getReplaceFileName())); } else { iFile = savedFolder2.getFile(Path.fromOSString(entryName)); } // ?. updateFile(monitor, 0, logger, iFile, new ZipFileContentsHandler(zipFile, zipEntry)); addStatus = true; } } if (savedFolder.exists() && savedFolder.members().length == 0) { // ????. savedFolder.delete(true, monitor); } } else { // ???. if (site.getReplaceFileName() != null) { iFile = savedFolder.getFile(Path.fromOSString(site.getReplaceFileName())); } else { // . iFile = savedFolder.getFile(Path.fromOSString(StringUtils.substringAfterLast(path, "/"))); } // . download(monitor, perSiteWork, logger, iFile, siteUrl); setWorked = true; if (!lastDownloadStatus) { // SE0101=ERROR,({0})??????URL={1}, File={2} logger.log(Messages.SE0101, iFile != null ? iFile.getFullPath().toString() : StringUtils.defaultString(site.getFilePattern()), site.getUrl(), site.getFilePattern()); libraryNode.setInError(true); } else { addStatus = true; } } // ?????. // . if (!addStatus) { // SE0099=ERROR,???????URL={1}, File={2} logger.log(Messages.SE0099, site.getUrl(), iFile != null ? iFile.getFullPath().toString() : StringUtils.defaultString(site.getFilePattern())); libraryNode.setInError(true); result = false; } // folder.refreshLocal(IResource.DEPTH_ZERO, null); // // SE0102=INFO,???? // logger.log(Messages.SE0102); // logger.log(Messages.SE0068, iFile.getFullPath()); if (!setWorked) { monitor.worked(perSiteWork); } } } else { monitor.worked(perLibWork); } return result; }
From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileUtilities.java
public void decompressZip(File inputZipPath, File zipPath) { int BUFFER = 2048; List<File> zipFiles = new ArrayList<File>(); try {//ww w. j a v a2 s. c o m zipPath.mkdir(); } catch (SecurityException e) { jlog.fatal("Security exception when creating " + zipPath.getName()); } ZipFile zipFile = null; boolean isZip = true; // Open Zip file for reading (should be in temppath) try { zipFile = new ZipFile(inputZipPath, ZipFile.OPEN_READ); } catch (IOException e) { jlog.fatal("IO exception in " + inputZipPath.getName()); } // Create an enumeration of the entries in the zip file Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries(); if (isZip) { // Process each entry while (zipFileEntries.hasMoreElements()) { // Get a zip file entry ZipEntry entry = zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = null; // destFile should be pointing to temppath\%date%\ try { destFile = new File(zipPath.getAbsolutePath(), currentEntry); destFile = new File(zipPath.getAbsolutePath(), destFile.getName()); } catch (NullPointerException e) { jlog.fatal("File not found" + destFile.getName()); } // If the entry is a .zip add it to the list so that it can be extracted if (currentEntry.endsWith(".zip")) { zipFiles.add(destFile); } try { // Extract file if not a directory if (!entry.isDirectory()) { // Stream the zip entry BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry)); int currentByte; // establish buffer for writing file byte data[] = new byte[BUFFER]; FileOutputStream fos = null; // Write the current file to disk try { fos = new FileOutputStream(destFile); } catch (FileNotFoundException e) { jlog.fatal("File not found " + destFile.getName()); } catch (SecurityException e) { jlog.fatal("Access denied to " + destFile.getName()); } BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); // read and write until last byte is encountered while ((currentByte = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, currentByte); } dest.flush(); dest.close(); is.close(); } } catch (IOException ioe) { jlog.fatal("IO exception in " + zipFile.getName()); } } try { zipFile.close(); } catch (IOException e) { jlog.fatal("IO exception when closing " + zipFile.getName()); } } // Recursively decompress the list of zip files for (File f : zipFiles) { decompressZip(f, zipPath); } return; }
From source file:org.guvnor.m2repo.backend.server.GuvnorM2Repository.java
private File appendPOMToJar(final String pom, final String jarPath, final GAV gav) { File originalJarFile = new File(jarPath); File appendedJarFile = new File(jarPath + ".tmp"); try {/* w ww .j a v a 2s. c o m*/ ZipFile war = new ZipFile(originalJarFile); ZipOutputStream append = new ZipOutputStream(new FileOutputStream(appendedJarFile)); // first, copy contents from existing war Enumeration<? extends ZipEntry> entries = war.entries(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); append.putNextEntry(e); if (!e.isDirectory()) { IOUtil.copy(war.getInputStream(e), append); } append.closeEntry(); } // append pom.xml ZipEntry e = new ZipEntry(getPomXmlPath(gav)); append.putNextEntry(e); append.write(pom.getBytes()); append.closeEntry(); // close war.close(); append.close(); } catch (ZipException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } return appendedJarFile; }
From source file:org.guvnor.m2repo.backend.server.GuvnorM2Repository.java
private File appendPomPropertiesToJar(final String pomProperties, final String jarPath, final GAV gav) { File originalJarFile = new File(jarPath); File appendedJarFile = new File(jarPath + ".tmp"); try {// ww w. j ava 2 s. c om ZipFile war = new ZipFile(originalJarFile); ZipOutputStream append = new ZipOutputStream(new FileOutputStream(appendedJarFile)); // first, copy contents from existing war Enumeration<? extends ZipEntry> entries = war.entries(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); append.putNextEntry(e); if (!e.isDirectory()) { IOUtil.copy(war.getInputStream(e), append); } append.closeEntry(); } // append pom.properties ZipEntry e = new ZipEntry(getPomPropertiesPath(gav)); append.putNextEntry(e); append.write(pomProperties.getBytes()); append.closeEntry(); // close war.close(); append.close(); } catch (ZipException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } //originalJarFile.delete(); //appendedJarFile.renameTo(originalJarFile); return appendedJarFile; }
From source file:org.talend.mdm.repository.ui.wizards.imports.ImportServerObjectWizard.java
private byte[] extractBar(File barFile) { ZipFile zipFile = null; InputStream entryInputStream = null; byte[] processBytes = null; try {/*w ww.j ava2 s .c o m*/ zipFile = new ZipFile(barFile); for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.isDirectory()) { if (entry.getName().endsWith(".proc")) { //$NON-NLS-1$ entryInputStream = zipFile.getInputStream(entry); processBytes = IOUtils.toByteArray(entryInputStream); } } } } catch (IOException e) { log.error(e.getMessage(), e); } finally { if (entryInputStream != null) { try { entryInputStream.close(); } catch (IOException e) { } } if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { } } } return processBytes; }