List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream putArchiveEntry
public void putArchiveEntry(ArchiveEntry archiveEntry) throws IOException
From source file:at.spardat.xma.xdelta.JarDelta.java
/** * Computes the binary differences of two zip files. For all files contained in source and target which * are not equal, the binary difference is caluclated by using * {@link com.nothome.delta.Delta#compute(byte[], InputStream, DiffWriter)}. * If the files are equal, nothing is written to the output for them. * Files contained only in target and files to small for {@link com.nothome.delta.Delta} are copied to output. * Files contained only in source are ignored. * At last a list of all files contained in target is written to <code>META-INF/file.list</code> in output. * * @param sourceName the original zip file * @param targetName a modification of the original zip file * @param source the original zip file/*ww w . j ava 2 s .com*/ * @param target a modification of the original zip file * @param output the zip file where the patches have to be written to * @throws IOException if an error occurs reading or writing any entry in a zip file */ public void computeDelta(String sourceName, String targetName, ZipFile source, ZipFile target, ZipArchiveOutputStream output) throws IOException { ByteArrayOutputStream listBytes = new ByteArrayOutputStream(); PrintWriter list = new PrintWriter(new OutputStreamWriter(listBytes)); list.println(sourceName); list.println(targetName); computeDelta(source, target, output, list, ""); list.close(); ZipArchiveEntry listEntry = new ZipArchiveEntry("META-INF/file.list"); output.putArchiveEntry(listEntry); output.write(listBytes.toByteArray()); output.closeArchiveEntry(); output.finish(); output.flush(); }
From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java
/** * Creates a zip file with random content. * * @author S3460//from ww w . j av a 2 s . c o m * @param source the source * @return the zip file * @throws Exception the exception */ private ZipFile makeSourceZipFile(File source) throws Exception { ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(source)); int size = randomSize(entryMaxSize); for (int i = 0; i < size; i++) { out.putArchiveEntry(new ZipArchiveEntry("zipentry" + i)); int anz = randomSize(10); for (int j = 0; j < anz; j++) { byte[] bytes = getRandomBytes(); out.write(bytes, 0, bytes.length); } out.flush(); out.closeArchiveEntry(); } //add leeres Entry out.putArchiveEntry(new ZipArchiveEntry("zipentry" + size)); out.flush(); out.closeArchiveEntry(); out.flush(); out.finish(); out.close(); return new ZipFile(source); }
From source file:com.amazon.aws.samplecode.travellog.util.DataExtractor.java
public void run() { try {//ww w . ja v a 2s. c om //Create temporary directory File tmpDir = File.createTempFile("travellog", ""); tmpDir.delete(); //Wipe out temporary file to replace with a directory tmpDir.mkdirs(); logger.log(Level.INFO, "Extract temp dir: " + tmpDir); //Store journal to props file Journal journal = dao.getJournal(); Properties journalProps = buildProps(journal); File journalFile = new File(tmpDir, "journal"); journalProps.store(new FileOutputStream(journalFile), ""); //Iterate through entries and grab related photos List<Entry> entries = dao.getEntries(journal); int entryIndex = 1; int imageFileIndex = 1; for (Entry entry : entries) { Properties entryProps = buildProps(entry); File entryFile = new File(tmpDir, "entry." + (entryIndex++)); entryProps.store(new FileOutputStream(entryFile), ""); List<Photo> photos = dao.getPhotos(entry); int photoIndex = 1; for (Photo photo : photos) { Properties photoProps = buildProps(photo); InputStream photoData = S3PhotoUtil.loadOriginalPhoto(photo); String imageFileName = "imgdata." + (imageFileIndex++); File imageFile = new File(tmpDir, imageFileName); FileOutputStream outputStream = new FileOutputStream(imageFile); IOUtils.copy(photoData, outputStream); photoProps.setProperty("file", imageFileName); outputStream.close(); photoData.close(); File photoFile = new File(tmpDir, "photo." + (entryIndex - 1) + "." + (photoIndex++)); photoProps.store(new FileOutputStream(photoFile), ""); } List<Comment> comments = dao.getComments(entry); int commentIndex = 1; for (Comment comment : comments) { Properties commentProps = buildProps(comment); File commentFile = new File(tmpDir, "comment." + (entryIndex - 1) + "." + commentIndex++); commentProps.store(new FileOutputStream(commentFile), ""); } } //Bundle up the folder as a zip final File zipOut; //If we have an output path store locally if (outputPath != null) { zipOut = new File(outputPath); } else { //storing to S3 zipOut = File.createTempFile("export", ".zip"); } zipOut.getParentFile().mkdirs(); //make sure directory structure is in place ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(zipOut); //Create the zip file File[] files = tmpDir.listFiles(); for (File file : files) { ZipArchiveEntry archiveEntry = new ZipArchiveEntry(file.getName()); byte[] fileData = FileUtils.readFileToByteArray(file); archiveEntry.setSize(fileData.length); zaos.putArchiveEntry(archiveEntry); zaos.write(fileData); zaos.flush(); zaos.closeArchiveEntry(); } zaos.close(); //If outputpath if (outputPath == null) { TravelLogStorageObject obj = new TravelLogStorageObject(); obj.setBucketName(bucketName); obj.setStoragePath(storagePath); obj.setData(FileUtils.readFileToByteArray(zipOut)); obj.setMimeType("application/zip"); S3StorageManager mgr = new S3StorageManager(); mgr.store(obj, false, null); //Store with full redundancy and default permissions } } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); } }
From source file:com.haulmont.cuba.core.app.FoldersServiceBean.java
@Override public byte[] exportFolder(Folder folder) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(byteArrayOutputStream); zipOutputStream.setMethod(ZipArchiveOutputStream.STORED); zipOutputStream.setEncoding(StandardCharsets.UTF_8.name()); String xml = createXStream().toXML(folder); byte[] xmlBytes = xml.getBytes(StandardCharsets.UTF_8); ArchiveEntry zipEntryDesign = newStoredEntry("folder.xml", xmlBytes); zipOutputStream.putArchiveEntry(zipEntryDesign); zipOutputStream.write(xmlBytes);/*from ww w . j a v a 2s . c o m*/ try { zipOutputStream.closeArchiveEntry(); } catch (Exception ex) { throw new RuntimeException( String.format("Exception occurred while exporting folder %s.", folder.getName())); } zipOutputStream.close(); return byteArrayOutputStream.toByteArray(); }
From source file:com.oculusinfo.binning.io.impl.ZipResourcePyramidSourceTest.java
@Test public void test() { ZipArchiveOutputStream zos = null; File archive;/* ww w.j av a 2s.c o m*/ String filename = ""; try { archive = File.createTempFile("test.", ".zip", null); archive.deleteOnExit(); filename = archive.getAbsolutePath(); zos = new ZipArchiveOutputStream(archive); for (int z = 0; z < 3; z++) { for (int x = 0; x < Math.pow(2, z); x++) { for (int y = 0; y < Math.pow(2, z); y++) { ZipArchiveEntry entry = new ZipArchiveEntry(getDummyFile(), "test/tiles/" + z + "/" + x + "/" + y + ".dummy"); zos.putArchiveEntry(entry); } } } ZipArchiveEntry entry = new ZipArchiveEntry(getDummyFile(), "test/metadata.json"); zos.putArchiveEntry(entry); zos.closeArchiveEntry(); zos.close(); zos = null; } catch (IOException e) { fail(e.getMessage()); } try { ZipResourcePyramidSource src = new ZipResourcePyramidSource(filename, "dummy"); TileIndex tileDef = new TileIndex(0, 0, 0, 1, 1); InputStream is = src.getSourceTileStream("test", tileDef); Assert.assertTrue(is != null); tileDef = new TileIndex(2, 3, 3, 1, 1); is = src.getSourceTileStream("test", tileDef); Assert.assertTrue(is != null); is = src.getSourceMetaDataStream("test"); Assert.assertTrue(is != null); } catch (IOException e) { fail(e.getMessage()); } }
From source file:com.oculusinfo.binning.io.impl.ZipResourcePyramidStreamSourceTest.java
@Test public void test() { ZipArchiveOutputStream zos = null; File archive;/* w ww. ja v a 2 s. c o m*/ String filename = ""; try { archive = File.createTempFile("test.", ".zip", null); archive.deleteOnExit(); filename = archive.getAbsolutePath(); zos = new ZipArchiveOutputStream(archive); for (int z = 0; z < 3; z++) { for (int x = 0; x < Math.pow(2, z); x++) { for (int y = 0; y < Math.pow(2, z); y++) { ZipArchiveEntry entry = new ZipArchiveEntry(getDummyFile(), "test/tiles/" + z + "/" + x + "/" + y + ".dummy"); zos.putArchiveEntry(entry); } } } ZipArchiveEntry entry = new ZipArchiveEntry(getDummyFile(), "test/metadata.json"); zos.putArchiveEntry(entry); zos.closeArchiveEntry(); zos.close(); zos = null; } catch (IOException e) { fail(e.getMessage()); } try { ZipResourcePyramidStreamSource src = new ZipResourcePyramidStreamSource(filename, "dummy"); TileIndex tileDef = new TileIndex(0, 0, 0, 1, 1); InputStream is = src.getTileStream("test", tileDef); Assert.assertTrue(is != null); tileDef = new TileIndex(2, 3, 3, 1, 1); is = src.getTileStream("test", tileDef); Assert.assertTrue(is != null); is = src.getMetaDataStream("test"); Assert.assertTrue(is != null); } catch (IOException e) { fail(e.getMessage()); } }
From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java
/** * Writes a modified version of zip_Source into target. * * @author S3460//from w w w. java2 s .c o m * @param zipSource the zip source * @param target the target * @return the zip file * @throws Exception the exception */ private ZipFile makeTargetZipFile(ZipFile zipSource, File target) throws Exception { ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(target)); for (Enumeration<ZipArchiveEntry> enumer = zipSource.getEntries(); enumer.hasMoreElements();) { ZipArchiveEntry sourceEntry = enumer.nextElement(); out.putArchiveEntry(new ZipArchiveEntry(sourceEntry.getName())); byte[] oldBytes = toBytes(zipSource, sourceEntry); byte[] newBytes = getRandomBytes(); byte[] mixedBytes = mixBytes(oldBytes, newBytes); out.write(mixedBytes, 0, mixedBytes.length); out.flush(); out.closeArchiveEntry(); } out.putArchiveEntry(new ZipArchiveEntry("zipentry" + entryMaxSize + 1)); byte[] bytes = getRandomBytes(); out.write(bytes, 0, bytes.length); out.flush(); out.closeArchiveEntry(); out.putArchiveEntry(new ZipArchiveEntry("zipentry" + (entryMaxSize + 2))); out.closeArchiveEntry(); out.flush(); out.finish(); out.close(); return new ZipFile(targetFile); }
From source file:adams.core.io.ZipUtils.java
/** * Creates a zip file from the specified files. * * @param output the output file to generate * @param files the files to store in the zip file * @param stripRegExp the regular expression used to strip the file names (only applied to the directory!) * @param bufferSize the buffer size to use * @return null if successful, otherwise error message *///from w w w .ja v a 2 s.c o m @MixedCopyright(copyright = "Apache compress commons", license = License.APACHE2, url = "http://commons.apache.org/compress/examples.html") public static String compress(File output, File[] files, String stripRegExp, int bufferSize) { String result; int i; byte[] buf; int len; ZipArchiveOutputStream out; BufferedInputStream in; FileInputStream fis; FileOutputStream fos; String filename; String msg; ZipArchiveEntry entry; in = null; fis = null; out = null; fos = null; result = null; try { // does file already exist? if (output.exists()) System.err.println("WARNING: overwriting '" + output + "'!"); // create ZIP file buf = new byte[bufferSize]; fos = new FileOutputStream(output.getAbsolutePath()); out = new ZipArchiveOutputStream(new BufferedOutputStream(fos)); for (i = 0; i < files.length; i++) { fis = new FileInputStream(files[i].getAbsolutePath()); in = new BufferedInputStream(fis); // Add ZIP entry to output stream. filename = files[i].getParentFile().getAbsolutePath(); if (stripRegExp.length() > 0) filename = filename.replaceFirst(stripRegExp, ""); if (filename.length() > 0) filename += File.separator; filename += files[i].getName(); entry = new ZipArchiveEntry(filename); entry.setSize(files[i].length()); out.putArchiveEntry(entry); // Transfer bytes from the file to the ZIP file while ((len = in.read(buf)) > 0) out.write(buf, 0, len); // Complete the entry out.closeArchiveEntry(); FileUtils.closeQuietly(in); FileUtils.closeQuietly(fis); in = null; fis = null; } // Complete the ZIP file FileUtils.closeQuietly(out); FileUtils.closeQuietly(fos); out = null; fos = null; } catch (Exception e) { msg = "Failed to generate archive '" + output + "': "; System.err.println(msg); e.printStackTrace(); result = msg + e; } finally { FileUtils.closeQuietly(in); FileUtils.closeQuietly(fis); FileUtils.closeQuietly(out); FileUtils.closeQuietly(fos); } return result; }
From source file:fr.acxio.tools.agia.tasks.ZipFilesTasklet.java
protected void zipResource(Resource sSourceResource, ZipArchiveOutputStream sZipArchiveOutputStream, StepContribution sContribution, ChunkContext sChunkContext) throws IOException, ZipFilesException { // TODO : use a queue to reduce the callstack overhead if (sSourceResource.exists()) { File aSourceFile = sSourceResource.getFile(); String aSourcePath = aSourceFile.getCanonicalPath(); if (!aSourcePath.startsWith(sourceBaseDirectoryPath)) { throw new ZipFilesException( "Source file " + aSourcePath + " does not match base directory " + sourceBaseDirectoryPath); }/*from w w w .jav a2s .c om*/ if (sContribution != null) { sContribution.incrementReadCount(); } String aZipEntryName = aSourcePath.substring(sourceBaseDirectoryPath.length() + 1); sZipArchiveOutputStream.putArchiveEntry(new ZipArchiveEntry(aZipEntryName)); if (LOGGER.isInfoEnabled()) { LOGGER.info("Zipping {} to {}", sSourceResource.getFile().getCanonicalPath(), aZipEntryName); } if (aSourceFile.isFile()) { InputStream aInputStream = sSourceResource.getInputStream(); IOUtils.copy(aInputStream, sZipArchiveOutputStream); aInputStream.close(); sZipArchiveOutputStream.closeArchiveEntry(); } else { sZipArchiveOutputStream.closeArchiveEntry(); for (File aFile : aSourceFile .listFiles((FileFilter) (recursive ? TrueFileFilter.TRUE : FileFileFilter.FILE))) { zipResource(new FileSystemResource(aFile), sZipArchiveOutputStream, sContribution, sChunkContext); } } if (sContribution != null) { sContribution.incrementWriteCount(1); } } else if (LOGGER.isInfoEnabled()) { LOGGER.info("{} does not exist", sSourceResource.getFilename()); } }
From source file:com.haulmont.cuba.core.app.importexport.EntityImportExport.java
@Override public byte[] exportEntitiesToZIP(Collection<? extends Entity> entities) { String json = entitySerialization.toJson(entities, null, EntitySerializationOption.COMPACT_REPEATED_ENTITIES); byte[] jsonBytes = json.getBytes(StandardCharsets.UTF_8); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(byteArrayOutputStream); zipOutputStream.setMethod(ZipArchiveOutputStream.STORED); zipOutputStream.setEncoding(StandardCharsets.UTF_8.name()); ArchiveEntry singleDesignEntry = newStoredEntry("entities.json", jsonBytes); try {//from ww w. j a v a 2s . com zipOutputStream.putArchiveEntry(singleDesignEntry); zipOutputStream.write(jsonBytes); zipOutputStream.closeArchiveEntry(); } catch (Exception e) { throw new RuntimeException("Error on creating zip archive during entities export", e); } finally { IOUtils.closeQuietly(zipOutputStream); } return byteArrayOutputStream.toByteArray(); }