Java Code Examples for java.util.zip.ZipFile
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project azkaban, under directory /azkaban/src/java/azkaban/web/.
Source file: JobManagerServlet.java

private File unzipFile(FileItem item) throws ServletException, IOException { File temp=File.createTempFile("job-temp",".zip"); temp.deleteOnExit(); OutputStream out=new BufferedOutputStream(new FileOutputStream(temp)); IOUtils.copy(item.getInputStream(),out); out.close(); ZipFile zipfile=new ZipFile(temp); File unzipped=Utils.createTempDir(new File(_tempDir)); Utils.unzip(zipfile,unzipped); temp.delete(); return unzipped; }
Example 2
From project ceres, under directory /ceres-deploy/src/main/java/com/bc/ceres/deploy/.
Source file: DeployMain.java

private void extractFiles(File moduleFile,File moduleRepositoryDir) throws IOException { ZipFile zip=new ZipFile(moduleFile); try { for ( String mandatoryFilePath : mandatoryFilePaths) { extractToDir(zip,mandatoryFilePath,true,moduleRepositoryDir); } for ( String optionalFilePath : optionalFilePaths) { extractToDir(zip,optionalFilePath,false,moduleRepositoryDir); } } finally { zip.close(); } }
Example 3
From project cloudbees-api-client, under directory /cloudbees-api-client/src/main/java/com/cloudbees/upload/.
Source file: ArchiveUtils.java

public static Map<String,Long> getCheckSums(String archiveFile) throws IOException { Map<String,Long> checkSums=new HashMap<String,Long>(); ZipFile zipFile=new ZipFile(archiveFile); Enumeration<? extends ZipEntry> e=zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry=e.nextElement(); checkSums.put(entry.getName(),entry.getCrc()); } return checkSums; }
Example 4
From project droidparts, under directory /extra/src/org/droidparts/util/.
Source file: AppUtils2.java

public long getClassesDexCrc(){ ZipFile zf; try { zf=new ZipFile(ctx.getPackageCodePath()); } catch ( IOException e) { L.e(e); return -1; } ZipEntry ze=zf.getEntry("classes.dex"); long crc=ze.getCrc(); return crc; }
Example 5
From project eclipse.pde.build, under directory /org.eclipse.pde.build/src/org/eclipse/pde/internal/build/site/.
Source file: ProfileManager.java

protected void loadJarJavaProfiles(File bundleLocation){ ZipFile zipFile=null; try { zipFile=new ZipFile(bundleLocation,ZipFile.OPEN_READ); loadJavaProfiles(zipFile); } catch ( IOException e) { } finally { Utils.close(zipFile); } }
Example 6
From project flexmojos, under directory /flexmojos-testing/flexmojos-test-harness/src/test/java/net/flexmojos/oss/tests/concept/.
Source file: CopyMojoTest.java

@Test public void copyFlexResouces() throws Exception { File testDir=getProject("/concept/copy-flex-resources"); test(testDir,"install"); File warFile=new File(testDir,"war/target/copy-war-1.0-SNAPSHOT.war"); Assert.assertTrue(warFile.exists(),"War file not found!"); ZipFile war=new ZipFile(warFile); Assert.assertNotNull(war.getEntry("copy-swf-1.0-SNAPSHOT.swf"),"Swf entry not present at war!"); Assert.assertNotNull(war.getEntry("copy-swf-1.0-SNAPSHOT-module1.swf"),"Swf entry not present at war!"); Assert.assertNotNull(war.getEntry("copy-swf-1.0-SNAPSHOT-module2.swf"),"Swf entry not present at war!"); Assert.assertNotNull(war.getEntry("rsls/framework-3.2.0.3958.swf"),"Rsl entry not present at war!"); }
Example 7
From project guvnorng, under directory /guvnorng-repository/src/main/java/org/drools/repository/.
Source file: ClassUtil.java

private void searchArchive(File archiveFile) throws IOException { ZipFile zip=new ZipFile(archiveFile); Enumeration<? extends ZipEntry> entries=zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry=entries.nextElement(); String resClasspathPath="/" + entry.getName(); if (isToBeAdded(resClasspathPath)) { resourceList.add(resClasspathPath); } } }
Example 8
From project ig-undx, under directory /src/main/java/org/illegalaccess/undx/.
Source file: DalvikToJVM.java

private static boolean isOTA(String z) throws IOException { ZipFile zf=new ZipFile(z); Enumeration<ZipEntry> e=(Enumeration<ZipEntry>)zf.entries(); boolean hasodex=false; for (; e.hasMoreElements(); ) { ZipEntry ze=e.nextElement(); if (ze.getName().endsWith(".odex")) { hasodex=true; } } return hasodex; }
Example 9
From project ISAvalidator-ISAconverter-BIImanager, under directory /val_conv_manager_gui/src/main/java/org/isatools/gui/.
Source file: SelectISATABUI.java

public boolean zipPreviewForInvestigationFile(File f) throws IOException { ZipFile zf=new ZipFile(f); Enumeration<? extends ZipEntry> e=zf.entries(); while (e.hasMoreElements()) { ZipEntry zfEntry=e.nextElement(); System.out.println(zfEntry.getName()); if (zfEntry.getName().toLowerCase().contains("i_")) { return true; } } return false; }
Example 10
From project JGit, under directory /org.spearce.jgit.pgm/src/org/spearce/jgit/pgm/build/.
Source file: JarLinkUtil.java

private void scanJar(final File jarPath) throws IOException { final ZipFile zf=new ZipFile(jarPath); final Enumeration<? extends ZipEntry> e=zf.entries(); while (e.hasMoreElements()) chosenSources.put(e.nextElement().getName(),jarPath); zf.close(); }
Example 11
From project kevoree-library, under directory /kalimucho/org.kevoree.library.kalimucho.kalimuchoNode/src/main/java/platform/ClassManager/.
Source file: JarRessources.java

/** * Returns an Input stream on the a resource in jar file * @param name name of the resource * @return an Input stream on the a resource in jar file * @throws IOException when this resource can't be read in the jar file */ public InputStream getRessourceAsStream(String name) throws IOException { ZipFile zf=new ZipFile(jarFileName); Enumeration<?> e=zf.entries(); while (e.hasMoreElements()) { ZipEntry ze=(ZipEntry)e.nextElement(); if (ze.getName().equals(name)) { return zf.getInputStream(ze); } } return null; }
Example 12
From project libra, under directory /tests/org.eclipse.libra.warproducts.core.test/src/org/eclipse/libra/warproducts/core/test/tests/.
Source file: WARProductExportOperationTest.java

private List extractWarEntriesAsString(File war) throws ZipException, IOException { ZipFile zip=new ZipFile(war); List warEntryList=new ArrayList(); Enumeration entries=zip.entries(); while (entries.hasMoreElements()) { Object nextElement=entries.nextElement(); warEntryList.add(nextElement.toString()); } return warEntryList; }
Example 13
From project logback, under directory /logback-core/src/test/java/ch/qos/logback/core/testUtil/.
Source file: FileToBufferUtil.java

private static void zipFileReadIntoList(File file,List<String> stringList) throws IOException { System.out.println("Reading zip file [" + file + "]"); ZipFile zipFile=new ZipFile(file); Enumeration entries=zipFile.entries(); ZipEntry entry=(ZipEntry)entries.nextElement(); readInputStream(zipFile.getInputStream(entry),stringList); }
Example 14
From project maven-ooo-plugin, under directory /src/test/java/org/openoffice/maven/packager/.
Source file: OxtMojoTest.java

/** * We want to exclude "Readme.txt" from the created OXT file. This is tested here. <br/> NOTE: It is marked as broken because we must first prepare UnoPackage to handle includes/excludes * @throws MojoExecutionException the mojo execution exception * @throws MojoFailureException the mojo failure exception * @throws IllegalAccessException the illegal access exception * @throws ZipException the zip exception * @throws IOException Signals that an I/O exception has occurred. */ public void testExcludes() throws MojoExecutionException, MojoFailureException, IllegalAccessException, ZipException, IOException { String[] excludes={"README.txt"}; setVariableValueToObject(mojo,"excludes",excludes); mojo.execute(); checkArchive(); ZipFile zip=new ZipFile(OXT_FILE); Enumeration<? extends ZipEntry> entries=zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry=entries.nextElement(); if (entry.getName().equals(excludes[0])) { fail(entry.getName() + " should be excluded!"); } } }
Example 15
From project mylyn.context, under directory /org.eclipse.mylyn.context.sdk.java/src/org/eclipse/mylyn/context/sdk/java/.
Source file: WorkspaceSetupHelper.java

public static IJavaProject createJavaPluginProjectFromZip(Object source,String projectName,String zipFileName) throws CoreException, ZipException, IOException { IProject project=createProject(projectName); ZipFile zip=new ZipFile(CommonTestUtil.getFile(source,"testdata/projects/" + zipFileName)); CommonTestUtil.unzip(zip,project.getLocation().toFile()); project.refreshLocal(IResource.DEPTH_INFINITE,null); IJavaProject javaProject=createPluginProject(project); return javaProject; }
Example 16
From project nuxeo-common, under directory /src/main/java/org/nuxeo/common/utils/.
Source file: ZipUtils.java

/** * Unzip directly the entry. The returned InputStream has to be closed. * @return the input stream of the desired entry - has to be closed by thecaller, or null if not found * @param file the source file * @param entryName the entry name that has to be extracted */ public static InputStream getEntryContentAsStream(File file,String entryName) throws IOException { InputStream result=null; ZipFile zip=new ZipFile(file); ZipEntry entry=zip.getEntry(entryName); if (entry != null) { result=zip.getInputStream(entry); } return result; }
Example 17
From project nuxeo-jsf, under directory /nuxeo-platform-webapp-base/src/test/java/org/nuxeo/ecm/webapp/clipboard/.
Source file: ZipUtilsTest.java

@Test public void testExportAllBlobs() throws Exception { DocumentModel heavyFile=createHeavyFile(); List<DocumentModel> documents=new ArrayList<DocumentModel>(); documents.add(heavyFile); DocumentListZipExporter zipExporter=new DocumentListZipExporter(); File file=zipExporter.exportWorklistAsZip(documents,session,true); assertNotNull(file); ZipFile zipFile=new ZipFile(file); assertNotNull(zipFile.getEntry("blob2.raw")); assertNotNull(zipFile.getEntry("blob1.raw")); }
Example 18
From project nuxeo-services, under directory /nuxeo-platform-filemanager-core/src/test/java/org/nuxeo/ecm/platform/filemanager/.
Source file: TestCSVImporter.java

@Test public void testArchiveDetection() throws Exception { createTestDocuments(); ZipFile archive=CSVZipImporter.getArchiveFileIfValid(getArchiveFile()); assertNotNull(archive); archive.close(); }
Example 19
From project nuxeo-tycho-osgi, under directory /nuxeo-common/src/main/java/org/nuxeo/common/utils/.
Source file: ZipUtils.java

/** * Unzip directly the entry. The returned InputStream has to be closed. * @return the input stream of the desired entry - has to be closed by thecaller, or null if not found * @param file the source file * @param entryName the entry name that has to be extracted */ public static InputStream getEntryContentAsStream(File file,String entryName) throws IOException { InputStream result=null; ZipFile zip=new ZipFile(file); ZipEntry entry=zip.getEntry(entryName); if (entry != null) { result=zip.getInputStream(entry); } return result; }
Example 20
From project onebusaway-nyc, under directory /onebusaway-nyc-transit-data-manager/onebusaway-nyc-tdm-webapp/src/test/java/org/onebusaway/nyc/transit_data_manager/api/barcode/.
Source file: ZipFileTesterUtil.java

