List of usage examples for java.util.zip ZipFile ZipFile
public ZipFile(File file) throws ZipException, IOException
From source file:fll.subjective.SubjectiveFrame.java
/** * Load data. Meant for testing. Most users should use #promptForFile(). * /*from w w w . j a va 2 s.co m*/ * @param file where to read the data in from and where to save data to * @throws IOException */ public void load(final File file) throws IOException { _file = file; ZipFile zipfile = null; try { zipfile = new ZipFile(file); final ZipEntry challengeEntry = zipfile.getEntry(DownloadSubjectiveData.CHALLENGE_ENTRY_NAME); if (null == challengeEntry) { throw new FLLRuntimeException( "Unable to find challenge descriptor in file, you probably choose the wrong file or it is corrupted"); } final InputStream challengeStream = zipfile.getInputStream(challengeEntry); _challengeDocument = ChallengeParser .parse(new InputStreamReader(challengeStream, Utilities.DEFAULT_CHARSET)); challengeStream.close(); _challengeDescription = new ChallengeDescription(_challengeDocument.getDocumentElement()); final ZipEntry scoreEntry = zipfile.getEntry(DownloadSubjectiveData.SCORE_ENTRY_NAME); if (null == scoreEntry) { throw new FLLRuntimeException( "Unable to find score data in file, you probably choose the wrong file or it is corrupted"); } final InputStream scoreStream = zipfile.getInputStream(scoreEntry); _scoreDocument = XMLUtils.parseXMLDocument(scoreStream); scoreStream.close(); final ZipEntry scheduleEntry = zipfile.getEntry(DownloadSubjectiveData.SCHEDULE_ENTRY_NAME); if (null != scheduleEntry) { ObjectInputStream scheduleStream = null; try { scheduleStream = new ObjectInputStream(zipfile.getInputStream(scheduleEntry)); _schedule = (TournamentSchedule) scheduleStream.readObject(); } finally { IOUtils.closeQuietly(scheduleStream); } } else { _schedule = null; } final ZipEntry mappingEntry = zipfile.getEntry(DownloadSubjectiveData.MAPPING_ENTRY_NAME); if (null != mappingEntry) { ObjectInputStream mappingStream = null; try { mappingStream = new ObjectInputStream(zipfile.getInputStream(mappingEntry)); // ObjectStream isn't type safe @SuppressWarnings("unchecked") final Collection<CategoryColumnMapping> mappings = (Collection<CategoryColumnMapping>) mappingStream .readObject(); _scheduleColumnMappings = mappings; } finally { IOUtils.closeQuietly(mappingStream); } } else { _scheduleColumnMappings = null; } } catch (final ClassNotFoundException e) { throw new FLLInternalException("Internal error loading schedule from data file", e); } catch (final SAXParseException spe) { final String errorMessage = String.format( "Error parsing file line: %d column: %d%n Message: %s%n This may be caused by using the wrong version of the software attempting to parse a file that is not subjective data.", spe.getLineNumber(), spe.getColumnNumber(), spe.getMessage()); throw new FLLRuntimeException(errorMessage, spe); } catch (final SAXException se) { final String errorMessage = "The subjective scores file was found to be invalid, check that you are parsing a subjective scores file and not something else"; throw new FLLRuntimeException(errorMessage, se); } finally { if (null != zipfile) { try { zipfile.close(); } catch (final IOException e) { LOGGER.debug("Error closing zipfile", e); } } } for (final ScoreCategory subjectiveCategory : getChallengeDescription().getSubjectiveCategories()) { createSubjectiveTable(tabbedPane, subjectiveCategory); } // get the name and location of the tournament final Element top = _scoreDocument.getDocumentElement(); final String tournamentName = top.getAttribute("tournamentName"); if (top.hasAttribute("tournamentLocation")) { final String tournamentLocation = top.getAttribute("tournamentName"); setTitle(String.format("Subjective Score Entry - %s @ %s", tournamentName, tournamentLocation)); } else { setTitle(String.format("Subjective Score Entry - %s", tournamentName)); } pack(); }
From source file:ZipUtilTest.java
public void testKeepEntriesState() throws IOException { File src = new File(getClass().getResource("demo-keep-entries-state.zip").getPath()); final String existingEntryName = "TestFile.txt"; final String fileNameToAdd = "TestFile-II.txt"; assertFalse(ZipUtil.containsEntry(src, fileNameToAdd)); File newEntry = new File(getClass().getResource(fileNameToAdd).getPath()); File dest = File.createTempFile("temp.zip", null); ZipUtil.addEntry(src, fileNameToAdd, newEntry, dest); ZipEntry srcEntry = new ZipFile(src).getEntry(existingEntryName); ZipEntry destEntry = new ZipFile(dest).getEntry(existingEntryName); assertTrue(srcEntry.getCompressedSize() == destEntry.getCompressedSize()); }
From source file:ClassFinder.java
private static void findClassesInPathsDir(String strPathElement, File dir, Set<String> listClasses) throws IOException { String[] list = dir.list();// w w w . ja v a 2 s . c o m for (int i = 0; i < list.length; i++) { File file = new File(dir, list[i]); if (file.isDirectory()) { // Recursive call findClassesInPathsDir(strPathElement, file, listClasses); } else if (list[i].endsWith(DOT_CLASS) && file.exists() && (file.length() != 0)) { final String path = file.getPath(); listClasses.add(path.substring(strPathElement.length() + 1, path.lastIndexOf(".")) // $NON-NLS-1$ .replace(File.separator.charAt(0), '.')); // $NON-NLS-1$ } else if (list[i].endsWith(DOT_JAR) && file.exists() && (file.length() != 0)) { ZipFile zipFile = new ZipFile(file); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { String strEntry = entries.nextElement().toString(); if (strEntry.endsWith(DOT_CLASS)) { listClasses.add(fixClassName(strEntry)); } } zipFile.close(); } } }
From source file:org.nebulaframework.deployment.classloading.GridArchiveClassLoader.java
/** * Internal method which does the search for class inside * the {@code GridArchive}. First attempts locate the file directly in * the {@code .nar} file. If this fails, it then looks in the * {@code .jar} libraries available in the {@code .nar} * file, and attempts to locate the class inside each of the {@code .jar} * file./* w ww . j a v a2 s.c o m*/ * * @param fileName expected filename of Class file to be loaded * * @return the {@code byte[]} for the class file * * @throws IOException if IO errors occur during operation * @throws ClassNotFoundException if unable to locate the class */ protected byte[] findInArchive(String fileName) throws IOException, ClassNotFoundException { ZipFile archive = new ZipFile(archiveFile); ZipEntry entry = archive.getEntry(fileName); if (entry == null) { // Unable to find file in archive try { // Attempt to look in libraries Enumeration<? extends ZipEntry> enumeration = archive.entries(); while (enumeration.hasMoreElements()) { ZipEntry zipEntry = enumeration.nextElement(); if (zipEntry.getName().contains(GridArchive.NEBULA_INF) && zipEntry.getName().endsWith(".jar")) { // Look in Jar File byte[] bytes = findInJarStream(archive.getInputStream(zipEntry), fileName); // If Found if (bytes != null) { log.debug("[GridArchiveClassLoader] found class in JAR Library " + fileName); return bytes; } } } } catch (Exception e) { log.warn("[[GridArchiveClassLoader] Exception " + "while attempting class loading", e); } // Cannot Find Class throw new ClassNotFoundException("No such file as " + fileName); } else { // Entry not null, Found Class log.debug("[GridArchiveClassLoader] found class at " + fileName); // Get byte[] and return return IOSupport.readBytes(archive.getInputStream(entry)); } }
From source file:de.tarent.maven.plugins.pkg.packager.IzPackPackager.java
/** * Puts the embedded izpack jar from the (resource) classpath into the work * directory and unpacks it there.//from w w w.j a v a 2s . c o m * * @param l * @param izPackEmbeddedFile * @param izPackEmbeddedHomeDir * @throws MojoExecutionException */ private void unpackIzPack(Log l, File izPackEmbeddedFile, File izPackEmbeddedHomeDir) throws MojoExecutionException { l.info("storing embedded IzPack installation in " + izPackEmbeddedFile); Utils.storeInputStream(IzPackPackager.class.getResourceAsStream(IZPACK_EMBEDDED_JAR), izPackEmbeddedFile, "IOException while unpacking embedded IzPack installation."); l.info("unzipping embedded IzPack installation to" + izPackEmbeddedHomeDir); int count = 0; ZipFile zip = null; try { zip = new ZipFile(izPackEmbeddedFile); Enumeration<? extends ZipEntry> e = zip.entries(); while (e.hasMoreElements()) { count++; ZipEntry entry = (ZipEntry) e.nextElement(); File unpacked = new File(izPackEmbeddedHomeDir, entry.getName()); if (entry.isDirectory()) { unpacked.mkdirs(); // TODO: Check success. } else { Utils.createFile(unpacked, "Unable to create ZIP file entry "); Utils.storeInputStream(zip.getInputStream(entry), unpacked, "IOException while unpacking ZIP file entry."); } } } catch (IOException ioe) { throw new MojoExecutionException("IOException while unpacking embedded IzPack installation.", ioe); } finally { if (zip != null) { try { zip.close(); } catch (IOException e) { l.info(String.format("Error at closing zipfile %s caused by %s", izPackEmbeddedFile.getName(), e.getMessage())); } } } l.info("unpacked " + count + " entries"); }
From source file:de.tuebingen.uni.sfs.germanet.api.GermaNet.java
/** * Constructs a new <code>GermaNet</code> object by loading the the data * files in the specified directory/archive File. * @param dir location of the GermaNet data files * @param ignoreCase if true ignore case on lookups, otherwise do case * sensitive searches/* w ww . j a v a 2s. 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.netspective.commons.xdm.XdmComponentFactory.java
/** * Factory method for obtaining a particular component from a file that can be found in the classpath (including * JARs and ZIPs on the classpath).//w ww . ja v a2 s.c o m */ public static XdmComponent get(Class componentClass, String fileName, int flags, boolean forceReload) throws DataModelException, InvocationTargetException, InstantiationException, IllegalAccessException, IOException, NoSuchMethodException, FileNotFoundException { FileFind.FileFindResults ffResults = FileFind.findInClasspath(fileName, FileFind.FINDINPATHFLAG_SEARCH_INSIDE_ARCHIVES_LAST); if (ffResults.isFileFound()) { if (ffResults.isFoundFileInJar()) { ZipFile zipFile = new ZipFile(ffResults.getFoundFile()); ZipEntry zipEntry = zipFile.getEntry(ffResults.getSearchFileName()); String systemId = ffResults.getFoundFile().getAbsolutePath() + "!" + ffResults.getSearchFileName(); XdmComponent component = forceReload ? null : getCachedComponent(systemId, flags); if (component != null) return component; // if we we get to this point, we're parsing an XML file into a given component class XdmParseContext pc = null; List errors = null; List warnings = null; // create a new class instance and hang onto the error list for use later component = (XdmComponent) discoverClass.newInstance(componentClass, componentClass.getName()); errors = component.getErrors(); warnings = component.getWarnings(); // if the class's attributes and model is not known, get it now XmlDataModelSchema.getSchema(componentClass); // parse the XML file long startTime = System.currentTimeMillis(); pc = XdmParseContext.parse(component, ffResults.getFoundFile(), zipEntry); component.setLoadDuration(startTime, System.currentTimeMillis()); // if we had some syntax errors, make sure the component records them for later use if (pc != null && pc.getErrors().size() != 0) errors.addAll(pc.getErrors()); if (pc != null && pc.getWarnings().size() != 0) warnings.addAll(pc.getWarnings()); component.loadedFromXml(flags); // if there are no errors, cache this component so if the file is needed again, it's available immediately if ((flags & XDMCOMPFLAG_CACHE_ALWAYS) != 0 || (((flags & XDMCOMPFLAG_CACHE_WHEN_NO_ERRORS) != 0) && errors.size() == 0)) cacheComponent(systemId, component, flags); return component; } else return get(componentClass, ffResults.getFoundFile(), flags, forceReload); } else throw new FileNotFoundException("File '" + fileName + "' not found in classpath. Searched: " + TextUtils.getInstance().join(ffResults.getSearchPaths(), ", ")); }
From source file:gdt.data.entity.facet.ExtensionHandler.java
public static String[] listResourcesByType(String jar$, String type$) { try {//from w w w. jav a2 s .c o m ArrayList<String> sl = new ArrayList<String>(); ZipFile zf = new ZipFile(jar$); Enumeration<? extends ZipEntry> entries = zf.entries(); ZipEntry ze; String[] sa; String resource$; while (entries.hasMoreElements()) { try { ze = entries.nextElement(); sa = ze.getName().split("/"); resource$ = sa[sa.length - 1]; // System.out.println("ExtensionHandler:loadIcon:zip entry="+sa[sa.length-1]); if (type$.equals(FileExpert.getExtension(resource$))) { sl.add(resource$); } } catch (Exception e) { } } return sl.toArray(new String[0]); } catch (Exception e) { Logger.getLogger(ExtensionHandler.class.getName()).severe(e.toString()); return null; } }
From source file:com.sshtools.j2ssh.util.ExtensionClassLoader.java
private URL findResourceInZipfile(File file, String name) { try {// w w w . j a v a2s . c om ZipFile zipfile = new ZipFile(file); ZipEntry entry = zipfile.getEntry(name); if (entry != null) { return new URL("jar:" + file.toURL() + "!" + (name.startsWith("/") ? "" : "/") + name); } else { return null; } } catch (IOException e) { return null; } }
From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.impl.DatasourceResourceIT.java
@Test public void testMondrianImportExport() throws Exception { final String domainName = "SalesData"; List<IMimeType> mimeTypeList = new ArrayList<IMimeType>(); mimeTypeList.add(new MimeType("Mondrian", "mondrian.xml")); System.setProperty("org.osjava.sj.root", "test-res/solution1/system/simple-jndi"); //$NON-NLS-1$ //$NON-NLS-2$ File mondrian = new File("test-res/dsw/testData/SalesData.mondrian.xml"); RepositoryFile repoMondrianFile = new RepositoryFile.Builder(mondrian.getName()).folder(false).hidden(false) .build();//from ww w . ja v a2 s .c o m RepositoryFileImportBundle bundle1 = new RepositoryFileImportBundle.Builder().file(repoMondrianFile) .charSet("UTF-8").input(new FileInputStream(mondrian)).mime("mondrian.xml") .withParam("parameters", "Datasource=Pentaho;overwrite=true").withParam("domain-id", "SalesData") .build(); MondrianImportHandler mondrianImportHandler = new MondrianImportHandler(mimeTypeList, PentahoSystem.get(IMondrianCatalogService.class)); mondrianImportHandler.importFile(bundle1); try { KettleEnvironment.init(); Props.init(Props.TYPE_PROPERTIES_EMPTY); } catch (Exception e) { // may already be initialized by another test } Domain domain = generateModel(); ModelerWorkspace model = new ModelerWorkspace(new GwtModelerWorkspaceHelper()); model.setModelName("ORDERS"); model.setDomain(domain); model.getWorkspaceHelper().populateDomain(model); new ModelerService().serializeModels(domain, domainName); final Response salesData = new DataSourceWizardResource().doGetDSWFilesAsDownload(domainName + ".xmi"); Assert.assertEquals(salesData.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertNotNull(salesData.getMetadata()); Assert.assertNotNull(salesData.getMetadata().getFirst("Content-Disposition")); Assert.assertEquals(salesData.getMetadata().getFirst("Content-Disposition").getClass(), String.class); Assert.assertTrue( ((String) salesData.getMetadata().getFirst("Content-Disposition")).endsWith(domainName + ".zip\"")); File file = File.createTempFile(domainName, ".zip"); final FileOutputStream fileOutputStream = new FileOutputStream(file); ((StreamingOutput) salesData.getEntity()).write(fileOutputStream); fileOutputStream.close(); final ZipFile zipFile = new ZipFile(file); final Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { final ZipEntry zipEntry = entries.nextElement(); Assert.assertTrue(zipEntry.getName().equals(domainName + ".xmi") || zipEntry.getName().equals(domainName + ".mondrian.xml")); } zipFile.close(); file.delete(); }