List of usage examples for java.util.zip ZipFile getEntry
public ZipEntry getEntry(String name)
From source file:com.ning.maven.plugins.duplicatefinder.DuplicateFinderMojo.java
/** * Calculates the SHA256 Hash of a class in a file. * //from w w w . j a v a 2s . com * @param file the archive contains the class * @param resourcePath the name of the class * @return the MD% Hash as Hex-Value * @throws IOException if any error occurs on reading class in archive */ private String getSHA256HexOfElement(final File file, final String resourcePath) throws IOException { class Sha256CacheKey { final File file; final String resourcePath; Sha256CacheKey(File file, String resourcePath) { this.file = file; this.resourcePath = resourcePath; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Sha256CacheKey key = (Sha256CacheKey) o; return file.equals(key.file) && resourcePath.equals(key.resourcePath); } public int hashCode() { return 31 * file.hashCode() + resourcePath.hashCode(); } } final Sha256CacheKey key = new Sha256CacheKey(file, resourcePath); if (CACHED_SHA256.containsKey(key)) { return (String) CACHED_SHA256.get(key); } ZipFile zip = new ZipFile(file); ZipEntry zipEntry = zip.getEntry(resourcePath); if (zipEntry == null) { throw new IOException("Could not found Zip-Entry for " + resourcePath + " in file " + file); } String sha256; InputStream in = zip.getInputStream(zipEntry); try { sha256 = DigestUtils.sha256Hex(in); } finally { IOUtils.closeQuietly(in); } CACHED_SHA256.put(key, sha256); return sha256; }
From source file:org.zeroturnaround.zip.ZipsTest.java
private void assertContainsEntryWithSeparatorrs(File zip, String entryPath, String expectedSeparator) throws IOException { char expectedSeparatorChar = expectedSeparator.charAt(0); String osSpecificEntryPath = entryPath.replace('\\', expectedSeparatorChar).replace('/', expectedSeparatorChar);/*from w w w . ja va 2 s.co m*/ ZipFile zf = new ZipFile(zip); try { if (zf.getEntry(osSpecificEntryPath) == null) { char unexpectedSeparatorChar = expectedSeparatorChar == '/' ? '\\' : '/'; String nonOsSpecificEntryPath = entryPath.replace('\\', unexpectedSeparatorChar).replace('/', unexpectedSeparatorChar); if (zf.getEntry(nonOsSpecificEntryPath) != null) { fail(zip.getAbsolutePath() + " is not packed using directory separator '" + expectedSeparatorChar + "', found entry '" + nonOsSpecificEntryPath + "', but not '" + osSpecificEntryPath + "'"); // used to fail with this message on windows } StringBuilder sb = new StringBuilder(); Enumeration entries = zf.entries(); while (entries.hasMoreElements()) { ZipEntry ze = (ZipEntry) entries.nextElement(); sb.append(ze.getName()).append(","); } fail(zip.getAbsolutePath() + " doesn't contain entry '" + entryPath + "', but found following entries: " + sb.toString()); } } finally { zf.close(); } assertTrue("Didn't find entry '" + entryPath + "' from " + zip.getAbsolutePath(), ZipUtil.containsEntry(zip, entryPath)); }
From source file:sernet.gs.scraper.ZIPGSSource.java
private ZipEntry getBaustein(ZipFile zf, String pathFragment, String bausteinFileName) { ZipEntry entry = null;//from ww w . ja va 2 s. c o m Pattern pat = Pattern.compile("(b\\d\\d).*"); Matcher matcher = pat.matcher(bausteinFileName); if (matcher.find()) { String chapter = matcher.group(1); String path = pathFragment + chapter + "/" + bausteinFileName + SUFFIX_2009; entry = zf.getEntry(path); } return entry; }
From source file:com.t3.persistence.PackedFile.java
public boolean hasFile(String path) throws IOException { if (removedFileSet.contains(path)) return false; File explodedFile = getExplodedFile(path); if (explodedFile.exists()) return true; boolean ret = false; if (file.exists()) { ZipFile zipFile = getZipFile(); ZipEntry ze = zipFile.getEntry(path); ret = (ze != null);// ww w . ja v a 2 s .co m } return ret; }
From source file:net.minecraftforge.fml.common.FMLModContainer.java
public Properties searchForVersionProperties() { try {/*www . j a va2 s .c o m*/ FMLLog.log(getModId(), Level.DEBUG, "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.log(getModId(), Level.TRACE, "Failed to find a usable version.properties file"); return null; } }
From source file:org.roda.core.plugins.plugins.characterization.ODFSignatureUtils.java
private static List<Reference> getReferenceList(ZipFile zipFile, DocumentBuilder documentBuilder, XMLSignatureFactory factory, NodeList listFileEntry, DigestMethod digestMethod) throws IOException, SAXException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, CanonicalizationException, InvalidCanonicalizerException { Transform transform = factory.newTransform(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS, (TransformParameterSpec) null); List<Transform> transformList = new ArrayList<>(); transformList.add(transform);//from w ww . j a va 2s. com MessageDigest messageDigest = MessageDigest.getInstance(RodaConstants.SHA1); List<Reference> referenceList = new ArrayList<>(); for (int i = 0; i < listFileEntry.getLength(); i++) { String fullPath = ((Element) listFileEntry.item(i)).getAttribute("manifest:full-path"); Reference reference; if (!fullPath.endsWith("/") && !fullPath.equals(META_INF_DOCUMENTSIGNATURES_XML)) { if ("content.xml".equals(fullPath) || "meta.xml".equals(fullPath) || "styles.xml".equals(fullPath) || "settings.xml".equals(fullPath)) { try (InputStream xmlFile = zipFile.getInputStream(zipFile.getEntry(fullPath))) { Element root = documentBuilder.parse(xmlFile).getDocumentElement(); Canonicalizer canonicalizer = Canonicalizer .getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS); byte[] docCanonicalize = canonicalizer.canonicalizeSubtree(root); byte[] digestValue = messageDigest.digest(docCanonicalize); reference = factory.newReference(fullPath.replaceAll(" ", "%20"), digestMethod, transformList, null, null, digestValue); } } else { try (InputStream is = zipFile.getInputStream(zipFile.getEntry(fullPath))) { byte[] digestValue = messageDigest.digest(IOUtils.toByteArray(is)); reference = factory.newReference(fullPath.replaceAll(" ", "%20"), digestMethod, null, null, null, digestValue); } } referenceList.add(reference); } } return referenceList; }
From source file:net.sf.asap.Player.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Uri uri = getIntent().getData();//from w ww.j a va2s . c o m filename = uri.getLastPathSegment(); ZipFile zip = null; final byte[] module = new byte[ASAPInfo.MAX_MODULE_LENGTH]; int moduleLen; try { InputStream is; if (Util.isZip(filename)) { zip = new ZipFile(uri.getPath()); filename = uri.getFragment(); is = zip.getInputStream(zip.getEntry(filename)); } else { try { is = getContentResolver().openInputStream(uri); } catch (FileNotFoundException ex) { if (uri.getScheme().equals("http")) is = httpGet(uri); else throw ex; } } moduleLen = readAndClose(is, module); } catch (IOException ex) { showError(R.string.error_reading_file); return; } finally { Util.close(zip); } try { asap.load(filename, module, moduleLen); } catch (Exception ex) { showError(R.string.invalid_file); return; } info = asap.getInfo(); setTitle(R.string.playing_title); setContentView(R.layout.playing); setTag(R.id.name, info.getTitleOrFilename()); setTag(R.id.author, info.getAuthor()); setTag(R.id.date, info.getDate()); findViewById(R.id.stop_button).setOnClickListener(new OnClickListener() { public void onClick(View v) { finish(); } }); mediaController = new MediaController(this, false); mediaController.setAnchorView(getContentView()); mediaController.setMediaPlayer(new MediaController.MediaPlayerControl() { public boolean canPause() { return !isPaused(); } public boolean canSeekBackward() { return false; } public boolean canSeekForward() { return false; } public int getBufferPercentage() { return 100; } public int getCurrentPosition() { return asap.getPosition(); } public int getDuration() { return info.getDuration(song); } public boolean isPlaying() { return !isPaused(); } public void pause() { audioTrack.pause(); } public void seekTo(int pos) { seek(pos); } public void start() { resume(); } }); if (info.getSongs() > 1) { mediaController.setPrevNextListeners(new OnClickListener() { public void onClick(View v) { playNextSong(); } }, new OnClickListener() { public void onClick(View v) { playPreviousSong(); } }); } new Handler().postDelayed(new Runnable() { public void run() { mediaController.show(); } }, 500); stop = false; playSong(info.getDefaultSong()); new Thread(this).start(); }
From source file:org.broad.igv.feature.genome.GenomeManager.java
/** * Rewrite the {@link Globals#GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY} property to equal * the specified {@code newSequencePath}. Works by creating a temp file and renaming * * @param targetFile A .genome file, in zip format * @param newSequencePath//from w ww . ja va2s . c om * @return boolean indicating success or failure. * @throws IOException */ static boolean rewriteSequenceLocation(File targetFile, String newSequencePath) throws IOException { ZipFile targetZipFile = new ZipFile(targetFile); boolean success = false; File tmpZipFile = File.createTempFile("tmpGenome", ".zip"); ZipEntry propEntry = targetZipFile.getEntry(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME); InputStream propertyInputStream = null; ZipOutputStream zipOutputStream = null; Properties inputProperties = new Properties(); try { propertyInputStream = targetZipFile.getInputStream(propEntry); BufferedReader reader = new BufferedReader(new InputStreamReader(propertyInputStream)); //Copy over property.txt, only replacing a few properties inputProperties.load(reader); inputProperties.put(Globals.GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY, newSequencePath); inputProperties.put(Globals.GENOME_ARCHIVE_CUSTOM_SEQUENCE_LOCATION_KEY, Boolean.TRUE.toString()); ByteArrayOutputStream propertyBytes = new ByteArrayOutputStream(); PrintWriter propertyFileWriter = new PrintWriter(new OutputStreamWriter(propertyBytes)); inputProperties.store(propertyFileWriter, null); propertyFileWriter.flush(); byte[] newPropertyBytes = propertyBytes.toByteArray(); Enumeration<? extends ZipEntry> entries = targetZipFile.entries(); zipOutputStream = new ZipOutputStream(new FileOutputStream(tmpZipFile)); while (entries.hasMoreElements()) { ZipEntry curEntry = entries.nextElement(); ZipEntry writeEntry = null; if (curEntry.getName().equals(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME)) { writeEntry = new ZipEntry(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME); writeEntry.setSize(newPropertyBytes.length); zipOutputStream.putNextEntry(writeEntry); zipOutputStream.write(newPropertyBytes); continue; } else { //Because the compressed size can vary, //we generate a new ZipEntry and copy some attributes writeEntry = new ZipEntry(curEntry.getName()); writeEntry.setSize(curEntry.getSize()); writeEntry.setComment(curEntry.getComment()); writeEntry.setTime(curEntry.getTime()); } zipOutputStream.putNextEntry(writeEntry); InputStream tmpIS = null; try { tmpIS = targetZipFile.getInputStream(writeEntry); int bytes = IOUtils.copy(tmpIS, zipOutputStream); log.debug(bytes + " bytes written to " + targetFile); } finally { if (tmpIS != null) tmpIS.close(); } } } catch (Exception e) { tmpZipFile.delete(); throw new RuntimeException(e.getMessage(), e); } finally { if (propertyInputStream != null) propertyInputStream.close(); if (zipOutputStream != null) { zipOutputStream.flush(); zipOutputStream.finish(); zipOutputStream.close(); } zipOutputStream = null; System.gc(); success = true; } //This is a hack. I don't know why it's necessary, //but for some reason the output zip file seems to be corrupt //at least when called from GenomeManager.refreshArchive try { Thread.sleep(1500); } catch (InterruptedException e) { // } //Rename tmp file if (success) { targetFile.delete(); FileUtils.copyFile(tmpZipFile, targetFile); success = targetFile.exists(); tmpZipFile.delete(); } return success; }
From source file:org.obiba.opal.web.FilesResourceTest.java
@SuppressWarnings("unchecked") private void checkCompressedFolder(String folderPath, String... expectedFolderContentArray) throws IOException { Response response = filesResource.getFile(folderPath, null); ZipFile zipfile = new ZipFile(((File) response.getEntity()).getPath()); // Check that all folders and files exist in the compressed archive that represents the folder. for (String anExpectedFolderContentArray : expectedFolderContentArray) { assertThat(zipfile.getEntry(anExpectedFolderContentArray)).isNotNull(); }//ww w .ja v a2s.c om Enumeration<ZipEntry> zipEnum = (Enumeration<ZipEntry>) zipfile.entries(); int count = 0; while (zipEnum.hasMoreElements()) { zipEnum.nextElement(); count++; } // Make sure that they are no unexpected files in the compressed archive. assertThat(expectedFolderContentArray.length).isEqualTo(count); zipfile.close(); }
From source file:org.zeroturnaround.zip.ZipsTest.java
public void testCharsetEntry() throws IOException { File src = new File(MainExamplesTest.DEMO_ZIP); final String fileName = "TestFile.txt"; assertFalse(ZipUtil.containsEntry(src, fileName)); File newEntry = new File("src/test/resources/TestFile.txt"); File dest = File.createTempFile("temp.zip", ".zip"); Charset charset = Charset.forName("UTF-8"); String entryName = ".txt"; try {//from ww w . j av a2s . c om Zips.get(src).charset(charset).addEntry(new FileSource(entryName, newEntry)).destination(dest) .process(); } catch (IllegalStateException e) { if (e.getMessage().startsWith("Using constructor ZipFile(File, Charset) has failed") || e.getMessage() .startsWith("Using constructor ZipOutputStream(OutputStream, Charset) has failed")) { // this is acceptable when old java doesn't have charset constructor return; } else { System.out.println("'" + e.getMessage() + "'"); } } ZipFile zf = null; try { zf = ZipFileUtil.getZipFile(dest, charset); assertNotNull("Entry '" + entryName + "' was not added", zf.getEntry(entryName)); } finally { ZipUtil.closeQuietly(zf); } }