public int getNumEntriesInZipFile(File file) throws ZipException, IOException { ZipFile zipFile=new ZipFile(file); int numActualEntries=zipFile.size(); zipFile.close(); return numActualEntries; }
Example 21
From project activejdbc, under directory /activejdbc-instrumentation/src/main/java/org/javalite/instrumentation/.
Source file: InstrumentationModelFinder.java

/** * Finds and processes property files inside zip or jar files. * @param file zip or jar file. */ private void processFilePath(File file){ try { if (file.getCanonicalPath().toLowerCase().endsWith(".jar") || file.getCanonicalPath().toLowerCase().endsWith(".zip")) { ZipFile zip=new ZipFile(file); Enumeration<? extends ZipEntry> entries=zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry=entries.nextElement(); if (entry.getName().endsWith("class")) { InputStream zin=zip.getInputStream(entry); classFound(entry.getName().replace(File.separatorChar,'.').substring(0,entry.getName().length() - 6)); zin.close(); } } } } catch ( IOException e) { throw new RuntimeException(e); } catch ( ClassNotFoundException ignore) { } }
Example 22
From project andlytics, under directory /src/com/github/andlyticsproject/io/.
Source file: StatsCsvReaderWriter.java

public static List<String> getImportFileNamesFromZip(String accountName,List<String> packageNames,String zipFilename) throws ServiceExceptoin { List<String> result=new ArrayList<String>(); try { if (!new File(zipFilename).exists()) { return result; } ZipFile zipFile=new ZipFile(zipFilename); Enumeration<? extends ZipEntry> entries=zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry=entries.nextElement(); InputStream in=zipFile.getInputStream(entry); if (isValidFile(accountName,in,packageNames)) { result.add(entry.getName()); } } return result; } catch ( IOException e) { Log.e(TAG,"Error reading zip file: " + e.getMessage()); return new ArrayList<String>(); } }
Example 23
From project android_packages_apps_FileManager, under directory /src/org/openintents/filemanager/util/.
Source file: ExtractManager.java

/** * Recursively extract file or directory */ public boolean extract(File archive,String destinationPath){ try { ZipFile zipfile=new ZipFile(archive); int fileCount=zipfile.size(); for (Enumeration e=zipfile.entries(); e.hasMoreElements(); ) { ZipEntry entry=(ZipEntry)e.nextElement(); unzipEntry(zipfile,entry,destinationPath); isExtracted++; progressDialog.setProgress((isExtracted * 100) / fileCount); } return true; } catch ( Exception e) { Log.e(TAG,"Error while extracting file " + archive,e); return false; } }
Example 24
From project ant4eclipse, under directory /org.ant4eclipse.lib.core/src/org/ant4eclipse/lib/core/util/.
Source file: Utilities.java

/** * Unpacks the content from the supplied zip file into the supplied destination directory. * @todo [11-Dec-2009:KASI] This should be merged with {@link #expandJarFile(JarFile,File)} * @param zipfile The zip file which has to be unpacked. Not <code>null</code> and must be a file. * @param destdir The directory where the content shall be written to. Not <code>null</code>. */ public static final void unpack(File zipfile,File destdir){ Assure.notNull("zipfile",zipfile); Assure.notNull("destdir",destdir); byte[] buffer=new byte[16384]; try { if (!destdir.isAbsolute()) { destdir=destdir.getAbsoluteFile(); } ZipFile zip=new ZipFile(zipfile); Enumeration<? extends ZipEntry> entries=zip.entries(); while (entries.hasMoreElements()) { ZipEntry zentry=entries.nextElement(); if (zentry.isDirectory()) { mkdirs(new File(destdir,zentry.getName())); } else { File destfile=new File(destdir,zentry.getName()); mkdirs(destfile.getParentFile()); copy(zip.getInputStream(zentry),new FileOutputStream(destfile),buffer); } } } catch ( IOException ex) { throw new Ant4EclipseException(ex,CoreExceptionCode.UNPACKING_FAILED,zipfile); } }
Example 25
From project Apertiurm-Androind-app-devlopment, under directory /ApertiumAndroid/src/org/apertium/android/filemanager/.
Source file: FileManager.java

static public void unzip(String zipFile,String to) throws ZipException, IOException { Log.i(TAG,zipFile); int BUFFER=2048; File file=new File(zipFile); ZipFile zip=new ZipFile(file); String newPath=to; Log.i(TAG,"new path =" + newPath); new File(newPath).mkdir(); Enumeration<? extends ZipEntry> zipFileEntries=zip.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry entry=(ZipEntry)zipFileEntries.nextElement(); String currentEntry=entry.getName(); File destFile=new File(newPath,currentEntry); File destinationParent=destFile.getParentFile(); destinationParent.mkdirs(); if (!entry.isDirectory()) { BufferedInputStream is=new BufferedInputStream(zip.getInputStream(entry)); int currentByte; byte data[]=new byte[BUFFER]; FileOutputStream fos=new FileOutputStream(destFile); BufferedOutputStream dest=new BufferedOutputStream(fos,BUFFER); while ((currentByte=is.read(data,0,BUFFER)) != -1) { dest.write(data,0,currentByte); } dest.flush(); dest.close(); is.close(); } } }
Example 26
From project apps-for-android, under directory /CLiCkin2DaBeaT/src/com/google/clickin2dabeat/.
Source file: Unzipper.java

public static void unzip(String fileUrl){ try { String filename=download(fileUrl); ZipFile zip=new ZipFile(filename); Enumeration<? extends ZipEntry> zippedFiles=zip.entries(); while (zippedFiles.hasMoreElements()) { ZipEntry entry=zippedFiles.nextElement(); InputStream is=zip.getInputStream(entry); String name=entry.getName(); File outputFile=new File("/sdcard/c2b/" + name); String outputPath=outputFile.getCanonicalPath(); name=outputPath.substring(outputPath.lastIndexOf("/") + 1); outputPath=outputPath.substring(0,outputPath.lastIndexOf("/")); File outputDir=new File(outputPath); outputDir.mkdirs(); outputFile=new File(outputPath,name); outputFile.createNewFile(); FileOutputStream out=new FileOutputStream(outputFile); byte buf[]=new byte[16384]; do { int numread=is.read(buf); if (numread <= 0) { break; } else { out.write(buf,0,numread); } } while (true); is.close(); out.close(); } File theZipFile=new File(filename); theZipFile.delete(); } catch ( IOException e) { e.printStackTrace(); } }
Example 27
From project as3-commons-jasblocks, under directory /src/main/java/org/as3commons/asblocks/impl/.
Source file: SWCResourceRoot.java

public SWCResourceRoot(File path) throws IOException { this.path=path; ZipFile zip=new ZipFile(path.getAbsolutePath()); try { ZipEntry entry=zip.getEntry(CATALOG_FILENAME); if (entry == null) { throw new IllegalArgumentException("No " + CATALOG_FILENAME + " in swc: "+ path.getAbsolutePath()); } qnames=readCatalog(zip.getInputStream(entry)); } catch ( ParserConfigurationException e) { throw new IOException(e.toString()); } catch ( SAXException e) { throw new IOException(e.toString()); } catch ( XPathExpressionException e) { throw new IOException(e.toString()); } finally { zip.close(); } }
Example 28
From project aviator, under directory /src/main/java/com/googlecode/aviator/asm/optimizer/.
Source file: JarOptimizer.java

static void optimize(final File f) throws IOException { if (f.isDirectory()) { File[] files=f.listFiles(); for (int i=0; i < files.length; ++i) { optimize(files[i]); } } else if (f.getName().endsWith(".jar")) { File g=new File(f.getParentFile(),f.getName() + ".new"); ZipFile zf=new ZipFile(f); ZipOutputStream out=new ZipOutputStream(new FileOutputStream(g)); Enumeration e=zf.entries(); byte[] buf=new byte[10000]; while (e.hasMoreElements()) { ZipEntry ze=(ZipEntry)e.nextElement(); if (ze.isDirectory()) { continue; } out.putNextEntry(ze); InputStream is=zf.getInputStream(ze); int n; do { n=is.read(buf,0,buf.length); if (n != -1) { out.write(buf,0,n); } } while (n != -1); out.closeEntry(); } out.close(); zf.close(); f.delete(); g.renameTo(f); } }
Example 29
From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/processor/.
Source file: CaptchaProcessor.java

/** * Loads captcha. */ private static void loadCaptchas(){ LOGGER.info("Loading captchas...."); try { final URL captchaURL=SoloServletListener.class.getClassLoader().getResource("captcha.zip"); final ZipFile zipFile=new ZipFile(captchaURL.getFile()); final Set<String> imageNames=new HashSet<String>(); for (int row=0; row < MAX_CAPTCHA_ROW; row++) { for (int column=0; column < MAX_CAPTCHA_COLUM; column++) { imageNames.add(row + "/" + column+ ".png"); } } final ImageService imageService=ImageServiceFactory.getImageService(); final Iterator<String> i=imageNames.iterator(); while (i.hasNext()) { final String imageName=i.next(); final ZipEntry zipEntry=zipFile.getEntry(imageName); final BufferedInputStream bufferedInputStream=new BufferedInputStream(zipFile.getInputStream(zipEntry)); final byte[] captchaCharData=new byte[bufferedInputStream.available()]; bufferedInputStream.read(captchaCharData); bufferedInputStream.close(); final Image captchaChar=imageService.makeImage(captchaCharData); CAPTCHAS.put(imageName,captchaChar); } zipFile.close(); } catch ( final Exception e) { LOGGER.severe("Can not load captchs!"); throw new IllegalStateException(e); } LOGGER.info("Loaded captch images"); }
Example 30
From project behemoth, under directory /gate/src/test/java/com/digitalpebble/behemoth/gate/.
Source file: GATEProcessorTest.java

/** * Unzips the argument into the temp directory and returns the unzipped location. */ public static File unzip(File inputZip){ File rootDir=null; try { BufferedOutputStream dest=null; BufferedInputStream is=null; ZipEntry entry; ZipFile zipfile=new ZipFile(inputZip); String zipname=inputZip.getName().replaceAll("\\.zip",""); File test=File.createTempFile("aaa","aaa"); String tempDir=test.getParent(); test.delete(); rootDir=new File(tempDir,zipname); rootDir.mkdir(); Enumeration e=zipfile.entries(); while (e.hasMoreElements()) { entry=(ZipEntry)e.nextElement(); is=new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[]=new byte[BUFFER]; File target=new File(rootDir,entry.getName()); if (entry.getName().endsWith("/")) { target.mkdir(); continue; } FileOutputStream fos=new FileOutputStream(target); dest=new BufferedOutputStream(fos,BUFFER); while ((count=is.read(data,0,BUFFER)) != -1) { dest.write(data,0,count); } dest.flush(); dest.close(); is.close(); } } catch ( Exception e) { e.printStackTrace(); } return rootDir; }
Example 31
From project bpelunit, under directory /net.bpelunit.framework.control.deploy.activevos9/src/main/java/net/bpelunit/util/.
Source file: ZipUtil.java

