List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream closeArchiveEntry
public void closeArchiveEntry() throws IOException
From source file:org.betaconceptframework.astroboa.engine.jcr.io.SerializationBean.java
private void addContentToZip(ZipArchiveOutputStream os, SerializationReport serializationReport, Session session, SerializationConfiguration serializationConfiguration, String filename, ContentObjectCriteria contentObjectCriteria) throws IOException, Exception, SAXException, RepositoryException, PathNotFoundException { long start = System.currentTimeMillis(); Serializer serializer = null;/*from w ww .j a v a 2 s .co m*/ try { //Create entry os.putArchiveEntry(new ZipArchiveEntry(filename + ".xml")); serializer = new Serializer(os, cmsRepositoryEntityUtils, session, serializationConfiguration); serializer.setSerializationReport(serializationReport); //Create document serializer.start(); //Create root element createRootElement(serializer, CmsConstants.REPOSITORY_PREFIXED_NAME, ResourceRepresentationType.XML, entityTypeToSerialize != null && (entityTypeToSerialize == CmsEntityType.OBJECT || entityTypeToSerialize == CmsEntityType.REPOSITORY)); switch (entityTypeToSerialize) { case OBJECT: if (contentObjectCriteria != null) { serializeObjectsAndTheirDependencies(contentObjectCriteria, serializer, session, serializationReport); } else { serializeAllNodesRepresentingObjects(serializer, session, serializationReport); } break; case REPOSITORY_USER: serializeAllNodesRepresentingRepositoryUsers(serializer, session, serializationReport); break; case TAXONOMY: serializeAllNodesRepresentingTaxonomies(serializer, session, serializationReport); break; case ORGANIZATION_SPACE: serializeNodeRepresentingOrganizationSpace(serializer, session, serializationReport); break; case REPOSITORY: serializeAllNodesRepresentingRepositoryUsers(serializer, session, serializationReport); serializeAllNodesRepresentingTaxonomies(serializer, session, serializationReport); serializeAllNodesRepresentingObjects(serializer, session, serializationReport); serializeNodeRepresentingOrganizationSpace(serializer, session, serializationReport); break; default: break; } serializer.closeEntity(CmsConstants.REPOSITORY_PREFIXED_NAME); //End document serializer.end(); //Close archive entry os.closeArchiveEntry(); logger.debug("Added content toy zip in {}", DurationFormatUtils.formatDuration(System.currentTimeMillis() - start, "HH:mm:ss.SSSSSS")); } finally { serializer = null; } }
From source file:org.betaconceptframework.astroboa.test.engine.AbstractRepositoryTest.java
protected void serializeUsingJCR(CmsEntityType cmsEntity) { long start = System.currentTimeMillis(); String repositoryHomeDir = AstroboaClientContextHolder.getActiveClientContext().getRepositoryContext() .getCmsRepository().getRepositoryHomeDirectory(); File serializationHomeDir = new File( repositoryHomeDir + File.separator + CmsConstants.SERIALIZATION_DIR_NAME); File zipFile = new File(serializationHomeDir, "document" + DateUtils.format(Calendar.getInstance(), "ddMMyyyyHHmmss.sss") + ".zip"); OutputStream out = null;/*from ww w. j a v a 2 s . co m*/ ZipArchiveOutputStream os = null; try { if (!zipFile.exists()) { FileUtils.touch(zipFile); } out = new FileOutputStream(zipFile); os = (ZipArchiveOutputStream) new ArchiveStreamFactory().createArchiveOutputStream("zip", out); os.setFallbackToUTF8(true); //Serialize all repository using JCR os.putArchiveEntry(new ZipArchiveEntry("document-view.xml")); final Session session = getSession(); switch (cmsEntity) { case OBJECT: session.exportDocumentView(JcrNodeUtils.getContentObjectRootNode(session).getPath(), os, false, false); break; case REPOSITORY_USER: session.exportDocumentView(JcrNodeUtils.getRepositoryUserRootNode(session).getPath(), os, false, false); break; case TAXONOMY: session.exportDocumentView(JcrNodeUtils.getTaxonomyRootNode(session).getPath(), os, false, false); break; case ORGANIZATION_SPACE: session.exportDocumentView(JcrNodeUtils.getOrganizationSpaceNode(session).getPath(), os, false, false); break; case REPOSITORY: session.exportDocumentView(JcrNodeUtils.getCMSSystemNode(session).getPath(), os, false, false); break; default: break; } os.closeArchiveEntry(); os.finish(); os.close(); } catch (Exception e) { throw new CmsException(e); } finally { if (out != null) { IOUtils.closeQuietly(out); } if (os != null) { IOUtils.closeQuietly(os); } long serialzationDuration = System.currentTimeMillis() - start; logger.debug("Export entities using JCR finished in {} ", DurationFormatUtils.formatDurationHMS(serialzationDuration)); } }
From source file:org.cloudfoundry.util.FileUtils.java
private static void write(Path root, Path path, ZipArchiveOutputStream out) { try {//from w ww . j a v a 2s. c om if (Files.isSameFile(root, path)) { return; } ZipArchiveEntry entry = new ZipArchiveEntry(getRelativePathName(root, path)); entry.setUnixMode(getUnixMode(path)); entry.setLastModifiedTime(Files.getLastModifiedTime(path)); out.putArchiveEntry(entry); if (Files.isRegularFile(path)) { Files.copy(path, out); } out.closeArchiveEntry(); } catch (IOException e) { throw Exceptions.propagate(e); } }
From source file:org.codehaus.mojo.unix.maven.zip.ZipUnixPackage.java
private BasicPackageFileSystemObject<F2<UnixFsObject, ZipArchiveOutputStream, IoEffect>> directory( Directory directory) {//ww w.ja v a 2 s .c o m F2<UnixFsObject, ZipArchiveOutputStream, IoEffect> f = new F2<UnixFsObject, ZipArchiveOutputStream, IoEffect>() { public IoEffect f(final UnixFsObject file, final ZipArchiveOutputStream zos) { return new IoEffect() { public void run() throws IOException { String path = file.path.isBase() ? "." : file.path.asAbsolutePath("./") + "/"; ZipArchiveEntry entry = new ZipArchiveEntry(path); entry.setSize(file.size); entry.setTime(file.lastModified.toDateTime().getMillis()); if (file.attributes.mode.isSome()) { entry.setUnixMode(file.attributes.mode.some().toInt()); } zos.putArchiveEntry(entry); zos.closeArchiveEntry(); } }; } }; return basicPackageFSO(directory, f); }
From source file:org.codehaus.mojo.unix.maven.zip.ZipUnixPackage.java
private BasicPackageFileSystemObject<F2<UnixFsObject, ZipArchiveOutputStream, IoEffect>> file( final Fs<?> fromFile, UnixFsObject file) { F2<UnixFsObject, ZipArchiveOutputStream, IoEffect> f = new F2<UnixFsObject, ZipArchiveOutputStream, IoEffect>() { public IoEffect f(final UnixFsObject file, final ZipArchiveOutputStream zos) { return new IoEffect() { public void run() throws IOException { InputStream inputStream = null; BufferedReader reader = null; try { P2<InputStream, Option<Long>> p = filtersAndLineEndingHandingInputStream(file, fromFile.inputStream()); inputStream = p._1(); long size = p._2().orSome(file.size); ZipArchiveEntry entry = new ZipArchiveEntry(file.path.asAbsolutePath("./")); entry.setSize(size); entry.setTime(file.lastModified.toDateTime().getMillis()); if (file.attributes.mode.isSome()) { entry.setUnixMode(file.attributes.mode.some().toInt()); }/*from w ww . j a va2s. c o m*/ zos.putArchiveEntry(entry); copy(inputStream, zos, 1024 * 128); zos.closeArchiveEntry(); } finally { IOUtil.close(inputStream); IOUtil.close(reader); } } }; } }; return basicPackageFSO(file, f); }
From source file:org.dataconservancy.packaging.tool.impl.AnnotationDrivenPackageStateSerializerTest.java
@Test public void testDeserializeZipArchiveSimple() throws Exception { // produce a zip archive containing a single serialized stream for this test. ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(baos); ZipArchiveEntry zipEntry = new ZipArchiveEntry(StreamId.APPLICATION_VERSION.name()); zipOut.putArchiveEntry(zipEntry);/*from w w w . j a va 2 s .co m*/ IOUtils.copy(APPLICATION_VERSION_1.getInputStream(), zipOut); zipOut.closeArchiveEntry(); zipOut.close(); state = new PackageState(); when(mockedMarshallerMap.get(StreamId.APPLICATION_VERSION).getUnmarshaller().unmarshal(any(Source.class))) .thenReturn(applicationVersion); ByteArrayInputStream zipIn = new ByteArrayInputStream(baos.toByteArray()); underTest.deserialize(state, StreamId.APPLICATION_VERSION, zipIn); assertNotNull(state.getCreationToolVersion()); assertEquals(applicationVersion, state.getCreationToolVersion()); verify(mockedMarshallerMap.get(StreamId.APPLICATION_VERSION).getUnmarshaller()) .unmarshal(any(Source.class)); }
From source file:org.dspace.content.packager.AbstractMETSDisseminator.java
/** * Make a Zipped up METS package for the given DSpace Object * * @param context DSpace Context/*w ww .java 2 s . com*/ * @param dso The DSpace Object * @param params Parameters to the Packager script * @param pkg Package output stream * @throws PackageValidationException * @throws AuthorizeException * @throws SQLException * @throws IOException */ protected void writeZipPackage(Context context, DSpaceObject dso, PackageParameters params, OutputStream pkg) throws PackageValidationException, CrosswalkException, MetsException, AuthorizeException, SQLException, IOException { long lmTime = 0; if (dso.getType() == Constants.ITEM) { lmTime = ((Item) dso).getLastModified().getTime(); } // map of extra streams to put in Zip (these are located during makeManifest()) MdStreamCache extraStreams = new MdStreamCache(); ZipArchiveOutputStream zip = new ZipArchiveOutputStream(pkg); zip.setComment("METS archive created by DSpace " + Util.getSourceVersion()); Mets manifest = makeManifest(context, dso, params, extraStreams); // copy extra (metadata, license, etc) bitstreams into zip, update manifest if (extraStreams != null) { for (Map.Entry<MdRef, InputStream> ment : extraStreams.getMap().entrySet()) { MdRef ref = ment.getKey(); // Both Deposit Licenses & CC Licenses which are referenced as "extra streams" may already be // included in our Package (if their bundles are already included in the <filSec> section of manifest). // So, do a special check to see if we need to link up extra License <mdRef> entries to the bitstream in the <fileSec>. // (this ensures that we don't accidentally add the same License file to our package twice) linkLicenseRefsToBitstreams(context, params, dso, ref); //If this 'mdRef' is NOT already linked up to a file in the package, // then its file must be missing. So, we are going to add a new // file to the Zip package. if (ref.getXlinkHref() == null || ref.getXlinkHref().isEmpty()) { InputStream is = ment.getValue(); // create a hopefully unique filename within the Zip String fname = gensym("metadata"); // link up this 'mdRef' to point to that file ref.setXlinkHref(fname); if (log.isDebugEnabled()) { log.debug("Writing EXTRA stream to Zip: " + fname); } //actually add the file to the Zip package ZipArchiveEntry ze = new ZipArchiveEntry(fname); if (lmTime != 0) { ze.setTime(lmTime); } else //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged { ze.setTime(DEFAULT_MODIFIED_DATE); } zip.putArchiveEntry(ze); Utils.copy(is, zip); zip.closeArchiveEntry(); is.close(); } } } // write manifest after metadata. ZipArchiveEntry me = new ZipArchiveEntry(METSManifest.MANIFEST_FILE); if (lmTime != 0) { me.setTime(lmTime); } else //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged { me.setTime(DEFAULT_MODIFIED_DATE); } zip.putArchiveEntry(me); // can only validate now after fixing up extraStreams // note: only validate METS if specified (default = true) if (params.getBooleanProperty("validate", true)) { manifest.validate(new MetsValidator()); } manifest.write(new MetsWriter(zip)); zip.closeArchiveEntry(); //write any bitstreams associated with DSpace object to zip package addBitstreamsToZip(context, dso, params, zip); zip.close(); }
From source file:org.dspace.content.packager.AbstractMETSDisseminator.java
/** * Add Bitstreams associated with a given DSpace Object into an * existing ZipArchiveOutputStream// www. j a v a 2 s . c o m * @param context DSpace Context * @param dso The DSpace Object * @param params Parameters to the Packager script * @param zip Zip output */ protected void addBitstreamsToZip(Context context, DSpaceObject dso, PackageParameters params, ZipArchiveOutputStream zip) throws PackageValidationException, AuthorizeException, SQLException, IOException { // how to handle unauthorized bundle/bitstream: String unauth = (params == null) ? null : params.getProperty("unauthorized"); // copy all non-meta bitstreams into zip if (dso.getType() == Constants.ITEM) { Item item = (Item) dso; //get last modified time long lmTime = ((Item) dso).getLastModified().getTime(); Bundle bundles[] = item.getBundles(); for (int i = 0; i < bundles.length; i++) { if (includeBundle(bundles[i])) { // unauthorized bundle? if (!AuthorizeManager.authorizeActionBoolean(context, bundles[i], Constants.READ)) { if (unauth != null && (unauth.equalsIgnoreCase("skip"))) { log.warn("Skipping Bundle[\"" + bundles[i].getName() + "\"] because you are not authorized to read it."); continue; } else { throw new AuthorizeException( "Not authorized to read Bundle named \"" + bundles[i].getName() + "\""); } } Bitstream[] bitstreams = bundles[i].getBitstreams(); for (int k = 0; k < bitstreams.length; k++) { boolean auth = AuthorizeManager.authorizeActionBoolean(context, bitstreams[k], Constants.READ); if (auth || (unauth != null && unauth.equalsIgnoreCase("zero"))) { String zname = makeBitstreamURL(bitstreams[k], params); ZipArchiveEntry ze = new ZipArchiveEntry(zname); if (log.isDebugEnabled()) { log.debug(new StringBuilder().append("Writing CONTENT stream of bitstream(") .append(bitstreams[k].getID()).append(") to Zip: ").append(zname) .append(", size=").append(bitstreams[k].getSize()).toString()); } if (lmTime != 0) { ze.setTime(lmTime); } else //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged { ze.setTime(DEFAULT_MODIFIED_DATE); } ze.setSize(auth ? bitstreams[k].getSize() : 0); zip.putArchiveEntry(ze); if (auth) { InputStream input = bitstreams[k].retrieve(); Utils.copy(input, zip); input.close(); } else { log.warn("Adding zero-length file for Bitstream, SID=" + String.valueOf(bitstreams[k].getSequenceID()) + ", not authorized for READ."); } zip.closeArchiveEntry(); } else if (unauth != null && unauth.equalsIgnoreCase("skip")) { log.warn("Skipping Bitstream, SID=" + String.valueOf(bitstreams[k].getSequenceID()) + ", not authorized for READ."); } else { throw new AuthorizeException("Not authorized to read Bitstream, SID=" + String.valueOf(bitstreams[k].getSequenceID())); } } } } } // Coll, Comm just add logo bitstream to content if there is one else if (dso.getType() == Constants.COLLECTION || dso.getType() == Constants.COMMUNITY) { Bitstream logoBs = dso.getType() == Constants.COLLECTION ? ((Collection) dso).getLogo() : ((Community) dso).getLogo(); if (logoBs != null) { String zname = makeBitstreamURL(logoBs, params); ZipArchiveEntry ze = new ZipArchiveEntry(zname); if (log.isDebugEnabled()) { log.debug("Writing CONTENT stream of bitstream(" + String.valueOf(logoBs.getID()) + ") to Zip: " + zname + ", size=" + String.valueOf(logoBs.getSize())); } ze.setSize(logoBs.getSize()); //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged ze.setTime(DEFAULT_MODIFIED_DATE); zip.putArchiveEntry(ze); Utils.copy(logoBs.retrieve(), zip); zip.closeArchiveEntry(); } } }
From source file:org.eclipse.cbi.maven.plugins.macsigner.SignMojo.java
/** * Creates a zip file.//w w w . java 2s. com * @param dir The Directory of the files to be zipped. * @param zip An output stream to write the file * @throws IOException */ private void createZip(File dir, ZipArchiveOutputStream zip) throws IOException { Deque<File> dir_stack = new LinkedList<File>(); dir_stack.push(dir); // base path is the parent of the "Application.app" folder // it will be used to make "Application.app" the top-level folder in the zip String base_path = getParentDirAbsolutePath(dir); // verify that "dir" actually id the ".app" folder if (!dir.getName().endsWith(".app")) throw new IOException("Please verify the configuration. Directory does not end with '.app': " + dir); while (!dir_stack.isEmpty()) { File file = dir_stack.pop(); File[] files = file.listFiles(); for (File f : files) { String name = f.getAbsolutePath().substring(base_path.length()); getLog().debug("Found: " + name); if (f.isFile() && isInContentsFolder(name)) { getLog().debug("Adding to zip file for signing: " + f); ZipArchiveEntry entry = new ZipArchiveEntry(name); zip.putArchiveEntry(entry); if (f.canExecute()) { //work around to track the relative file names // of those that need to be set as executable on unZip executableFiles.add(name); } InputStream is = new FileInputStream(f); copyInputStreamToOutputStream(is, zip); is.close(); zip.closeArchiveEntry(); } else if (f.isDirectory() && isInContentsFolder(name)) { //add directory entry dir_stack.push(f); } else { getLog().debug(f + " was not included in the zip file to be signed."); } } } }
From source file:org.envirocar.app.util.Util.java
/** * Android devices up to version 2.3.7 have a bug in the native * Zip archive creation, making the archive unreadable with some * programs./*from w ww . j a v a 2s .c o m*/ * * @param files * the list of files of the target archive * @param target * the target filename * @throws IOException */ public static void zipInteroperable(List<File> files, String target) throws IOException { ZipArchiveOutputStream aos = null; OutputStream out = null; try { File tarFile = new File(target); out = new FileOutputStream(tarFile); try { aos = (ZipArchiveOutputStream) new ArchiveStreamFactory() .createArchiveOutputStream(ArchiveStreamFactory.ZIP, out); } catch (ArchiveException e) { throw new IOException(e); } for (File file : files) { ZipArchiveEntry entry = new ZipArchiveEntry(file, file.getName()); entry.setSize(file.length()); aos.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file), aos); aos.closeArchiveEntry(); } } catch (IOException e) { throw e; } finally { aos.finish(); out.close(); } }