List of usage examples for java.util.zip ZipFile getInputStream
public InputStream getInputStream(ZipEntry entry) throws IOException
From source file:nl.edia.sakai.tool.skinmanager.impl.SkinFileSystemServiceImpl.java
protected void createFile(ZipEntry zipEntry, File file, ZipFile myZipFile) throws IOException { String myEntryName = zipEntry.getName(); boolean isMatched = isValidName(myEntryName); if (!isMatched) { LOG.warn("Skipping file entry: " + myEntryName + ""); return;//from w ww. j a v a 2 s. c om } if (PATTERN_IMAGES_DIR_CONTENT.matcher(myEntryName).matches()) { File myParentDir = file.getParentFile(); if (!myParentDir.exists()) { if (!myParentDir.mkdir()) { LOG.warn("Unable to mkdir: " + myParentDir); } } } InputStream myInputStream = null; OutputStream myOutputStream = null; try { myInputStream = myZipFile.getInputStream(zipEntry); myOutputStream = new FileOutputStream(file); byte[] myBuffer = new byte[1024]; int read; while ((read = myInputStream.read(myBuffer)) != -1) { myOutputStream.write(myBuffer, 0, read); } } finally { if (myOutputStream != null) { myOutputStream.close(); } if (myInputStream != null) { myInputStream.close(); } } }
From source file:com.drevelopment.couponcodes.bukkit.updater.Updater.java
/** * Part of Zip-File-Extractor, modified by Gravity for use with Updater. * * @param file the location of the file to extract. *//*from w ww.j a v a 2 s. c om*/ private void unzip(String file) { final File fSourceZip = new File(file); try { final String zipPath = file.substring(0, file.length() - 4); ZipFile zipFile = new ZipFile(fSourceZip); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); File destinationFilePath = new File(zipPath, entry.getName()); this.fileIOOrError(destinationFilePath.getParentFile(), destinationFilePath.getParentFile().mkdirs(), true); if (!entry.isDirectory()) { final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; final byte[] buffer = new byte[Updater.BYTE_SIZE]; final FileOutputStream fos = new FileOutputStream(destinationFilePath); final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE); while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) { bos.write(buffer, 0, b); } bos.flush(); bos.close(); bis.close(); final String name = destinationFilePath.getName(); if (name.endsWith(".jar") && this.pluginExists(name)) { File output = new File(this.updateFolder, name); this.fileIOOrError(output, destinationFilePath.renameTo(output), true); } } } zipFile.close(); // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. moveNewZipFiles(zipPath); } catch (final IOException e) { this.plugin.getLogger().log(Level.SEVERE, "The auto-updater tried to unzip a new update file, but was unsuccessful.", e); this.result = Updater.UpdateResult.FAIL_DOWNLOAD; } finally { this.fileIOOrError(fSourceZip, fSourceZip.delete(), false); } }
From source file:eionet.meta.exports.ods.Ods.java
/** * Zips file.//from w w w . jav a2 s .c om * * @param fileToZip * file to zip (full path) * @param fileName * file name * @throws java.lang.Exception * if operation fails. */ private void zip(String fileToZip, String fileName) throws Exception { // get source file File src = new File(workingFolderPath + ODS_FILE_NAME); ZipFile zipFile = new ZipFile(src); // create temp file for output File tempDst = new File(workingFolderPath + ODS_FILE_NAME + ".zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tempDst)); // iterate on each entry in zip file Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = entries.nextElement(); BufferedInputStream bis; if (StringUtils.equals(fileName, zipEntry.getName())) { bis = new BufferedInputStream(new FileInputStream(new File(fileToZip))); } else { bis = new BufferedInputStream(zipFile.getInputStream(zipEntry)); } ZipEntry ze = new ZipEntry(zipEntry.getName()); zos.putNextEntry(ze); while (bis.available() > 0) { zos.write(bis.read()); } zos.closeEntry(); bis.close(); } zos.finish(); zos.close(); zipFile.close(); // rename file src.delete(); tempDst.renameTo(src); }
From source file:org.guvnor.m2repo.backend.server.GuvnorM2Repository.java
private File appendPOMToJar(final String pom, final String jarPath, final GAV gav) { File originalJarFile = new File(jarPath); File appendedJarFile = new File(jarPath + ".tmp"); try {/*from w w w . j a va 2 s . co m*/ ZipFile war = new ZipFile(originalJarFile); ZipOutputStream append = new ZipOutputStream(new FileOutputStream(appendedJarFile)); // first, copy contents from existing war Enumeration<? extends ZipEntry> entries = war.entries(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); append.putNextEntry(e); if (!e.isDirectory()) { IOUtil.copy(war.getInputStream(e), append); } append.closeEntry(); } // append pom.xml ZipEntry e = new ZipEntry(getPomXmlPath(gav)); append.putNextEntry(e); append.write(pom.getBytes()); append.closeEntry(); // close war.close(); append.close(); } catch (ZipException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } return appendedJarFile; }
From source file:org.b3log.solo.processor.CaptchaProcessor.java
/** * Loads captcha./*from www.ja v a 2 s .c o m*/ */ private synchronized void loadCaptchas() { LOGGER.info("Loading captchas...."); try { captchas = new Image[CAPTCHA_COUNT]; ZipFile zipFile; if (RuntimeEnv.LOCAL == Latkes.getRuntimeEnv()) { final InputStream inputStream = SoloServletListener.class.getClassLoader() .getResourceAsStream("captcha_static.zip"); final File file = File.createTempFile("b3log_captcha_static", null); final OutputStream outputStream = new FileOutputStream(file); IOUtils.copy(inputStream, outputStream); zipFile = new ZipFile(file); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } else { final URL captchaURL = SoloServletListener.class.getClassLoader().getResource("captcha_static.zip"); zipFile = new ZipFile(captchaURL.getFile()); } final Enumeration<? extends ZipEntry> entries = zipFile.entries(); int i = 0; while (entries.hasMoreElements()) { final ZipEntry entry = entries.nextElement(); final BufferedInputStream bufferedInputStream = new BufferedInputStream( zipFile.getInputStream(entry)); final byte[] captchaCharData = new byte[bufferedInputStream.available()]; bufferedInputStream.read(captchaCharData); bufferedInputStream.close(); final Image image = IMAGE_SERVICE.makeImage(captchaCharData); image.setName(entry.getName().substring(0, entry.getName().lastIndexOf('.'))); captchas[i] = image; i++; } zipFile.close(); } catch (final Exception e) { LOGGER.error("Can not load captchs!"); throw new IllegalStateException(e); } LOGGER.info("Loaded captch images"); }
From source file:org.guvnor.m2repo.backend.server.GuvnorM2Repository.java
private File appendPomPropertiesToJar(final String pomProperties, final String jarPath, final GAV gav) { File originalJarFile = new File(jarPath); File appendedJarFile = new File(jarPath + ".tmp"); try {//from w w w . java 2 s.c o m ZipFile war = new ZipFile(originalJarFile); ZipOutputStream append = new ZipOutputStream(new FileOutputStream(appendedJarFile)); // first, copy contents from existing war Enumeration<? extends ZipEntry> entries = war.entries(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); append.putNextEntry(e); if (!e.isDirectory()) { IOUtil.copy(war.getInputStream(e), append); } append.closeEntry(); } // append pom.properties ZipEntry e = new ZipEntry(getPomPropertiesPath(gav)); append.putNextEntry(e); append.write(pomProperties.getBytes()); append.closeEntry(); // close war.close(); append.close(); } catch (ZipException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } //originalJarFile.delete(); //appendedJarFile.renameTo(originalJarFile); return appendedJarFile; }
From source file:com.jayway.maven.plugins.android.phase09package.ApkMojo.java
private File removeDuplicatesFromJar(File in, List<String> duplicates) { String target = projectOutputDirectory.getAbsolutePath(); File tmp = new File(target, "unpacked-embedded-jars"); tmp.mkdirs();/*w ww .j a va2s . c o m*/ File out = new File(tmp, in.getName()); if (out.exists()) { return out; } else { try { out.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } // Create a new Jar file final FileOutputStream fos; final ZipOutputStream jos; try { fos = new FileOutputStream(out); jos = new ZipOutputStream(fos); } catch (FileNotFoundException e1) { getLog().error( "Cannot remove duplicates : the output file " + out.getAbsolutePath() + " does not found"); return null; } final ZipFile inZip; try { inZip = new ZipFile(in); Enumeration<? extends ZipEntry> entries = inZip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); // If the entry is not a duplicate, copy. if (!duplicates.contains(entry.getName())) { // copy the entry header to jos jos.putNextEntry(entry); InputStream currIn = inZip.getInputStream(entry); copyStreamWithoutClosing(currIn, jos); currIn.close(); jos.closeEntry(); } } } catch (IOException e) { getLog().error("Cannot removing duplicates : " + e.getMessage()); return null; } try { inZip.close(); jos.close(); fos.close(); } catch (IOException e) { // ignore it. } getLog().info(in.getName() + " rewritten without duplicates : " + out.getAbsolutePath()); return out; }
From source file:com.hichinaschool.flashcards.libanki.Media.java
/** * Extract zip data.// ww w . ja v a2s. com * * @param zipData An input stream that represents a zipped file. * @return True if finished. */ public boolean syncAdd(File zipData) { boolean finished = false; ZipFile z = null; ArrayList<Object[]> media = new ArrayList<Object[]>(); long sizecnt = 0; JSONObject meta = null; int nextUsn = 0; try { z = new ZipFile(zipData, ZipFile.OPEN_READ); // get meta info first ZipEntry metaEntry = z.getEntry("_meta"); // if (metaEntry.getSize() >= 100000) { // Log.e(AnkiDroidApp.TAG, "Size for _meta entry found too big (" + z.getEntry("_meta").getSize() + ")"); // return false; // } meta = new JSONObject(Utils.convertStreamToString(z.getInputStream(metaEntry))); ZipEntry usnEntry = z.getEntry("_usn"); String usnstr = Utils.convertStreamToString(z.getInputStream(usnEntry)); nextUsn = Integer.parseInt(usnstr); } catch (JSONException e) { throw new RuntimeException(e); } catch (ZipException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } // Then loop through all files for (ZipEntry zentry : Collections.list(z.entries())) { // Check for zip bombs sizecnt += zentry.getSize(); if (sizecnt > 100 * 1024 * 1024) { Log.e(AnkiDroidApp.TAG, "Media zip file exceeds 100MB uncompressed, aborting unzipping"); return false; } if (zentry.getName().compareTo("_meta") == 0 || zentry.getName().compareTo("_usn") == 0) { // Ignore previously retrieved meta continue; } else if (zentry.getName().compareTo("_finished") == 0) { finished = true; } else { String name = meta.optString(zentry.getName()); if (illegal(name)) { continue; } String path = getDir().concat(File.separator).concat(name); try { Utils.writeToFile(z.getInputStream(zentry), path); } catch (IOException e) { throw new RuntimeException(e); } String csum = Utils.fileChecksum(path); // append db media.add(new Object[] { name, csum, _mtime(name) }); mMediaDb.execute("delete from log where fname = ?", new String[] { name }); } } // update media db and note new starting usn if (!media.isEmpty()) { mMediaDb.executeMany("insert or replace into media values (?,?,?)", media); } setUsn(nextUsn); // commits // if we have finished adding, we need to record the new folder mtime // so that we don't trigger a needless scan if (finished) { syncMod(); } return finished; }
From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.ArchiveExpander.java
private void expandZip(final File expandDir, final Archive archive, final QcContext context) throws IOException { ZipFile zipFile = null; BufferedOutputStream out = null; try {//from ww w . j a v a 2 s . c o m zipFile = new ZipFile(archive.fullArchivePathAndName()); // write each entry to the archive directory final Enumeration zipEnum = zipFile.entries(); boolean foundArchiveDir = false; while (zipEnum.hasMoreElements()) { final ZipEntry entry = (ZipEntry) zipEnum.nextElement(); if (!entry.isDirectory()) { String entryName = entry.getName(); final File entryFile = new File(entryName); // extract out just the filename of the entry if (entryFile.getCanonicalPath().lastIndexOf(File.separator) != -1) { entryName = entryFile.getCanonicalPath() .substring(entryFile.getCanonicalPath().lastIndexOf(File.separator)); } // the file to write is the archive dir plus just the filename final File archiveFile = new File(expandDir, entryName); InputStream in = zipFile.getInputStream(entry); FileOutputStream fout = new FileOutputStream(archiveFile); //noinspection IOResourceOpenedButNotSafelyClosed out = new BufferedOutputStream(fout); copyInputStream(in, out); in = null; out = null; fout.close(); fout = null; } else { // if find a directory that isn't the archive name, add warning for weird archive structure if (!entry.getName().equals(archive.getArchiveName()) && !entry.getName().equals(archive.getArchiveName() + "/")) { context.addWarning(new StringBuilder().append("Archive '") .append("' has a non-standard directory '").append(entry.getName()).append("'.") .append("Archive files should be contained inside a single directory with the archive name as its name.") .toString()); } else { foundArchiveDir = true; } } } if (!foundArchiveDir) { context.addWarning( "Archive files should be contained inside a single directory with the archive name as its name."); } } finally { IOUtils.closeQuietly(out); if (zipFile != null) { zipFile.close(); } } }
From source file:org.bdval.BDVModel.java
/** * Loads a BDVal model from disk. BDVal models are generated with the * {@link org.bdval.DiscoverAndValidate} tools (BDVal). * * @param options specific options to use when loading the model * @throws IOException if there is a problem accessing the model * @throws ClassNotFoundException if the type of the model is not recognized *///w ww . jav a2 s .c om public void load(final DAVOptions options) throws IOException, ClassNotFoundException { final boolean zipExists = new File(zipFilename).exists(); if (LOG.isDebugEnabled()) { LOG.debug("model zip file exists: " + BooleanUtils.toStringYesNo(zipExists)); } properties.clear(); properties.setDelimiterParsingDisabled(true); // check to see if a zip file exists - if it doesn't we assume it's an old binary format if (zipModel && zipExists) { LOG.info("Reading model from filename: " + zipFilename); final ZipFile zipFile = new ZipFile(zipFilename); try { final ZipEntry propertyEntry = zipFile.getEntry(FilenameUtils.getName(modelPropertiesFilename)); // load properties properties.clear(); properties.addAll(loadProperties(zipFile.getInputStream(propertyEntry), options)); // the platform is more than one entry in the zip, so here we pass the whole zip trainingPlatform = options.trainingPlatform = loadPlatform(zipFile); if (isConsensusModel()) { int index = 0; final ObjectList<String> modelJurorFilePrefixes = new ObjectArrayList<String>(); String nextFilename; while ((nextFilename = (String) properties .getProperty("bdval.consensus.model." + Integer.toString(index))) != null) { modelJurorFilePrefixes.add(nextFilename); index++; } delegate = new ConsensusBDVModel(modelFilenamePrefix, modelJurorFilePrefixes.toArray(new String[modelJurorFilePrefixes.size()])); delegate.load(options); setGeneList(convertTrainingPlatformToGeneList(options)); return; } else { probesetScaleMeanMap = options.probesetScaleMeanMap = loadMeansMap( zipFile.getInputStream(zipFile.getEntry(FilenameUtils.getName(meansMapFilename)))); probesetScaleRangeMap = options.probesetScaleRangeMap = loadRangeMap( zipFile.getInputStream(zipFile.getEntry(FilenameUtils.getName(rangeMapFilename)))); setGeneList(convertTrainingPlatformToGeneList(options)); } final String modelParameters = properties.getString("training.classifier.parameters"); LOG.info("Loading model " + modelFilename); final InputStream modelStream = zipFile .getInputStream(zipFile.getEntry(FilenameUtils.getName(modelFilename))); helper = ClassificationModel.load(modelStream, modelParameters); LOG.info("Model loaded."); options.classiferClass = helper.classifier.getClass(); // we don't have a way to inspect the saved model for parameters used during training: options.classifierParameters = ClassificationModel.splitModelParameters(modelParameters); } finally { try { zipFile.close(); } catch (IOException e) { // NOPMD // ignore since there is not much we can do anyway } } } else { final File propertyFile = new File(modelFilenamePrefix + "." + ModelFileExtension.props.toString()); LOG.debug("Loading properties from " + propertyFile.getAbsolutePath()); final Properties properties = loadProperties(FileUtils.openInputStream(propertyFile), options); trainingPlatform = options.trainingPlatform = (GEOPlatformIndexed) BinIO.loadObject(platformFilename); if (isConsensusModel()) { int index = 0; final ObjectList<String> modelJurorFilePrefixes = new ObjectArrayList<String>(); String nextFilename = null; while ((nextFilename = (String) properties .getProperty("bdval.consensus.model." + Integer.toString(index))) != null) { modelJurorFilePrefixes.add(nextFilename); index++; } delegate = new ConsensusBDVModel(modelFilenamePrefix, modelJurorFilePrefixes.toArray(new String[modelJurorFilePrefixes.size()])); delegate.load(options); setGeneList(convertTrainingPlatformToGeneList(options)); return; } else { probesetScaleMeanMap = options.probesetScaleMeanMap = (Object2DoubleMap<MutableString>) BinIO .loadObject(modelFilenamePrefix + ".means"); if (LOG.isDebugEnabled()) { LOG.debug("Number of entries in means map = " + probesetScaleMeanMap.size()); } probesetScaleRangeMap = options.probesetScaleRangeMap = (Object2DoubleMap<MutableString>) BinIO .loadObject(modelFilenamePrefix + ".ranges"); if (LOG.isDebugEnabled()) { LOG.debug("Number of entries in range map = " + probesetScaleRangeMap.size()); } setGeneList(convertTrainingPlatformToGeneList(options)); } final String modelParameters = properties.getString("training.classifier.parameters"); LOG.info("Loading model " + modelFilename); helper = ClassificationModel.load(modelFilename, modelParameters); LOG.info("Model loaded."); options.classiferClass = helper.classifier.getClass(); // we don't have a way to inspect the saved model for parameters used during training: options.classifierParameters = ClassificationModel.splitModelParameters(modelParameters); } }