public static void unzipFile(File zip,File dir) throws IOException { InputStream in=null; OutputStream out=null; ZipFile zipFile=new ZipFile(zip); Enumeration<? extends ZipEntry> entries=zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry=entries.nextElement(); if (!entry.getName().endsWith("/")) { File unzippedFile=new File(dir,entry.getName()); try { in=zipFile.getInputStream(entry); unzippedFile.getParentFile().mkdirs(); out=new FileOutputStream(unzippedFile); IOUtils.copy(in,out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } }
Example 32
From project bundlemaker, under directory /main/org.bundlemaker.core/src/org/bundlemaker/core/resource/.
Source file: ResourceKey.java

/** * {@inheritDoc} */ public long getTimestamp(){ if (_timestamp == -1) { if (getRoot().endsWith(".jar") || getRoot().endsWith(".zip")) { try { ZipFile zipFile=new ZipFile(new File(getRoot())); ZipEntry zipEntry=zipFile.getEntry(getPath()); setTimeStamp(zipEntry); } catch ( ZipException e) { e.printStackTrace(); } catch ( IOException e) { e.printStackTrace(); } } else { setTimeStamp(new File(getRoot(),getPath())); } } return _timestamp; }
Example 33
From project c24-spring, under directory /c24-spring-batch/src/test/java/biz/c24/io/spring/batch/writer/.
Source file: C24ItemWriterTests.java

@Test public void testZipFileWrite() throws Exception { File outputFile=File.createTempFile("ItemWriterTest-",".csv.zip"); outputFile.deleteOnExit(); String outputFileName=outputFile.getAbsolutePath(); C24ItemWriter itemWriter=new C24ItemWriter(); itemWriter.setSink(new TextualSink()); itemWriter.setWriterSource(new ZipFileWriterSource()); itemWriter.setup(getStepExecution(outputFileName)); itemWriter.write(employees); itemWriter.cleanup(); ZipFile zipFile=new ZipFile(outputFileName); Enumeration<? extends ZipEntry> entries=zipFile.entries(); assertNotNull(entries); assertTrue(entries.hasMoreElements()); ZipEntry entry=entries.nextElement(); assertFalse(entry.getName().contains(System.getProperty("file.separator"))); assertFalse(entry.getName().endsWith(".zip")); assertFalse(entries.hasMoreElements()); try { compareCsv(zipFile.getInputStream(entry),employees); } finally { if (zipFile != null) { zipFile.close(); } } }
Example 34
From project ceylon-ide-eclipse, under directory /plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/editor/.
Source file: SourceArchiveDocumentProvider.java

private String getZipEntryContents(IURIEditorInput uriEditorInput,String encoding){ String path=uriEditorInput.getURI().getPath(); int lastColonIdx=path.lastIndexOf('!'); if (lastColonIdx < 0) return null; String jarPath=path.substring(0,lastColonIdx); String entryPath=path.substring(lastColonIdx + 2); try { ZipFile zipFile=new ZipFile(new File(jarPath)); try { ZipEntry entry=zipFile.getEntry(entryPath); return encoding == null ? readStreamContents(zipFile.getInputStream(entry)) : readStreamContents(zipFile.getInputStream(entry),encoding); } finally { zipFile.close(); } } catch ( IOException e) { e.printStackTrace(); return null; } }
Example 35
From project ceylon-runtime, under directory /bootstrap/src/main/java/ceylon/modules/bootstrap/loader/.
Source file: DistributionModuleLoader.java

/** * Unzip bootstrap distrubution if not already present. * @param dir the unzip destination * @param zip the zipped bootstrap distribution * @return unziped root directory */ protected File unzipDistribution(File dir,File zip){ File exploded=new File(dir,BOOTSTRAP_DISTRIBUTION + "-exploded"); if (exploded.exists()) { if (forceBootstrapUpdate() == false) return exploded; else delete(exploded); } try { final ZipFile zipFile=new ZipFile(zip); try { final Enumeration<? extends ZipEntry> entries=zipFile.entries(); while (entries.hasMoreElements()) { final ZipEntry ze=entries.nextElement(); final File file=new File(exploded,ze.getName()); if (ze.isDirectory()) { if (file.mkdirs() == false) throw new IllegalArgumentException("Cannot create dir: " + file); } else { final FileOutputStream fos=new FileOutputStream(file); copyStream(zipFile.getInputStream(ze),fos); } } } finally { zipFile.close(); } } catch ( IOException e) { throw new IllegalArgumentException(e); } return exploded; }
Example 36
From project ChkBugReport, under directory /src/com/sonyericsson/chkbugreport/.
Source file: Main.java

protected int loadReportFrom(Module report,String fileName,int mode) throws IOException { for ( Extension ext : mExtensions) { int ret=ext.loadReportFrom(report,fileName,mode); if (ret != RET_NOP) { return ret; } } File f=new File(fileName); InputStream is=null; if (!f.exists()) { onPrint(1,TYPE_ERR,"File " + fileName + " does not exists!"); return RET_FALSE; } try { ZipFile zip=new ZipFile(fileName); Enumeration<? extends ZipEntry> entries=zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry=entries.nextElement(); if (!entry.isDirectory()) { if (!mSilent) System.out.println("Trying to parse zip entry: " + entry.getName() + " ..."); if (loadFrom(report,fileName,zip.getInputStream(entry))) { return RET_TRUE; } } } } catch ( IOException e) { } try { is=new FileInputStream(f); } catch ( IOException e) { onPrint(1,TYPE_ERR,"Error opening file " + fileName + "!"); return RET_FALSE; } if (!loadFrom(report,fileName,is)) { return RET_FALSE; } return RET_TRUE; }
Example 37
From project Clotho-Core, under directory /ClothoProject/ClothoCore/src/org/clothocore/api/core/.
Source file: Collator.java

/** * Determines if the file is valid .clo file * @param files * @return */ public static boolean isValidCloFile(File[] files){ if (files[0].getName().contains(".clo")) { try { ZipFile zipfile=new ZipFile(files[0]); } catch ( ZipException ex) { return false; } catch ( IOException ex) { return false; } return true; } else { return false; } }
Example 38
From project cloudify, under directory /CLI/src/main/java/org/cloudifysource/shell/commands/.
Source file: TestRecipe.java

/** * Unzips a given file. * @param inputFile The zip file to extract * @return The new folder, containing the extracted content of the zip file * @throws IOException Reporting a failure to extract the zipped file or close it afterwards */ private static File unzipFile(final File inputFile) throws IOException { ZipFile zipFile=null; try { final File baseDir=TestRecipe.createTempDir(); zipFile=new ZipFile(inputFile); final Enumeration<? extends ZipEntry> entries=zipFile.entries(); while (entries.hasMoreElements()) { final ZipEntry entry=entries.nextElement(); if (entry.isDirectory()) { logger.fine("Extracting directory: " + entry.getName()); final File dir=new File(baseDir,entry.getName()); dir.mkdir(); continue; } logger.finer("Extracting file: " + entry.getName()); final File file=new File(baseDir,entry.getName()); file.getParentFile().mkdirs(); ServiceReader.copyInputStream(zipFile.getInputStream(entry),new BufferedOutputStream(new FileOutputStream(file))); } return baseDir; } finally { if (zipFile != null) { try { zipFile.close(); } catch ( final IOException e) { logger.log(Level.SEVERE,"Failed to close zip file after unzipping zip contents",e); } } } }
Example 39
From project core_1, under directory /common/src/main/java/org/switchyard/common/type/classpath/.
Source file: ClasspathScanner.java

private void handleArchive(File file) throws IOException { if (_logger.isDebugEnabled()) { _logger.debug("Scanning archive: " + file.getAbsolutePath()); } ZipFile zip=new ZipFile(file); Enumeration<? extends ZipEntry> entries=zip.entries(); while (entries.hasMoreElements()) { if (!_filter.continueScanning()) { break; } ZipEntry entry=entries.nextElement(); String name=entry.getName(); _filter.filter(name); } }
Example 40
From project cpp-maven-plugins, under directory /cpp-compiler-maven-plugin/src/main/java/com/ericsson/tools/cpp/compiler/dependencies/.
Source file: DependencyExtractor.java

private void extractDependency(final DependencyIdentifier dep) throws MojoExecutionException { int extractedFiles=0; try { final ZipFile zipFile=new ZipFile(dep.getArtifact().getFile()); final Enumeration<? extends ZipEntry> entriesEnum=zipFile.entries(); while (entriesEnum.hasMoreElements()) { final ZipEntry entry=entriesEnum.nextElement(); if (entryMatchesDependency(entry,dep)) { extractEntry(entry,zipFile,dep.getDestination()); extractedFiles++; } } zipFile.close(); } catch ( IOException e) { throw new MojoExecutionException("Failed to extract " + dep.getArtifact() + ".",e); } if (extractedFiles > 0) log.debug("Extracted " + extractedFiles + " files from \""+ dep+ "\" to "+ dep.getDestination()); }
Example 41
From project dawn-isencia, under directory /com.isencia.passerelle.commons/src/main/java/com/isencia/util/.
Source file: FileLocator.java

private static NamedDataInputStream locateInZipFile(String zipFileName,String fileName,boolean wantClass,boolean buffered) throws ZipException, IOException { ZipFile zf; ZipEntry ze; zf=new ZipFile(zipFileName); if (zf == null) return null; String zeName=wantClass ? fileName.replace('.','/') + ".class" : fileName; ze=zf.getEntry(zeName); if (ze == null) { zf.close(); zf=null; return null; } InputStream istream=zf.getInputStream(ze); if (buffered) istream=new BufferedInputStream(istream); return new NamedDataInputStream(istream,zipFileName + '(' + zeName+ ')',true); }
Example 42
From project discovery, under directory /src/main/java/com/tacitknowledge/util/discovery/.
Source file: ArchiveResourceListSource.java

/** * @see ResourceListSourceSupport#getResources(String) */ protected String[] getResources(String basePath){ String root=(basePath == null) ? "" : basePath; root=root.replace('\\','/'); List resourceNames=new ArrayList(); List jars=getJars(); for (Iterator i=jars.iterator(); i.hasNext(); ) { String jarName=(String)i.next(); try { ZipFile file=new ZipFile(jarName); resourceNames.addAll(getResources(file,root)); } catch ( IOException e) { } } return (String[])resourceNames.toArray(new String[resourceNames.size()]); }
Example 43
From project dolphin, under directory /dolphinmaple/src/com/tan/util/.
Source file: ZipUtils.java

/** * ?????????? * @param zipFile ?????? * @param folderPath ???????????? * @throws IOException ??????????????? */ public static void upZipFile(File zipFile,String folderPath) throws IOException { ZipFile zf=new ZipFile(zipFile); for (Enumeration entries=zf.entries(); entries.hasMoreElements(); ) { ZipEntry entry=((ZipEntry)entries.nextElement()); InputStream in=zf.getInputStream(entry); OutputStream out=new FileOutputStream(folderPath + File.separator + entry.getName()); byte buffer[]=new byte[BUFF_SIZE]; int realLength; while ((realLength=in.read(buffer)) > 0) { out.write(buffer,0,realLength); } in.close(); out.close(); } }
Example 44
From project EasySOA, under directory /easysoa-registry/easysoa-registry-api/easysoa-registry-api-frascati/src/main/java/org/easysoa/registry/frascati/.
Source file: FileUtils.java

/** * Unzips the given jar in a temp file and returns its files' URLs Inspired from AssemblyFactoryManager.processContribution() (though doesn't add it to the classloader or parse composites) TODO move to util TODO better : delete temp files afterwards (or mark them so) OR rather use jar:url ? * @param SCA zip or jar * @return unzipped composites URLs * @throws ManagerException */ public static final Set<URL> unzipAndGetFileUrls(File file){ try { ZipFile zipFile=new ZipFile(file); final String folder=zipFile.getName().substring(zipFile.getName().lastIndexOf(File.separator),zipFile.getName().length() - ".zip".length()); Set<URL> fileURLSet=new HashSet<URL>(); final String tempDir=System.getProperty("java.io.tmpdir") + File.separator + folder+ File.separator; Enumeration<? extends ZipEntry> entries=zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry=entries.nextElement(); log.info("ZIP entry: " + entry.getName()); if (entry.isDirectory()) { log.info("create directory : " + tempDir + entry.getName()); new File(tempDir,entry.getName()).mkdirs(); } else { File f=new File(tempDir,File.separator + entry.getName()); int idx=entry.getName().lastIndexOf(File.separator); if (idx != -1) { String tmp=entry.getName().substring(0,idx); log.info("create directory : " + tempDir + tmp); new File(tempDir,tmp).mkdirs(); } copy(zipFile.getInputStream(entry),new BufferedOutputStream(new FileOutputStream(f))); fileURLSet.add(f.toURI().toURL()); } } return fileURLSet; } catch ( IOException e) { log.error(e); return new HashSet<URL>(0); } }
Example 45
From project eclipse-integration-cloudfoundry, under directory /org.cloudfoundry.ide.eclipse.server.core/src/org/cloudfoundry/ide/eclipse/internal/server/core/.
Source file: ModuleResourceApplicationArchive.java

