List of usage examples for java.util.zip ZipFile getInputStream
public InputStream getInputStream(ZipEntry entry) throws IOException
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 ww w . j av a2 s .c o 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:com.hichinaschool.flashcards.libanki.Utils.java
public static boolean unzipFiles(ZipFile zipFile, String targetDirectory, String[] zipEntries, HashMap<String, String> zipEntryToFilenameMap) { byte[] buf = new byte[FILE_COPY_BUFFER_SIZE]; File dir = new File(targetDirectory); if (!dir.exists() && !dir.mkdirs()) { Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Could not create target directory: " + targetDirectory); return false; }//from w w w . j a v a 2s . c om if (zipEntryToFilenameMap == null) { zipEntryToFilenameMap = new HashMap<String, String>(); } BufferedInputStream zis = null; BufferedOutputStream bos = null; try { for (String requestedEntry : zipEntries) { ZipEntry ze = zipFile.getEntry(requestedEntry); if (ze != null) { String name = ze.getName(); if (zipEntryToFilenameMap.containsKey(name)) { name = zipEntryToFilenameMap.get(name); } File destFile = new File(dir, name); File parentDir = destFile.getParentFile(); if (!parentDir.exists() && !parentDir.mkdirs()) { return false; } if (!ze.isDirectory()) { // Log.i(AnkiDroidApp.TAG, "uncompress " + name); zis = new BufferedInputStream(zipFile.getInputStream(ze)); bos = new BufferedOutputStream(new FileOutputStream(destFile), FILE_COPY_BUFFER_SIZE); int n; while ((n = zis.read(buf, 0, FILE_COPY_BUFFER_SIZE)) != -1) { bos.write(buf, 0, n); } bos.flush(); bos.close(); zis.close(); } } } } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while unzipping archive.", e); return false; } finally { try { if (bos != null) { bos.close(); } } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while closing output stream.", e); } try { if (zis != null) { zis.close(); } } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while closing zip input stream.", e); } } return true; }
From source file:com.web.server.SARDeployer.java
/** * This method extracts the SAR archive and configures for the SAR and starts the services * @param file/* w w w. ja v a 2 s .co m*/ * @param warDirectoryPath * @throws IOException */ public void extractSar(File file, String warDirectoryPath) throws IOException { ZipFile zip = new ZipFile(file); ZipEntry ze = null; String fileName = file.getName(); fileName = fileName.substring(0, fileName.indexOf('.')); fileName += "sar"; String fileDirectory; CopyOnWriteArrayList classPath = new CopyOnWriteArrayList(); Enumeration<? extends ZipEntry> entries = zip.entries(); int numBytes; while (entries.hasMoreElements()) { ze = entries.nextElement(); // //System.out.println("Unzipping " + ze.getName()); String filePath = deployDirectory + "/" + fileName + "/" + ze.getName(); if (!ze.isDirectory()) { fileDirectory = filePath.substring(0, filePath.lastIndexOf('/')); } else { fileDirectory = filePath; } // //System.out.println(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(); URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = loader.getURLs(); WebClassLoader sarClassLoader = new WebClassLoader(urls); for (int index = 0; index < classPath.size(); index++) { System.out.println("file:" + classPath.get(index)); new WebServer().addURL(new URL("file:" + classPath.get(index)), sarClassLoader); } new WebServer().addURL(new URL("file:" + deployDirectory + "/" + fileName + "/"), sarClassLoader); sarsMap.put(fileName, sarClassLoader); System.out.println(sarClassLoader.geturlS()); try { Sar sar = (Sar) sardigester.parse(new InputSource( new FileInputStream(deployDirectory + "/" + fileName + "/META-INF/" + "mbean-service.xml"))); CopyOnWriteArrayList mbeans = sar.getMbean(); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); System.out.println(mbs); ObjectName objName; for (int index = 0; index < mbeans.size(); index++) { Mbean mbean = (Mbean) mbeans.get(index); System.out.println(mbean.getObjectname()); System.out.println(mbean.getCls()); objName = new ObjectName(mbean.getObjectname()); Class helloWorldService = sarClassLoader.loadClass(mbean.getCls()); Object obj = helloWorldService.newInstance(); if (mbs.isRegistered(objName)) { mbs.invoke(objName, "stopService", null, null); //mbs.invoke(objName, "destroy", null, null); mbs.unregisterMBean(objName); } 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()); mbs.setAttribute(objName, mbeanattribute); } } mbs.invoke(objName, "startService", null, null); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedObjectNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstanceAlreadyExistsException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MBeanRegistrationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NotCompliantMBeanException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstanceNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ReflectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MBeanException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidAttributeValueException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (AttributeNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.fuin.utils4j.Utils4J.java
/** * Unzips a file into a given directory. WARNING: Only relative path entries * are allowed inside the archive!//from w w w . ja v a 2s . c om * * @param zipFile * Source ZIP file - Cannot be <code>null</code> and must be a * valid ZIP file. * @param destDir * Destination directory - Cannot be <code>null</code> and must * exist. * @param wrapper * Callback interface to give the caller the chance to wrap the * ZIP input stream into another one. This is useful for example * to display a progress bar - Can be <code>null</code> if no * wrapping is required. * @param cancelable * Signals if the unzip should be canceled - Can be * <code>null</code> if no cancel option is required. * * @throws IOException * Error unzipping the file. */ public static void unzip(final File zipFile, final File destDir, final UnzipInputStreamWrapper wrapper, final Cancelable cancelable) throws IOException { checkNotNull("zipFile", zipFile); checkValidFile(zipFile); checkNotNull("destDir", destDir); checkValidDir(destDir); final ZipFile zip = new ZipFile(zipFile); try { final Enumeration enu = zip.entries(); while (enu.hasMoreElements() && ((cancelable == null) || !cancelable.isCanceled())) { final ZipEntry entry = (ZipEntry) enu.nextElement(); final File file = new File(entry.getName()); if (file.isAbsolute()) { throw new IllegalArgumentException( "Only relative path entries are allowed! [" + entry.getName() + "]"); } if (entry.isDirectory()) { final File dir = new File(destDir, entry.getName()); createIfNecessary(dir); } else { final File outFile = new File(destDir, entry.getName()); createIfNecessary(outFile.getParentFile()); final InputStream in; if (wrapper == null) { in = new BufferedInputStream(zip.getInputStream(entry)); } else { in = new BufferedInputStream( wrapper.wrapInputStream(zip.getInputStream(entry), entry, outFile)); } try { final OutputStream out = new BufferedOutputStream(new FileOutputStream(outFile)); try { final byte[] buf = new byte[4096]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { out.close(); } } finally { in.close(); } } } } finally { zip.close(); } }
From source file:org.apache.maven.doxia.siterenderer.DefaultSiteRenderer.java
/** {@inheritDoc} */ public SiteRenderingContext createContextForSkin(Artifact skin, Map<String, ?> attributes, DecorationModel decoration, String defaultWindowTitle, Locale locale) throws IOException, RendererException { SiteRenderingContext context = createSiteRenderingContext(attributes, decoration, defaultWindowTitle, locale);/*ww w . j a v a 2 s.c o m*/ context.setSkin(skin); ZipFile zipFile = getZipFile(skin.getFile()); InputStream in = null; try { if (zipFile.getEntry(SKIN_TEMPLATE_LOCATION) != null) { context.setTemplateName(SKIN_TEMPLATE_LOCATION); context.setTemplateClassLoader(new URLClassLoader(new URL[] { skin.getFile().toURI().toURL() })); } else { context.setTemplateName(DEFAULT_TEMPLATE); context.setTemplateClassLoader(getClass().getClassLoader()); context.setUsingDefaultTemplate(true); } ZipEntry skinDescriptorEntry = zipFile.getEntry(SkinModel.SKIN_DESCRIPTOR_LOCATION); if (skinDescriptorEntry != null) { in = zipFile.getInputStream(skinDescriptorEntry); SkinModel skinModel = new SkinXpp3Reader().read(in); context.setSkinModel(skinModel); String toolsPrerequisite = skinModel.getPrerequisites() == null ? null : skinModel.getPrerequisites().getDoxiaSitetools(); Package p = DefaultSiteRenderer.class.getPackage(); String current = (p == null) ? null : p.getImplementationVersion(); if (StringUtils.isNotBlank(toolsPrerequisite) && (current != null) && !matchVersion(current, toolsPrerequisite)) { throw new RendererException("Cannot use skin: has " + toolsPrerequisite + " Doxia Sitetools prerequisite, but current is " + current); } } } catch (XmlPullParserException e) { throw new RendererException("Failed to parse " + SkinModel.SKIN_DESCRIPTOR_LOCATION + " skin descriptor from " + skin.getId() + " skin", e); } finally { IOUtil.close(in); closeZipFile(zipFile); } return context; }
From source file:com.jayway.maven.plugins.android.phase09package.ApkMojo.java
private void updateWithMetaInf(ZipOutputStream zos, File jarFile, Set<String> entries, boolean metaInfOnly) throws IOException { ZipFile zin = new ZipFile(jarFile); for (Enumeration<? extends ZipEntry> en = zin.entries(); en.hasMoreElements();) { ZipEntry ze = en.nextElement(); if (ze.isDirectory()) { continue; }//from w w w. j a v a2s. c o m String zn = ze.getName(); if (metaInfOnly) { if (!zn.startsWith("META-INF/")) { continue; } if (this.extractDuplicates && !entries.add(zn)) { continue; } if (!this.apkMetaInf.isIncluded(zn)) { continue; } } final ZipEntry ne; if (ze.getMethod() == ZipEntry.STORED) { ne = new ZipEntry(ze); } else { ne = new ZipEntry(zn); } zos.putNextEntry(ne); InputStream is = zin.getInputStream(ze); copyStreamWithoutClosing(is, zos); is.close(); zos.closeEntry(); } zin.close(); }
From source file:org.apache.taverna.commandline.TavernaCommandLineTest.java
private void assertZipFilesEqual(File file1, File file2) { ZipFile zipFile1 = null; ZipFile zipFile2 = null;//from ww w . j a v a 2s . c o m try { zipFile1 = new ZipFile(file1); zipFile2 = new ZipFile(file2); } catch (Exception e) { assertTrue(String.format("%s and %s are not both zip files"), zipFile1 == null); } if (zipFile1 != null && zipFile2 != null) { Enumeration<? extends ZipEntry> entries1 = zipFile1.entries(); Enumeration<? extends ZipEntry> entries2 = zipFile2.entries(); while (entries1.hasMoreElements()) { assertTrue(entries2.hasMoreElements()); ZipEntry zipEntry1 = entries1.nextElement(); ZipEntry zipEntry2 = entries2.nextElement(); assertEquals(String.format("%s and %s are not both directories", zipEntry1, zipEntry2), zipEntry1.isDirectory(), zipEntry2.isDirectory()); assertEquals(String.format("%s and %s have different names", zipEntry1, zipEntry2), zipEntry1.getName(), zipEntry2.getName()); assertEquals(String.format("%s and %s have different sizes", zipEntry1, zipEntry2), zipEntry1.getSize(), zipEntry2.getSize()); try { byte[] byteArray1 = IOUtils.toByteArray(zipFile1.getInputStream(zipEntry1)); byte[] byteArray2 = IOUtils.toByteArray(zipFile2.getInputStream(zipEntry2)); assertArrayEquals(String.format("%s != %s", zipEntry1, zipEntry2), byteArray1, byteArray2); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } assertFalse(entries2.hasMoreElements()); } }
From source file:org.geoserver.kml.KMLReflectorTest.java
protected void doTestRasterPlacemark(boolean doPlacemarks) throws Exception { // the style selects a single feature final String requestUrl = "wms/kml?layers=" + getLayerId(MockData.BASIC_POLYGONS) + "&styles=&mode=download&kmscore=0&format_options=kmplacemark:" + doPlacemarks + "&format=" + KMZMapOutputFormat.MIME_TYPE; MockHttpServletResponse response = getAsServletResponse(requestUrl); assertEquals(KMZMapOutputFormat.MIME_TYPE, response.getContentType()); ZipFile zipFile = null; try {//from www . j a va 2s . c o m // create the kmz File tempDir = org.geoserver.data.util.IOUtils.createRandomDirectory("./target", "kmplacemark", "test"); tempDir.deleteOnExit(); File zip = new File(tempDir, "kmz.zip"); zip.deleteOnExit(); FileOutputStream output = new FileOutputStream(zip); FileUtils.writeByteArrayToFile(zip, getBinary(response)); output.flush(); output.close(); assertTrue(zip.exists()); // unzip and test it zipFile = new ZipFile(zip); ZipEntry entry = zipFile.getEntry("wms.kml"); assertNotNull(entry); assertNotNull(zipFile.getEntry("images/layers_0.png")); // unzip the wms.kml to file byte[] buffer = new byte[1024]; int len; InputStream inStream = zipFile.getInputStream(entry); File temp = File.createTempFile("test_out", "kmz", tempDir); temp.deleteOnExit(); BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(temp)); while ((len = inStream.read(buffer)) >= 0) outStream.write(buffer, 0, len); inStream.close(); outStream.close(); // read in the wms.kml and check its contents Document document = dom(new BufferedInputStream(new FileInputStream(temp))); // print(document); assertEquals("kml", document.getDocumentElement().getNodeName()); if (doPlacemarks) { assertEquals(getFeatureSource(MockData.BASIC_POLYGONS).getFeatures().size(), document.getElementsByTagName("Placemark").getLength()); XMLAssert.assertXpathEvaluatesTo("3", "count(//kml:Placemark//kml:Point)", document); } else { assertEquals(0, document.getElementsByTagName("Placemark").getLength()); } } finally { if (zipFile != null) { zipFile.close(); } } }
From source file:org.eclipse.orion.internal.server.servlets.xfer.ClientImport.java
/** * Unzips the transferred file. Returns <code>true</code> if the unzip was * successful, and <code>false</code> otherwise. In case of failure, this method * handles setting an appropriate response. *///w ww . ja va2s .co m private boolean completeUnzip(HttpServletRequest req, HttpServletResponse resp) throws ServletException { IPath destPath = new Path(getPath()); boolean force = false; List<String> filesFailed = new ArrayList<String>(); if (req.getParameter("force") != null) { force = req.getParameter("force").equals("true"); } List<String> excludedFiles = new ArrayList<String>(); if (req.getParameter(ProtocolConstants.PARAM_EXCLUDE) != null) { excludedFiles = Arrays.asList(req.getParameter(ProtocolConstants.PARAM_EXCLUDE).split(",")); } try { ZipFile source = new ZipFile(new File(getStorageDirectory(), FILE_DATA)); IFileStore destinationRoot = NewFileServlet.getFileStore(req, destPath); Enumeration<? extends ZipEntry> entries = source.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); IFileStore destination = destinationRoot.getChild(entry.getName()); if (!destinationRoot.isParentOf(destination) || hasExcludedParent(destination, destinationRoot, excludedFiles)) { //file should not be imported continue; } if (entry.isDirectory()) destination.mkdir(EFS.NONE, null); else { if (!force && destination.fetchInfo().exists()) { filesFailed.add(entry.getName()); continue; } destination.getParent().mkdir(EFS.NONE, null); // this filter will throw an IOException if a zip entry is larger than 100MB FilterInputStream maxBytesReadInputStream = new FilterInputStream( source.getInputStream(entry)) { private static final int maxBytes = 0x6400000; // 100MB private int totalBytes; private void addByteCount(int count) throws IOException { totalBytes += count; if (totalBytes > maxBytes) { throw new IOException("Zip file entry too large"); } } @Override public int read() throws IOException { int c = super.read(); if (c != -1) { addByteCount(1); } return c; } @Override public int read(byte[] b, int off, int len) throws IOException { int read = super.read(b, off, len); if (read != -1) { addByteCount(read); } return read; } }; boolean fileWritten = false; try { IOUtilities.pipe(maxBytesReadInputStream, destination.openOutputStream(EFS.NONE, null), false, true); fileWritten = true; } finally { if (!fileWritten) { try { destination.delete(EFS.NONE, null); } catch (CoreException ce) { // best effort } } } } } source.close(); if (!filesFailed.isEmpty()) { String failedFilesList = ""; for (String file : filesFailed) { if (failedFilesList.length() > 0) { failedFilesList += ", "; } failedFilesList += file; } String msg = NLS.bind( "Failed to transfer all files to {0}, the following files could not be overwritten {1}", destPath.toString(), failedFilesList); JSONObject jsonData = new JSONObject(); jsonData.put("ExistingFiles", filesFailed); statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, jsonData, null)); return false; } } catch (ZipException e) { //zip exception implies client sent us invalid input String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString()); statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, e)); return false; } catch (Exception e) { //other failures should be considered server errors String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString()); statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e)); return false; } return true; }
From source file:com.googlecode.android_scripting.ZipExtractorTask.java
private long unzip() throws Exception { long extractedSize = 0l; Enumeration<? extends ZipEntry> entries; if (mInput.isFile() && mInput.getName().contains(".gz")) { InputStream stream = new FileInputStream(mInput); GZIPInputStream gzipStream = new GZIPInputStream(stream); InputSource is = new InputSource(gzipStream); InputStream input = new BufferedInputStream(is.getByteStream()); File destination = new File(mOutput, "php"); ByteArrayBuffer baf = new ByteArrayBuffer(255000); int current = 0; while ((current = input.read()) != -1) { baf.append((byte) current); }/*from w w w. ja v a 2 s . co m*/ FileOutputStream output = new FileOutputStream(destination); output.write(baf.toByteArray()); output.close(); Log.d("written!"); return baf.toByteArray().length; } ZipFile zip = new ZipFile(mInput); long uncompressedSize = getOriginalSize(zip); publishProgress(0, (int) uncompressedSize); entries = zip.entries(); try { while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { // Not all zip files actually include separate directory entries. // We'll just ignore them // and create them as necessary for each actual entry. continue; } File destination = new File(mOutput, entry.getName()); if (!destination.getParentFile().exists()) { destination.getParentFile().mkdirs(); } if (destination.exists() && mContext != null && !mReplaceAll) { Replace answer = showDialog(entry.getName()); switch (answer) { case YES: break; case NO: continue; case YESTOALL: mReplaceAll = true; break; default: return extractedSize; } } ProgressReportingOutputStream outStream = new ProgressReportingOutputStream(destination); extractedSize += IoUtils.copy(zip.getInputStream(entry), outStream); outStream.close(); } } finally { try { zip.close(); } catch (Exception e) { // swallow this exception, we are only interested in the original one } } Log.v("Extraction is complete."); return extractedSize; }