public void generatePartialWarFile(Set<String> knownResourceNames){ Iterable<Entry> localEntries=getEntries(); Map<String,AbstractModuleResourceEntryAdapter> missingChangedEntries=new HashMap<String,AbstractModuleResourceEntryAdapter>(); Set<IModuleResource> missingChangedResources=new HashSet<IModuleResource>(); for ( Entry entry : localEntries) { if (entry.isDirectory() || !knownResourceNames.contains(entry.getName())) { missingChangedEntries.put(entry.getName(),(AbstractModuleResourceEntryAdapter)entry); missingChangedResources.add(((AbstractModuleResourceEntryAdapter)entry).getResource()); } } try { File partialWar=CloudUtil.createWarFile(getModuleResources(),getModule(),missingChangedResources,null); if (partialWar.exists()) { fileName=partialWar.getName(); ZipFile zipPartialWar=new ZipFile(partialWar); Enumeration<? extends ZipEntry> zipEntries=zipPartialWar.entries(); List<Entry> toDeploy=new ArrayList<ApplicationArchive.Entry>(); while (zipEntries.hasMoreElements()) { ZipEntry zipEntry=zipEntries.nextElement(); AbstractModuleResourceEntryAdapter archiveEntry=missingChangedEntries.get(zipEntry.getName()); if (archiveEntry != null) { DeployedResourceEntry deployedResourcesEntry=archiveEntry instanceof ZipModuleFileEntryAdapter ? ((ZipModuleFileEntryAdapter)archiveEntry).getDeployedResourcesEntry() : null; toDeploy.add(new PartialZipEntryAdapter(deployedResourcesEntry,zipEntry,zipPartialWar)); } } entries=toDeploy; } } catch ( CoreException e) { CloudFoundryPlugin.logError(e); } catch ( ZipException e) { CloudFoundryPlugin.logError(e); } catch ( IOException e) { CloudFoundryPlugin.logError(e); } }
Example 46
From project enclojure, under directory /org-enclojure-ide/src/main/java/org/enclojure/ide/asm/optimizer/.
Source file: JarOptimizer.java

static void optimize(final File f) throws IOException { if (f.isDirectory()) { File[] files=f.listFiles(); for (int i=0; i < files.length; ++i) { optimize(files[i]); } } else if (f.getName().endsWith(".jar")) { File g=new File(f.getParentFile(),f.getName() + ".new"); ZipFile zf=new ZipFile(f); ZipOutputStream out=new ZipOutputStream(new FileOutputStream(g)); Enumeration e=zf.entries(); byte[] buf=new byte[10000]; while (e.hasMoreElements()) { ZipEntry ze=(ZipEntry)e.nextElement(); if (ze.isDirectory()) { continue; } out.putNextEntry(ze); if (ze.getName().endsWith(".class")) { ClassReader cr=new ClassReader(zf.getInputStream(ze)); cr.accept(new ClassVerifier(),0); } InputStream is=zf.getInputStream(ze); int n; do { n=is.read(buf,0,buf.length); if (n != -1) { out.write(buf,0,n); } } while (n != -1); out.closeEntry(); } out.close(); zf.close(); f.delete(); g.renameTo(f); } }
Example 47
From project erjang, under directory /src/main/java/erjang/driver/efile/.
Source file: ClassPathResource.java

private static void listJarURL(Set<String> res,URL url) throws IOException { String path=url.getPath(); int bang=path.indexOf('!'); String jar=path.substring("file:".length(),bang); String elm=path.substring(bang + 2); ZipFile z=new ZipFile(jar); Enumeration<? extends ZipEntry> ents=z.entries(); while (ents.hasMoreElements()) { ZipEntry ent=ents.nextElement(); if (ent.getName().startsWith(elm)) { add(res,elm,ent.getName()); } } z.close(); }
Example 48
From project fairy, under directory /fairy-core/src/main/java/com/mewmew/fairy/v1/spell/.
Source file: Spells.java

static void addSpells(File f) throws ClassNotFoundException, IllegalAccessException, InstantiationException, IOException { if (f.isDirectory()) { for ( File file : f.listFiles()) { addSpells(file); } } else if (f.isFile()) { if (f.getName().endsWith(".class") && !f.getName().contains("$") && f.getPath().contains("book")) { String c=f.getName().substring(0,f.getName().length() - ".class".length()); addSpell("com.mewmew.fairy.v1.book" + "." + c); } else if (f.getName().endsWith(".jar") && f.exists()) { ZipFile zip=new ZipFile(f); for (Enumeration em=zip.entries(); em.hasMoreElements(); ) { ZipEntry ze=(ZipEntry)em.nextElement(); String c=ze.getName(); if (c.contains("book") && c.endsWith(".class") && !c.contains("$")) { String name=c.substring(0,c.length() - ".class".length()).replaceAll("/","."); addSpell(name); } } } } }
Example 49
From project fakereplace, under directory /plugins/maven/src/main/java/org/fakereplace/maven/.
Source file: FakereplaceMojo.java

@Override public void execute() throws MojoExecutionException, MojoFailureException { if (project.getArtifact() == null || project.getArtifact().getFile() == null) { throw new IllegalStateException("You must run mvn package before the fakereplace plugin runs, e.g. mvn package fakereplace:fakereplace"); } final String fileName=project.getArtifact().getFile().getName(); ZipFile zipFile=null; try { zipFile=new ZipFile(project.getArtifact().getFile()); final File file=new File(path); final Map<String,ClassData> classes=new HashMap<String,ClassData>(); final Map<String,ResourceData> resources=new HashMap<String,ResourceData>(); handleClassesDirectory(file,file,classes); handleArtifact(zipFile,resources); FakeReplaceClient.run(fileName,classes,resources); } catch ( Throwable t) { getLog().error("Error running fakereplace: ",t); } finally { if (zipFile != null) { try { zipFile.close(); } catch ( IOException e) { e.printStackTrace(); } } } }
Example 50
From project filemanager, under directory /FileManager/src/org/openintents/filemanager/util/.
Source file: ExtractManager.java

/** * Recursively extract file or directory */ public boolean extract(File archive,String destinationPath){ try { ZipFile zipfile=new ZipFile(archive); int fileCount=zipfile.size(); for (Enumeration e=zipfile.entries(); e.hasMoreElements(); ) { ZipEntry entry=(ZipEntry)e.nextElement(); unzipEntry(zipfile,entry,destinationPath); isExtracted++; progressDialog.setProgress((isExtracted * 100) / fileCount); } return true; } catch ( Exception e) { Log.e(TAG,"Error while extracting file " + archive,e); return false; } }
Example 51
From project fitnesse, under directory /src/fitnesse/wiki/zip/.
Source file: ZipFileVersionsController.java

public PageData getRevisionData(final FileSystemPage page,final String label){ final String filename=getFileSystemPath(page) + "/" + label+ ".zip"; final File file=new File(filename); if (!file.exists()) { throw new NoSuchVersionException("There is no version '" + label + "'"); } ZipFile zipFile=null; try { final PageData data=new PageData(page); zipFile=new ZipFile(file); loadVersionContent(zipFile,data); loadVersionAttributes(zipFile,data); data.addVersions(loadVersions(page)); return data; } catch ( Throwable th) { throw new RuntimeException(th); } finally { try { if (zipFile != null) { zipFile.close(); } } catch ( IOException e) { e.printStackTrace(); } } }
Example 52
From project FML, under directory /common/cpw/mods/fml/common/.
Source file: FMLModContainer.java

public Properties searchForVersionProperties(){ try { FMLLog.fine("Attempting to load the file version.properties from %s to locate a version number for %s",getSource().getName(),getModId()); Properties version=null; if (getSource().isFile()) { ZipFile source=new ZipFile(getSource()); ZipEntry versionFile=source.getEntry("version.properties"); if (versionFile != null) { version=new Properties(); version.load(source.getInputStream(versionFile)); } source.close(); } else if (getSource().isDirectory()) { File propsFile=new File(getSource(),"version.properties"); if (propsFile.exists() && propsFile.isFile()) { version=new Properties(); FileInputStream fis=new FileInputStream(propsFile); version.load(fis); fis.close(); } } return version; } catch ( Exception e) { Throwables.propagateIfPossible(e); FMLLog.fine("Failed to find a usable version.properties file"); return null; } }
Example 53
From project freemind, under directory /freemind/freemind/extensions/.
Source file: ImportWizard.java

/** * Adds the classes from the supplied Zip file to the class list. * @param classList the Vector to add the classes to * @param classPathFile the File to scan as a zip file */ public void addClassesFromZip(Vector classList,File classPathFile){ try { ZipFile zipFile=new ZipFile(classPathFile); Enumeration enumeration=zipFile.entries(); while (enumeration.hasMoreElements()) { ZipEntry zipEntry=(ZipEntry)enumeration.nextElement(); String current=zipEntry.getName(); if (isInteresting(current)) { current=current.substring(0,current.length() - lookFor.length()); classList.addElement(current); } } } catch ( Exception ex) { freemind.main.Resources.getInstance().logException(ex,"Problem opening " + classPathFile + " with zip."); } }
Example 54
From project GenericKnimeNodes, under directory /com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/nodes/io/exporter/.
Source file: MimeFileExporterNodeModel.java

/** * {@inheritDoc} */ @Override protected void loadInternals(final File internDir,final ExecutionMonitor exec) throws IOException, CanceledExecutionException { ZipFile zip=new ZipFile(new File(internDir,"loadeddata")); @SuppressWarnings("unchecked") Enumeration<ZipEntry> entries=(Enumeration<ZipEntry>)zip.entries(); int BUFFSIZE=2048; byte[] BUFFER=new byte[BUFFSIZE]; while (entries.hasMoreElements()) { ZipEntry entry=(ZipEntry)entries.nextElement(); if (entry.getName().equals("rawdata.bin")) { int size=(int)entry.getSize(); byte[] data=new byte[size]; InputStream in=zip.getInputStream(entry); int len; int totlen=0; while ((len=in.read(BUFFER,0,BUFFSIZE)) >= 0) { System.arraycopy(BUFFER,0,data,totlen,len); totlen+=len; } this.data=new String(data); } } zip.close(); }
Example 55
From project Gmote, under directory /gmoteupdater/src/org/gmote/server/updater/.
Source file: FileExtractor.java

@SuppressWarnings("unchecked") public static void unzipArchive(File archive,File outputDir,UpdateTask updateTask) throws IOException { ZipFile zipfile=new ZipFile(archive); updateTask.setProgressBarSize(zipfile.size()); int count=0; for (Enumeration e=zipfile.entries(); e.hasMoreElements(); ) { ZipEntry entry=(ZipEntry)e.nextElement(); unzipEntry(zipfile,entry,outputDir); count++; if (count % 10 == 0) { updateTask.setProgressForTask(count); } } updateTask.setProgressForTask(zipfile.size()); updateTask.updateStatusLabel("abc " + zipfile.size()); }
Example 56
From project GraphLab, under directory /src/graphlab/platform/extension/.
Source file: ExtensionClassLoader.java

/** * this part of code has get from: http://www.devx.com/getHelpOn/10MinuteSolution/20447 * @param zipFileName */ public static void unZip(String zipFileName,String destDir){ System.out.println(zipFileName); Enumeration entries; ZipFile zipFile; try { zipFile=new ZipFile(zipFileName); entries=zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry=(ZipEntry)entries.nextElement(); if (entry.isDirectory()) { (new File(destDir + File.separator + entry.getName())).mkdirs(); continue; } System.out.println("Extracting file: " + destDir + entry.getName()); copyInputStream(zipFile.getInputStream(entry),new BufferedOutputStream(new FileOutputStream(destDir + File.separator + entry.getName()))); } zipFile.close(); } catch ( IOException ioe) { System.err.println("Unhandled exception:"); ioe.printStackTrace(); return; } }
Example 57
From project griffon, under directory /subprojects/griffon-wrapper/src/main/java/org/gradle/wrapper/.
Source file: Install.java

public void unzip(File zip,File dest) throws IOException { Enumeration entries; ZipFile zipFile; zipFile=new ZipFile(zip); entries=zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry=(ZipEntry)entries.nextElement(); if (entry.isDirectory()) { (new File(dest,entry.getName())).mkdirs(); continue; } copyInputStream(zipFile.getInputStream(entry),new BufferedOutputStream(new FileOutputStream(new File(dest,entry.getName())))); } zipFile.close(); }
Example 58
From project guj.com.br, under directory /src/br/com/caelum/guj/util/.
Source file: FileUtil.java

@SuppressWarnings("unchecked") public static void extractZipAndCopyFilesToDisk(File zip,String filesPath,String articlePath){ Enumeration entries=null; ZipFile zipFile=null; try { zipFile=new ZipFile(zip); entries=zipFile.entries(); File directory=new File(filesPath + articlePath); File[] listFiles=directory.listFiles(); if (listFiles != null) { for ( File file : listFiles) { file.delete(); } } while (entries.hasMoreElements()) { ZipEntry entry=(ZipEntry)entries.nextElement(); String name=entry.getName(); if (name.lastIndexOf(".gif") != -1 || name.lastIndexOf(".png") != -1 || name.lastIndexOf(".jpg") != -1) { directory.mkdirs(); File file=new File(directory,entry.getName()); file.createNewFile(); copyFileToDisk(zipFile.getInputStream(entry),new BufferedOutputStream(new FileOutputStream(file))); } } zipFile.close(); } catch ( IOException ioe) { ioe.printStackTrace(); } }
Example 59
From project jabox, under directory /bts-jtrac/src/main/java/org/jabox/its/jtrac/.
Source file: JtracServer.java

public static File retrieveJtracWar(final File jtracZip){ try { ZipFile zip=new ZipFile(jtracZip); ZipEntry entry=zip.getEntry("jtrac/jtrac.war"); InputStream is=zip.getInputStream(entry); BufferedInputStream bin=null; BufferedOutputStream bout=null; bin=new BufferedInputStream(is); File jtracWar=File.createTempFile("jtrac",".war"); jtracWar.deleteOnExit(); bout=new BufferedOutputStream(new FileOutputStream(jtracWar)); while (true) { int datum=bin.read(); if (datum == -1) { break; } bout.write(datum); } bout.flush(); return jtracWar; } catch ( ZipException e) { LOGGER.error("Zip Exception thrown",e); } catch ( IOException e) { LOGGER.error("IO Exception thrown",e); } return null; }
Example 60
From project jangaroo-tools, under directory /jangaroo/jangaroo-compiler/src/main/java/net/jangaroo/jooc/input/.
Source file: ZipFileInputSource.java

/** * Create an InputSource directory from the given zip or jar file, providing a "union view" over the zip file with all entries with paths relative to the given root directories * @param file a zip or jar file * @param rootDirs a list of directories to accept as roots (e.g. ["", "META-INF/joo-api"], in lookup order * @throws IOException if an IO error occurs */ public ZipFileInputSource(final File file,String[] rootDirs) throws IOException { super(); this.file=file; this.zipFile=new ZipFile(file); this.rootDirs=rootDirs.clone(); final Enumeration<? extends ZipEntry> zipEntryEnum=zipFile.entries(); while (zipEntryEnum.hasMoreElements()) { ZipEntry entry=zipEntryEnum.nextElement(); final String relativePath=getRelativePath(entry.getName()); if (relativePath != null && !entries.containsKey(relativePath)) { this.entries.put(relativePath,new ZipEntryInputSource(this,entry,relativePath)); } } }
Example 61
From project jbosgi-framework, under directory /core/src/main/java/org/jboss/osgi/framework/internal/.
Source file: JDKPaths.java

private static void processClassPathItem(final String classPath,final Set<String> jarSet,final Set<String> pathSet){ if (classPath == null) return; int s=0, e; do { e=classPath.indexOf(File.pathSeparatorChar,s); String item=e == -1 ? classPath.substring(s) : classPath.substring(s,e); if (!jarSet.contains(item)) { final File file=new File(item); if (file.isDirectory()) { processDirectory0(pathSet,file); } else { try { final ZipFile zipFile=new ZipFile(file); try { final Enumeration<? extends ZipEntry> entries=zipFile.entries(); while (entries.hasMoreElements()) { final ZipEntry entry=entries.nextElement(); final String name=entry.getName(); final int lastSlash=name.lastIndexOf('/'); if (lastSlash != -1) { pathSet.add(name.substring(0,lastSlash)); } } } finally { zipFile.close(); } } catch ( IOException ex) { } } } s=e + 1; } while (e != -1); }
Example 62
From project jboss-modules, under directory /src/main/java/org/jboss/modules/.
Source file: JDKPaths.java

private static void processClassPathItem(final String classPath,final Set<String> jarSet,final Set<String> pathSet){ if (classPath == null) return; int s=0, e; do { e=classPath.indexOf(File.pathSeparatorChar,s); String item=e == -1 ? classPath.substring(s) : classPath.substring(s,e); if (!jarSet.contains(item)) { final File file=new File(item); if (file.isDirectory()) { processDirectory0(pathSet,file); } else { try { final ZipFile zipFile=new ZipFile(file); try { final Enumeration<? extends ZipEntry> entries=zipFile.entries(); while (entries.hasMoreElements()) { final ZipEntry entry=entries.nextElement(); final String name=entry.getName(); final int lastSlash=name.lastIndexOf('/'); if (lastSlash != -1) { pathSet.add(name.substring(0,lastSlash)); } } } finally { zipFile.close(); } } catch ( IOException ex) { } } } s=e + 1; } while (e != -1); }
Example 63
From project jeppetto, under directory /jeppetto-test-support/src/main/java/org/iternine/jeppetto/testsupport/db/.
Source file: MongoDatabase.java

private File findMongod() throws IOException { if (mongod != null) { return mongod; } File mongoArchive=findMongoArchive(); if (!mongoArchive.exists()) { throw new RuntimeException("Mongo archive not found at: " + mongoArchive.getAbsolutePath()); } logger.debug(String.format("Extracting mongod from %s%n",mongoArchive.getAbsolutePath())); ZipFile zip=new ZipFile(mongoArchive); ZipEntry mongodEntry=zip.getEntry("bin/mongod"); InputStream input=zip.getInputStream(mongodEntry); mongod=new File(System.getProperty("java.io.tmpdir","/tmp"),"mongod-bin/mongod"); if (!mongod.getParentFile().mkdirs()) { logger.warn("Could not create parent dir for mongod, either a permission issue or dir was left behind by previous process."); } copy(input,mongod); zip.close(); logger.debug(String.format("Copied mongod binary to %s%n",mongod.getAbsolutePath())); return mongod; }
Example 64
public void open() throws ZipException, IOException { if (zipFile != null) { throw new IllegalStateException("ZipFile is already open"); } zipFile=new ZipFile(file); }
Example 65
/** * Parse the given Java class file and return an object that represents the contained data, i.e., constants, methods, fields and commands. A <em>ClassFormatException</em> is raised, if the file is not a valid .class file. (This does not include verification of the byte code as it is performed by the java interpreter). * @return Class object representing the parsed class file * @throws IOException * @throws ClassFormatException */ public JavaClass parse() throws IOException, ClassFormatException { ZipFile zip=null; try { if (fileOwned) { if (is_zip) { zip=new ZipFile(zip_file); ZipEntry entry=zip.getEntry(file_name); file=new DataInputStream(new BufferedInputStream(zip.getInputStream(entry),BUFSIZE)); } else { file=new DataInputStream(new BufferedInputStream(new FileInputStream(file_name),BUFSIZE)); } } readID(); readVersion(); readConstantPool(); readClassInfo(); readInterfaces(); readFields(); readMethods(); readAttributes(); } finally { if (fileOwned) { file.close(); if (zip != null) { zip.close(); } } } return new JavaClass(class_name_index,superclass_name_index,file_name,major,minor,access_flags,constant_pool,interfaces,fields,methods,attributes,is_zip ? JavaClass.ZIP : JavaClass.FILE); }
Example 66
From project jsf-test, under directory /stage/src/main/java/org/jboss/test/faces/.
Source file: ApplicationServer.java

/** * Internal method used by the {@link #addResourcesFromDirectory(String,URL)} to process 'jar' protocol. * @param resource URL to the any object in the source directory. * @param baseDirectory target virtual directory. */ protected void addResourcesFromJar(String resourcePath,URL resource){ try { String jarPath=resource.getPath(); String entry=jarPath.substring(jarPath.indexOf('!') + 2); jarPath=jarPath.substring(0,jarPath.indexOf('!')); File file=new File(new URI(jarPath)); ZipFile zip=new ZipFile(file); Enumeration<? extends ZipEntry> entries=zip.entries(); entry=entry.substring(0,entry.lastIndexOf('/') + 1); while (entries.hasMoreElements()) { ZipEntry zzz=entries.nextElement(); if (zzz.getName().startsWith(entry) && !zzz.isDirectory()) { String relativePath=zzz.getName().substring(entry.length()); URL relativeResource=new URL(resource,relativePath); addResource(resourcePath + "/" + relativePath,relativeResource); } } } catch ( IOException e) { throw new TestException("Error read Jar content",e); } catch ( URISyntaxException e) { throw new TestException(e); } }
Example 67
From project jsfunit, under directory /jboss-jsfunit-ant/src/main/java/org/jboss/jsfunit/ant/.
Source file: JSFUnitWarTask.java

/** * This method gets called if we are dealing with an actual archive and not an exploded archive. This archive is exploded to a temporary directory so that it can be altered in the same manner as if we were dealing with an expldoded archive. */ private void JSFUnitWar(){ try { File tmpDir=File.createTempFile("jsfunitwartask",""); tmpDir.delete(); tmpDir.mkdir(); ZipFile zip=new ZipFile(srcfile); File explodedArchive=Utils.explodeArchive(zip,tmpDir); WebXml webXml=getWebXml(explodedArchive); editWebXml(webXml); writeWebXml(explodedArchive,webXml); addLibs(explodedArchive); autoAddLibs(explodedArchive); addClasses(explodedArchive); Utils.archive(explodedArchive,destfile); } catch ( Exception e) { log(e.getMessage(),Project.MSG_ERR); e.printStackTrace(); } }
Example 68
From project jsword, under directory /src/main/java/org/crosswire/common/util/.
Source file: IOUtil.java

/** * Unpack a zip file to a given directory. Honor the paths as given in the zip file. * @param file The zip file to download * @param destdir The directory to unpack up * @throws IOException If there is an file error */ public static void unpackZip(File file,File destdir) throws IOException { byte[] dbuf=new byte[4096]; ZipFile zf=null; try { zf=new ZipFile(file); Enumeration<? extends ZipEntry> entries=zf.entries(); while (entries.hasMoreElements()) { ZipEntry entry=entries.nextElement(); String entrypath=entry.getName(); File entryFile=new File(destdir,entrypath); File parentDir=entryFile.getParentFile(); if (!parentDir.isDirectory()) { if (!parentDir.mkdirs()) { throw new MalformedURLException(JSMsg.gettext("The URL {0} could not be created as a directory.",parentDir.toString())); } } if (!entry.isDirectory()) { URI child=NetUtil.getURI(entryFile); OutputStream dataOut=NetUtil.getOutputStream(child); InputStream dataIn=zf.getInputStream(entry); while (true) { int count=dataIn.read(dbuf); if (count == -1) { break; } dataOut.write(dbuf,0,count); } dataOut.close(); } } } finally { IOUtil.close(zf); } }
Example 69
From project juzu, under directory /core/src/main/java/juzu/impl/fs/spi/classloader/.
Source file: URLCache.java

private static void add(Trie<String,URL> root,URL url) throws IOException { if ("file".equals(url.getProtocol())) { try { File f=new File(url.toURI()); ZipFile jarFile=new ZipFile(f); for (Enumeration<? extends ZipEntry> en=jarFile.entries(); en.hasMoreElements(); ) { ZipEntry entry=en.nextElement(); add(root,url,entry); } } catch ( URISyntaxException e1) { throw new IOException("Could not access jar file " + url,e1); } } else { ZipInputStream in=new ZipInputStream(url.openStream()); try { for (ZipEntry jarEntry=in.getNextEntry(); jarEntry != null; jarEntry=in.getNextEntry()) { add(root,url,jarEntry); } } finally { Tools.safeClose(in); } } }
Example 70
From project koneki.ldt, under directory /plugins/org.eclipse.koneki.ldt/src/org/eclipse/koneki/ldt/core/internal/buildpath/.
Source file: LuaExecutionEnvironmentManager.java

public static LuaExecutionEnvironment getExecutionEnvironmentFromCompressedFile(final String filePath) throws CoreException { ZipFile zipFile=null; String manifestString=null; try { zipFile=new ZipFile(filePath); final Enumeration<? extends ZipEntry> zipEntries=zipFile.entries(); while (zipEntries.hasMoreElements()) { final ZipEntry zipEntry=zipEntries.nextElement(); if ((!zipEntry.getName().contains("/")) && zipEntry.getName().endsWith(LuaExecutionEnvironmentConstants.MANIFEST_EXTENSION)) { if (manifestString != null) { throwException(MessageFormat.format("Invalid Execution Environment : more than one \"{0}\" file.",LuaExecutionEnvironmentConstants.MANIFEST_EXTENSION),null,IStatus.ERROR); } final InputStream input=zipFile.getInputStream(zipEntry); manifestString=IOUtils.toString(input); } } } catch ( IOException e) { throwException(MessageFormat.format("Unable to extract manifest from zip file {0}",filePath),e,IStatus.ERROR); } finally { if (zipFile != null) try { zipFile.close(); } catch ( IOException e) { Activator.logWarning(MessageFormat.format("Unable to close zip file {0}",filePath),e); } } if (manifestString == null) { throwException(MessageFormat.format("No manifest \"{0}\" file found",LuaExecutionEnvironmentConstants.MANIFEST_EXTENSION),null,IStatus.ERROR); } return getLuaExecutionEnvironmentFromManifest(manifestString,null); }
Example 71
From project KoNLP, under directory /inst/javasrc/kr/pe/freesearch/KoNLP/.
Source file: KoNLPUtil.java

public static String[] readZipDic(String zipPath,String dicPath) throws IOException { BufferedReader bin=null; ZipFile zip=null; List<String> list=null; try { zip=new ZipFile(zipPath); ZipEntry entry=zip.getEntry(dicPath); bin=new BufferedReader(new InputStreamReader(zip.getInputStream(entry))); String str=""; list=new ArrayList<String>(); while ((str=bin.readLine()) != null) { String[] parsed=str.trim().split("\t"); if (parsed.length != 2 || !parsed[1].matches("[a-zA-Z]+")) { continue; } for ( String chunk : parsed) { list.add(chunk); } } } catch ( IOException e) { e.printStackTrace(); if (bin != null) bin.close(); if (zip != null) zip.close(); } bin.close(); zip.close(); return list.toArray(new String[0]); }
Example 72
From project Lily, under directory /tools/lily-kauri-plugin/src/main/java/org/lilyproject/tools/mavenplugin/kauridepresolver/.
Source file: KauriProjectClasspath.java

public Set<Artifact> getClassPathArtifacts(Artifact moduleArtifact,String entryPath) throws MojoExecutionException { ZipFile zipFile=null; InputStream is=null; Document classLoaderDocument; try { zipFile=new ZipFile(moduleArtifact.getFile()); ZipEntry zipEntry=zipFile.getEntry(entryPath); if (zipEntry == null) { log.debug("No " + entryPath + " found in "+ moduleArtifact); return Collections.emptySet(); } else { is=zipFile.getInputStream(zipEntry); classLoaderDocument=parse(is); } } catch ( Exception e) { throw new MojoExecutionException("Error reading " + entryPath + " from "+ moduleArtifact,e); } finally { if (is != null) try { is.close(); } catch ( Exception e) { } if (zipFile != null) try { zipFile.close(); } catch ( Exception e) { } } return getArtifacts(classLoaderDocument,"/classloader/classpath/artifact","classloader.xml from module " + moduleArtifact); }
Example 73
private ZipFile zip(){ if (zip == null) { try { zip=new ZipFile(zipPath.file()); } catch ( IOException e) { throw new LimelightException(e); } } return zip; }
Example 74
From project m2e-core-tests, under directory /org.eclipse.m2e.pr.tests/src/org/eclipse/m2e/pr/internal/data/.
Source file: DataGathererTest.java

public void testRobustnessAgainstFailingGatherers() throws Exception { DataGatherer gatherer=new DataGatherer(null,null,null,null,null,null); List<File> files=gatherer.gather(null,EnumSet.allOf(Data.class),new NullProgressMonitor()); for ( File tmpFile : files) { tmpFile.deleteOnExit(); } assertEquals(1,files.size()); File tmpFile=files.get(0); assertTrue(tmpFile.isFile()); ZipFile zip=new ZipFile(tmpFile); try { assertNotNull(zip.getEntry("pr/status-0.txt")); assertNotNull(zip.getEntry("pr/status-1.txt")); } finally { zip.close(); } }
Example 75
From project m2eclipse-wtp, under directory /org.maven.ide.eclipse.wtp.overlay/src/org/maven/ide/eclipse/wtp/overlay/utilities/.
Source file: CompressionUtil.java

/** * Unzips the platform formatted zip file to specified folder * @param zipFile The platform formatted zip file * @param projectFolderFile The folder where to unzip the archive * @param monitor Monitor to display progress and/or cancel operation * @throws IOException * @throws FileNotFoundException * @throws InterruptedException */ public static void unzip(File archive,File projectFolderFile,IProgressMonitor monitor) throws IOException, FileNotFoundException, InterruptedException { initialize(projectFolderFile); ZipFile zipFile=new ZipFile(archive); Enumeration<ZipEntry> e=(Enumeration<ZipEntry>)zipFile.entries(); if (monitor == null) { monitor=new NullProgressMonitor(); } while (e.hasMoreElements()) { ZipEntry zipEntry=(ZipEntry)e.nextElement(); File file=new File(projectFolderFile,zipEntry.getName()); if (!zipEntry.isDirectory()) { File parentFile=file.getParentFile(); if (null != parentFile && !parentFile.exists()) { parentFile.mkdirs(); } InputStream is=null; OutputStream os=null; try { is=zipFile.getInputStream(zipEntry); os=new FileOutputStream(file); byte[] buffer=new byte[BUFFER]; while (true) { int len=is.read(buffer); if (len < 0) break; os.write(buffer,0,len); } } finally { FileUtils.close(is); FileUtils.close(os); } } monitor.worked(1); if (monitor.isCanceled()) { throw new InterruptedException(" unzipping " + archive.getAbsolutePath() + " to "+ projectFolderFile.getAbsolutePath()+ " was interrupted"); } } }
Example 76
From project maven-android-plugin, under directory /src/main/java/com/jayway/maven/plugins/android/phase09package/.
Source file: 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; } String zn=ze.getName(); if (metaInfOnly) { if (!zn.startsWith("META-INF/")) { continue; } if (this.extractDuplicates && !entries.add(zn)) { continue; } if (!metaInfMatches(zn)) { continue; } } zos.putNextEntry(new ZipEntry(zn)); InputStream is=zin.getInputStream(ze); copyStreamWithoutClosing(is,zos); is.close(); zos.closeEntry(); } zin.close(); }
Example 77
From project maven-shared, under directory /maven-verifier/src/main/java/org/apache/maven/it/util/.
Source file: ResourceExtractor.java

private static void extractResourcePathFromJar(Class cl,File jarFile,String resourcePath,File dest) throws IOException { ZipFile z=new ZipFile(jarFile,ZipFile.OPEN_READ); String zipStyleResourcePath=resourcePath.substring(1) + "/"; ZipEntry ze=z.getEntry(zipStyleResourcePath); if (ze != null) { for (Enumeration entries=z.entries(); entries.hasMoreElements(); ) { ze=(ZipEntry)entries.nextElement(); if (ze.getName().startsWith(zipStyleResourcePath)) { String relativePath=ze.getName().substring(zipStyleResourcePath.length()); File destFile=new File(dest,relativePath); if (ze.isDirectory()) { destFile.mkdirs(); } else { FileOutputStream fos=new FileOutputStream(destFile); try { IOUtil.copy(z.getInputStream(ze),fos); } finally { IOUtil.close(fos); } } } } } else { FileOutputStream fos=new FileOutputStream(dest); try { IOUtil.copy(cl.getResourceAsStream(resourcePath),fos); } finally { IOUtil.close(fos); } } }
Example 78
protected static void unzip(){ String path=MZLOptions.RootDir; String ZFilePath=path + MZLOptions.zip_package; String ExPath=path; Vector zipEntries=new Vector(); try { ZipFile zf=new ZipFile(ZFilePath); Enumeration en=zf.entries(); while (en.hasMoreElements()) zipEntries.addElement((ZipEntry)en.nextElement()); for (int i=0; i < zipEntries.size(); i++) { ZipEntry ze=(ZipEntry)zipEntries.elementAt(i); extractFromZip(ZFilePath,ExPath,ze.getName(),zf,ze); } zf.close(); } catch ( Exception ex) { print(ex.toString()); } new File(ZFilePath).delete(); }
Example 79
From project medsavant, under directory /MedSavantClient/src/org/ut/biolab/medsavant/plugin/.
Source file: PluginController.java

public void getGeneManiaData(){ URL pathToGMData=NetworkUtils.getKnownGoodURL("http://genomesavant.com/serve/data/genemania/gmdata.zip"); try { File data=RemoteFileCache.getCacheFile(pathToGMData); System.out.println("data is" + data.getAbsolutePath()); ZipFile zipData=new ZipFile(data.getAbsolutePath()); Enumeration entries=zipData.entries(); while (entries.hasMoreElements()) { ZipEntry entry=(ZipEntry)entries.nextElement(); if (entry.isDirectory()) { (new File(entry.getName())).mkdirs(); continue; } System.err.println("Extracting file: " + entry.getName()); copyInputStream(zipData.getInputStream(entry),new BufferedOutputStream(new FileOutputStream(entry.getName()))); } zipData.close(); } catch ( IOException ex) { Logger.getLogger(PluginController.class.getName()).log(Level.SEVERE,null,ex); } }
Example 80
From project mididuino, under directory /editor/app/src/processing/app/debug/.
Source file: Compiler.java

static private void packageListFromZip(String filename,Hashtable<String,Object> table){ try { ZipFile file=new ZipFile(filename); Enumeration entries=file.entries(); while (entries.hasMoreElements()) { ZipEntry entry=(ZipEntry)entries.nextElement(); if (!entry.isDirectory()) { String name=entry.getName(); if (name.endsWith(".class")) { int slash=name.lastIndexOf('/'); if (slash == -1) { continue; } String pname=name.substring(0,slash); if (table.get(pname) == null) { table.put(pname,new Object()); } } } } } catch ( IOException e) { System.err.println("Ignoring " + filename + " ("+ e.getMessage()+ ")"); } }
Example 81
From project Minequest-2-API, under directory /src/main/java/com/theminequest/MineQuest/API/Utils/.
Source file: ZipUtils.java

public static void unzip(String file,String destinationdir){ try { BufferedOutputStream dest=null; BufferedInputStream is=null; ZipEntry entry; ZipFile zipfile=new ZipFile(file); Enumeration<? extends ZipEntry> e=zipfile.entries(); while (e.hasMoreElements()) { entry=(ZipEntry)e.nextElement(); is=new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[]=new byte[BUFFER]; FileOutputStream fos=new FileOutputStream(destinationdir + File.separator + entry.getName()); dest=new BufferedOutputStream(fos,BUFFER); while ((count=is.read(data,0,BUFFER)) != -1) { dest.write(data,0,count); } dest.flush(); dest.close(); is.close(); } } catch ( Exception e) { e.printStackTrace(); } }
Example 82
From project mkgmap, under directory /src/uk/me/parabola/mkgmap/reader/osm/boundary/.
Source file: BoundaryUtil.java

/** * return the available *.bnd files in dirName, either dirName has to a directory or a zip file. * @param dirName : path to a directory or a zip file containing the *.bnd files * @return */ public static List<String> getBoundaryDirContent(String dirName){ List<String> names=new ArrayList<String>(); File boundaryDir=new File(dirName); if (!boundaryDir.exists()) log.error("boundary directory/zip does not exist: " + dirName); else { if (boundaryDir.isDirectory()) { String[] allNames=boundaryDir.list(); for ( String name : allNames) { if (name.endsWith(".bnd")) names.add(name); } } else if (boundaryDir.getName().endsWith(".zip")) { try { ZipFile zipFile=new ZipFile(boundaryDir); Enumeration<? extends ZipEntry> entries=zipFile.entries(); boolean isFlat=true; while (entries.hasMoreElements()) { ZipEntry entry=entries.nextElement(); if (entry.isDirectory()) { isFlat=false; } if (entry.getName().endsWith(".bnd")) names.add(entry.getName()); } zipFile.close(); if (!isFlat) { log.error("boundary zip file contains directories. Files in directories will be ignored." + dirName); } } catch ( IOException ioe) { System.err.println("Unhandled exception:"); ioe.printStackTrace(); } } } return names; }
Example 83
From project mob, under directory /com.netappsid.mob.jndi/src/org/apache/naming/resources/.
Source file: WARDirContext.java

/** * Set the document root. * @param docBase The new document root * @exception IllegalArgumentException if the specified value is not supported by this implementation * @exception IllegalArgumentException if this would create a malformed URL */ public void setDocBase(String docBase){ if (docBase == null) throw new IllegalArgumentException(sm.getString("resources.null")); if (!(docBase.endsWith(".war"))) throw new IllegalArgumentException(sm.getString("warResources.notWar")); File base=new File(docBase); if (!base.exists() || !base.canRead() || base.isDirectory()) throw new IllegalArgumentException(sm.getString("warResources.invalidWar",docBase)); try { this.base=new ZipFile(base); } catch ( Exception e) { throw new IllegalArgumentException(sm.getString("warResources.invalidWar",e.getMessage())); } super.setDocBase(docBase); loadEntries(); }
Example 84
From project MoreMaterials, under directory /src/main/java/net/morematerials/manager/.
Source file: SmpManager.java

private void loadPackage(File file) throws Exception { HashMap<String,YamlConfiguration> materials=new HashMap<String,YamlConfiguration>(); ZipFile smpFile=new ZipFile(file); Enumeration<? extends ZipEntry> entries=smpFile.entries(); ZipEntry entry; YamlConfiguration yml; String smpName=this.plugin.getUtilsManager().getName(file.getName()); while (entries.hasMoreElements()) { entry=entries.nextElement(); if (entry.getName().endsWith(".yml")) { yml=new YamlConfiguration(); yml.load(smpFile.getInputStream(entry)); materials.put(entry.getName().substring(0,entry.getName().lastIndexOf(".")),yml); } else if (entry.getName().endsWith(".shape") || entry.getName().endsWith(".obj") || entry.getName().endsWith(".ply")) { String matName=this.plugin.getUtilsManager().getName(entry.getName()); this.shapesMap.put(smpName + "_" + matName,new CustomShapeTemplate(this.plugin,smpFile,entry)); } else { this.plugin.getAssetManager().addAsset(smpFile,entry); } } smpFile.close(); for ( String matName : materials.keySet()) { if (!matName.matches("^[0-9@]+$")) { this.createMaterial(smpName,matName,materials.get(matName),smpFile); } } this.storedConfigs.put(smpName,materials); }
Example 85
From project mylyn.incubator, under directory /org.eclipse.mylyn.sandbox.tests/src/org/eclipse/mylyn/monitor/tests/.
Source file: MonitorPackagingTest.java

public void testCreateUploadPackage() throws IOException, InterruptedException { UiUsageMonitorPlugin.getDefault().getInteractionLogger().stopMonitoring(); File monitorFile=UiUsageMonitorPlugin.getDefault().getMonitorLogFile(); List<File> files=new ArrayList<File>(); files.add(monitorFile); File zipFile=new File(monitorFile.getParentFile(),"usage-upload.zip"); zipFile.deleteOnExit(); ZipFileUtil.createZipFile(zipFile,files); UiUsageMonitorPlugin.getDefault().getInteractionLogger().startMonitoring(); Thread.sleep(1000); ZipFile zf=new ZipFile(zipFile); try { int numEntries=0; for (Enumeration<? extends ZipEntry> entries=zf.entries(); entries.hasMoreElements(); ) { numEntries++; String zipEntryName=((ZipEntry)entries.nextElement()).getName(); assertTrue("Unknown Entry: " + zipEntryName,zipEntryName.compareTo(monitorFile.getName()) == 0); } assertEquals("Results not correct size",1,numEntries); } finally { zf.close(); } zipFile.delete(); }
Example 86
From project nexus-p2-repository-plugin, under directory /src/main/java/org/sonatype/nexus/plugins/p2/repository/metadata/.
Source file: MetadataUtils.java

private static Xpp3Dom parseJarItem(final StorageFileItem item,final String jarPath) throws IOException, XmlPullParserException { final File file=File.createTempFile("p2file","zip"); try { final InputStream is=item.getInputStream(); try { FileUtils.copyStreamToFile(new RawInputStreamFacade(is),file); final ZipFile z=new ZipFile(file); try { final ZipEntry ze=z.getEntry(jarPath); if (ze == null) { throw new LocalStorageException("Corrupted P2 metadata jar " + jarPath); } final InputStream zis=z.getInputStream(ze); return Xpp3DomBuilder.build(new XmlStreamReader(zis)); } finally { z.close(); } } finally { IOUtil.close(is); } } finally { file.delete(); } }
Example 87
From project nuxeo-webengine, under directory /nuxeo-webengine-core/src/main/java/.
Source file: Archetype.java

public static void main(String[] args) throws Exception { if (args.length == 0) { System.err.println("Syntax Error: you must specify a project template name"); } int k=0; String tpl=args[k]; if ("-b".equals(tpl)) { batchMode=true; if (args.length < 2) { System.err.println("Syntax Error: you must specify a project template name"); } tpl=args[++k]; } k++; archive=new File(tpl); if (args.length > k) { outDir=args[k]; } ZipFile zip=new ZipFile(archive); ZipEntry entry=zip.getEntry("archetype.xml"); if (entry == null) { System.err.println("Invalid archetype zip."); System.exit(1); } InputStream in=new BufferedInputStream(zip.getInputStream(entry)); Document doc=load(in); zip.close(); processArchetype(doc,System.getProperties()); }
Example 88
From project OpenMEAP, under directory /server-side/openmeap-shared-serverside/src/com/openmeap/model/.
Source file: ArchiveFileHelper.java

/** * @param archive * @param zipFile * @param events * @return TRUE if the file successfully is exploded, FALSE otherwise. */ public static Boolean unzipFile(ModelManager modelManager,FileOperationManager fileManager,ApplicationArchive archive,File zipFile,List<ProcessingEvent> events){ try { GlobalSettings settings=modelManager.getGlobalSettings(); File dest=archive.getExplodedPath(settings.getTemporaryStoragePath()); if (dest.exists()) { fileManager.delete(dest.getAbsolutePath()); } ZipFile file=null; try { file=new ZipFile(zipFile); fileManager.unzipFile(file,archive.getHash()); } finally { file.close(); } return Boolean.TRUE; } catch ( Exception e) { logger.error("An exception occurred unzipping the archive to the viewing location: {}",e); events.add(new MessagesEvent(String.format("An exception occurred unzipping the archive to the viewing location: %s",e.getMessage()))); } return Boolean.FALSE; }
Example 89
From project org.eclipse.scout.builder, under directory /org.eclipse.scout.releng.ant/test/org/eclipse/scout/releng/ant/archive/.
Source file: TestCreateDropInZip.java

@Test public void testTask() throws Exception { CreateDropInZip task=new CreateDropInZip(); task.setOutputDir(new File(m_workingDir + "/output")); Project p=new Project(); task.setProject(p); FileSet set1=new FileSet(); set1.setDir(new File(m_workingDir + "/input/sdkFeature")); set1.createInclude().setName("**/**"); task.addFileset(set1); FileSet set2=new FileSet(); set2.setDir(new File(m_workingDir + "/input/rtFeature")); set2.createInclude().setName("**/**"); task.addFileset(set2); task.setZipName("blubber"); task.setMilestone("M4"); task.setTimestamp("201001211203"); task.setVersionMajor("3"); task.setVersionMinor("5"); task.setVersionMicro("0"); task.execute(); File file=new File(m_workingDir + "/output/blubber-3.5.0M4-201001211203.zip"); Assert.assertTrue(file.exists()); Assert.assertTrue(file.isFile()); ZipFile zipFile=new ZipFile(file); int i=0; Enumeration<? extends ZipEntry> entries=zipFile.entries(); while (entries.hasMoreElements()) { entries.nextElement(); i++; } Assert.assertEquals(i,20); }
Example 90
From project org.openscada.external, under directory /org.openscada.external.jOpenDocument/src/org/jopendocument/io/.
Source file: ODTContentExtractor.java

public void load() throws IOException { ZipFile zFile=new ZipFile(this.file); ZipEntry e=zFile.getEntry("content.xml"); InputStream in=zFile.getInputStream(e); BufferedReader r=new BufferedReader(new InputStreamReader(in)); final char[] chars=new char[(int)e.getSize()]; r.read(chars); StringBuilder builder=new StringBuilder(); boolean add=false; final int length=chars.length; for (int i=0; i < length; i++) { char c=chars[i]; if (c == '<') { add=false; } else if (c == '>') { add=true; } else if (add) { builder.append(c); } } in.close(); zFile.close(); this.text=builder.toString(); }
Example 91
From project droid-comic-viewer, under directory /src/net/robotmedia/acv/comic/.
Source file: ZipComic.java

private void init(String comicPath){ try { this.setZip(new ZipFile(comicPath)); Enumeration<? extends ZipEntry> entries=mZip.entries(); while (entries.hasMoreElements()) { ZipEntry entry=entries.nextElement(); if (!entry.isDirectory()) { this.processEntry(entry); } } } catch ( Exception e) { e.printStackTrace(); error(); } { ArrayList<String> orderedScreenKeys=new ArrayList<String>(unorderedScreens.keySet()); screens=new ArrayList<String>(orderedScreenKeys.size()); for (int i=0; i < orderedScreenKeys.size(); i++) { screens.add(unorderedScreens.get(orderedScreenKeys.get(i))); } } }
Example 92
From project Eclipse, under directory /com.mobilesorcery.sdk.importproject/src/com/mobilesorcery/sdk/importproject/.
Source file: MoSyncWizardProjectsImportPage.java

/** * Answer a handle to the zip file currently specified as being the source. Return null if this file does not exist or is not of valid format. */ private ZipFile getSpecifiedZipSourceFile(String fileName){ if (fileName.length() == 0) { return null; } try { return new ZipFile(fileName); } catch ( ZipException e) { displayErrorDialog(DataTransferMessages.ZipImport_badFormat); } catch ( IOException e) { displayErrorDialog(DataTransferMessages.ZipImport_couldNotRead); } archivePathField.setFocus(); return null; }
Example 93
From project encog-java-core, under directory /src/main/java/org/encog/ml/data/buffer/codec/.
Source file: ExcelCODEC.java

/** * {@inheritDoc} */ @Override public void prepareRead(){ try { this.readZipFile=new ZipFile(this.file); final Enumeration<? extends ZipEntry> entries=this.readZipFile.entries(); this.entry=null; while (entries.hasMoreElements()) { final ZipEntry e=entries.nextElement(); if (e.getName().equals("xl/worksheets/sheet1.xml")) { this.entry=e; } } if (this.entry == null) { this.readZipFile.close(); this.readZipFile=null; throw new BufferedDataError("Could not find worksheet."); } final InputStream is=this.readZipFile.getInputStream(this.entry); this.xmlIn=new ReadXML(is); } catch ( final ZipException e) { throw new BufferedDataError("Not a valid Excel file."); } catch ( final IOException e) { throw new BufferedDataError(e); } }
Example 94
From project karaf, under directory /deployer/kar/src/main/java/org/apache/karaf/deployer/kar/.
Source file: KarArtifactInstaller.java

public boolean canHandle(File file){ if (file.isFile() && file.getName().endsWith(KAR_SUFFIX)) { LOGGER.info("Found a .kar file to deploy."); return true; } else if (file.isFile() && file.getName().endsWith(ZIP_SUFFIX)) { LOGGER.debug("Found a .zip file to deploy; checking contents to see if it's a Karaf archive."); try { if (new ZipFile(file).getEntry("META-INF/KARAF.MF") != null) { LOGGER.info("Found a Karaf archive with .zip prefix; will deploy."); return true; } } catch ( Exception e) { LOGGER.warn("Problem extracting zip file '{}'; ignoring.",file.getName(),e); } } return false; }
Example 95
From project LateralGM, under directory /org/lateralgm/resources/library/.
Source file: LibManager.java

/** * Retrieves all libs/lgls in a given location (directory or zip file). The files are stored in order and already opened for convenience. */ public static TreeMap<String,InputStream> getLibs(File loc){ if (loc.exists()) { try { if (loc.isDirectory()) return getDirLibs(loc); if (!passFilter(loc.getName())) return getZipLibs(new ZipFile(loc)); TreeMap<String,InputStream> map=new TreeMap<String,InputStream>(); map.put(loc.getName(),new FileInputStream(loc)); return map; } catch ( IOException e) { e.printStackTrace(); } } return null; }
Example 96
From project bndtools, under directory /bndtools.jareditor/src/bndtools/jareditor/internal/.
Source file: JAREntryPart.java

protected static void readAsText(ZipFile zipFile,ZipEntry entry,String encoding,Writer out,long limit,IProgressMonitor monitor) throws IOException { SubMonitor progress=createProgressMonitor(entry,limit,monitor); boolean limitReached=false; InputStream stream=zipFile.getInputStream(entry); try { long total=0; byte[] buffer=new byte[1024]; while (true) { if (progress.isCanceled()) return; int bytesRead=stream.read(buffer,0,1024); if (bytesRead < 0) break; String string=new String(buffer,0,bytesRead,encoding); out.write(string); total+=bytesRead; progress.worked(bytesRead); if (limit >= 0 && total >= limit) { limitReached=true; return; } } } finally { if (limitReached) { out.write("\nLimit of " + (limit >> 10) + "Kb reached, the rest of the entry is not shown."); } stream.close(); } }
Example 97
From project cdk, under directory /maven-resources-plugin/src/main/java/org/richfaces/cdk/vfs/zip/.
Source file: ZipVFSFile.java

public ZipVFSFile(ZipFile zipFile,ZipNode zipNode,String relativePath){ super(); this.zipFile=zipFile; this.zipNode=zipNode; this.relativePath=relativePath; }
Example 98
From project CIShell, under directory /core/org.cishell.utilities/src/org/cishell/utilities/.
Source file: ZipUtilities.java

public static File readFileFromZipFile(ZipEntry entry,ZipFile zipFile) throws IOException { long size=entry.getSize(); if (size > 0) { BufferedInputStream reader=new BufferedInputStream(zipFile.getInputStream(entry)); String fileName=new File(entry.getName()).getName(); File outputFile=FileUtilities.createTemporaryFileInDefaultTemporaryDirectory(fileName,"tmp"); BufferedOutputStream output=new BufferedOutputStream(new FileOutputStream(outputFile),BUFFER_SIZE); byte readBytes[]=new byte[BUFFER_SIZE]; int readByteCount; while ((readByteCount=reader.read(readBytes,0,BUFFER_SIZE)) != -1) { output.write(readBytes,0,readByteCount); } output.close(); return outputFile; } else { return null; } }
Example 99
From project dawn-common, under directory /org.dawb.common.util/src/org/dawb/common/util/io/.
Source file: IOUtils.java

/** * Unconditionally close a <code>ZipFile</code>. and optinally log errors * @param input A (possibly null) Reader */ public static void close(ZipFile input,String msg){ if (input == null) { logger.error("ZipFile is null",msg,1); return; } try { input.close(); } catch ( IOException ioe) { logger.error("Cannot close stream",ioe); } }
Example 100
From project dawn-isenciaui, under directory /com.isencia.passerelle.workbench.model/src/main/java/com/isencia/passerelle/workbench/model/utils/.
Source file: IOUtils.java

/** * Unconditionally close a <code>ZipFile</code>. and optinally log errors * @param input A (possibly null) Reader */ public static void close(ZipFile input,String msg){ if (input == null) { logger.error("ZipFile is null",msg,1); return; } try { input.close(); } catch ( IOException ioe) { logger.error("Cannot close stream",ioe); } }
Example 101
From project gda-common, under directory /uk.ac.gda.common/src/uk/ac/gda/util/io/.
Source file: IOUtils.java

/** * Unconditionally close a <code>ZipFile</code>. and optionally log errors * @param input A (possibly null) Reader */ public static void close(ZipFile input,String msg){ if (input == null) { logger.error("ZipFile is null",msg,1); return; } try { input.close(); } catch ( IOException ioe) { logger.error("Cannot close stream",ioe); } }
Example 102
From project grails-ide, under directory /org.grails.ide.eclipse.groovy.debug.tests/test plugin/org/eclipse/jdt/debug/testplugin/.
Source file: JavaProjectHelper.java

/** * Imports files from the specified zip to the specified destination * @param srcZipFile * @param destPath * @param monitor * @throws InvocationTargetException */ private static void importFilesFromZip(ZipFile srcZipFile,IPath destPath,IProgressMonitor monitor) throws InvocationTargetException { ZipFileStructureProvider structureProvider=new ZipFileStructureProvider(srcZipFile); try { ImportOperation op=new ImportOperation(destPath,structureProvider.getRoot(),structureProvider,new ImportOverwriteQuery()); op.run(monitor); } catch ( InterruptedException e) { } }
Example 103
From project jboss-as-maven-plugin, under directory /src/main/java/org/jboss/as/plugin/common/.
Source file: Streams.java

public static void safeClose(final ZipFile file){ if (file != null) try { file.close(); } catch ( Exception e) { } }
Example 104
From project jboss-vfs, under directory /src/main/java/org/jboss/vfs/.
Source file: VFSUtils.java

/** * Safely close some resource without throwing an exception. Any exception will be logged at TRACE level. * @param zipFile the resource */ public static void safeClose(final ZipFile zipFile){ if (zipFile != null) try { zipFile.close(); } catch ( Exception e) { log.trace("Failed to close resource",e); } }
Example 105
From project maven3-support, under directory /maven3-plugin/src/main/java/org/hudsonci/maven/plugin/builder/internal/.
Source file: MavenInstallationValidator.java

private String getMavenVersionFromProperties(){ try { FilePath[] jars=getHome().child("lib").list("maven-core-*.jar, maven-*-uber.jar"); if (jars != null && jars.length > 0) { FilePath jar=jars[0]; Properties mavenProperties=jar.act(new FilePath.FileCallable<Properties>(){ private static final long serialVersionUID=1L; public Properties invoke( File file, VirtualChannel channel) throws IOException { ZipFile zipFile=new ZipFile(file); try { ZipEntry zipEntry=zipFile.getEntry("org/apache/maven/messages/build.properties"); if (zipEntry == null) { zipEntry=zipFile.getEntry("META-INF/maven/org.apache.maven/maven-core/pom.properties"); if (zipEntry == null) { return null; } } InputStream is=zipFile.getInputStream(zipEntry); Properties properties=new Properties(); properties.load(is); return properties; } finally { zipFile.close(); } } } ); if (muxlog.isTraceEnabled()) { muxlog.trace("Maven installation properties: {}",mavenProperties); } if (mavenProperties != null) { return mavenProperties.getProperty("version"); } } } catch ( Exception e) { } return null; }
Example 106
From project MimeUtil, under directory /src/main/java/eu/medsea/util/.
Source file: ZipJarUtil.java

/** * Get all entries from a zip or jar file. Ignores directories * @param zipFile * @return collection of Strings representing the entries in the zip or jar file * @throws ZipException * @throws IOException */ public static Collection getEntries(ZipFile zipFile) throws ZipException, IOException { Collection entries=new ArrayList(); Enumeration e=zipFile.entries(); while (e.hasMoreElements()) { ZipEntry ze=(ZipEntry)e.nextElement(); if (!ze.isDirectory()) { entries.add(ze.getName()); } } return entries; }
Example 107
From project Opal, under directory /opal-system/src/main/java/com/lyndir/lhunath/opal/system/util/.
Source file: IOUtils.java

/** * A sane way of retrieving an entry from a {@link ZipFile} based on its /-delimited path name. * @param zipFile The {@link ZipFile} to retrieve the entry for. * @param zippedName The /-delimited pathname of the entry. * @return The {@link ZipEntry} for the pathname or <code>null</code> if none was present. */ @Nullable public static ZipEntry getZipEntry(final ZipFile zipFile,final CharSequence zippedName){ Enumeration<? extends ZipEntry> entries=zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry=entries.nextElement(); if (PATH_SEPARATORS.matcher(entry.getName()).replaceAll("/").equals(PATH_SEPARATORS.matcher(zippedName).replaceAll("/"))) return entry; } return null; }
Example 108
From project OpenTripPlanner, under directory /opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/model/.
Source file: GtfsBundle.java

public CsvInputSource getCsvInputSource() throws IOException { if (csvInputSource == null) { if (path != null) { csvInputSource=new ZipFileCsvInputSource(new ZipFile(path)); } else if (url != null) { DownloadableGtfsInputSource isrc=new DownloadableGtfsInputSource(); isrc.setUrl(url); csvInputSource=isrc; } } return csvInputSource; }