List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream setComment
public void setComment(String comment)
From source file:com.ikon.util.ArchiveUtils.java
/** * Recursively create ZIP archive from directory *//*from w ww. j a va 2s .co m*/ public static void createZip(File path, String root, OutputStream os) throws IOException { log.debug("createZip({}, {}, {})", new Object[] { path, root, os }); if (path.exists() && path.canRead()) { ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(os); zaos.setComment("Generated by openkm"); zaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS); zaos.setUseLanguageEncodingFlag(true); zaos.setFallbackToUTF8(true); zaos.setEncoding("UTF-8"); // Prevents java.util.zip.ZipException: ZIP file must have at least one entry ZipArchiveEntry zae = new ZipArchiveEntry(root + "/"); zaos.putArchiveEntry(zae); zaos.closeArchiveEntry(); createZipHelper(path, zaos, root); zaos.flush(); zaos.finish(); zaos.close(); } else { throw new IOException("Can't access " + path); } log.debug("createZip: void"); }
From source file:com.openkm.util.ArchiveUtils.java
/** * Recursively create ZIP archive from directory *//*w ww . j av a2s . c o m*/ public static void createZip(File path, String root, OutputStream os) throws IOException { log.debug("createZip({}, {}, {})", new Object[] { path, root, os }); if (path.exists() && path.canRead()) { ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(os); zaos.setComment("Generated by OpenKM"); zaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS); zaos.setUseLanguageEncodingFlag(true); zaos.setFallbackToUTF8(true); zaos.setEncoding("UTF-8"); // Prevents java.util.zip.ZipException: ZIP file must have at least one entry ZipArchiveEntry zae = new ZipArchiveEntry(root + "/"); zaos.putArchiveEntry(zae); zaos.closeArchiveEntry(); createZipHelper(path, zaos, root); zaos.flush(); zaos.finish(); zaos.close(); } else { throw new IOException("Can't access " + path); } log.debug("createZip: void"); }
From source file:com.openkm.util.ArchiveUtils.java
/** * Create ZIP archive from file//from w w w . ja v a2s.com */ public static void createZip(File path, OutputStream os) throws IOException { log.debug("createZip({}, {})", new Object[] { path, os }); if (path.exists() && path.canRead()) { ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(os); zaos.setComment("Generated by OpenKM"); zaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS); zaos.setUseLanguageEncodingFlag(true); zaos.setFallbackToUTF8(true); zaos.setEncoding("UTF-8"); log.debug("FILE {}", path); ZipArchiveEntry zae = new ZipArchiveEntry(path.getName()); zaos.putArchiveEntry(zae); FileInputStream fis = new FileInputStream(path); IOUtils.copy(fis, zaos); fis.close(); zaos.closeArchiveEntry(); zaos.flush(); zaos.finish(); zaos.close(); } else { throw new IOException("Can't access " + path); } log.debug("createZip: void"); }
From source file:com.gitblit.utils.CompressionUtils.java
/** * Zips the contents of the tree at the (optionally) specified revision and * the (optionally) specified basepath to the supplied outputstream. * //from ww w . j a va 2 s. c o m * @param repository * @param basePath * if unspecified, entire repository is assumed. * @param objectId * if unspecified, HEAD is assumed. * @param os * @return true if repository was successfully zipped to supplied output * stream */ public static boolean zip(Repository repository, String basePath, String objectId, OutputStream os) { RevCommit commit = JGitUtils.getCommit(repository, objectId); if (commit == null) { return false; } boolean success = false; RevWalk rw = new RevWalk(repository); TreeWalk tw = new TreeWalk(repository); try { tw.reset(); tw.addTree(commit.getTree()); ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os); zos.setComment("Generated by Gitblit"); if (!StringUtils.isEmpty(basePath)) { PathFilter f = PathFilter.create(basePath); tw.setFilter(f); } tw.setRecursive(true); MutableObjectId id = new MutableObjectId(); ObjectReader reader = tw.getObjectReader(); long modified = commit.getAuthorIdent().getWhen().getTime(); while (tw.next()) { FileMode mode = tw.getFileMode(0); if (mode == FileMode.GITLINK || mode == FileMode.TREE) { continue; } tw.getObjectId(id, 0); ZipArchiveEntry entry = new ZipArchiveEntry(tw.getPathString()); entry.setSize(reader.getObjectSize(id, Constants.OBJ_BLOB)); entry.setComment(commit.getName()); entry.setUnixMode(mode.getBits()); entry.setTime(modified); zos.putArchiveEntry(entry); ObjectLoader ldr = repository.open(id); ldr.copyTo(zos); zos.closeArchiveEntry(); } zos.finish(); success = true; } catch (IOException e) { error(e, repository, "{0} failed to zip files from commit {1}", commit.getName()); } finally { tw.release(); rw.dispose(); } return success; }
From source file:com.eucalyptus.www.X509Download.java
private static byte[] getX509Zip(User u) throws Exception { X509Certificate cloudCert = null; final X509Certificate x509; String userAccessKey = null;// ww w . ja va 2 s. c o m String userSecretKey = null; KeyPair keyPair = null; try { for (AccessKey k : u.getKeys()) { if (k.isActive()) { userAccessKey = k.getAccessKey(); userSecretKey = k.getSecretKey(); } } if (userAccessKey == null) { AccessKey k = u.createKey(); userAccessKey = k.getAccessKey(); userSecretKey = k.getSecretKey(); } keyPair = Certs.generateKeyPair(); x509 = Certs.generateCertificate(keyPair, u.getName()); x509.checkValidity(); u.addCertificate(x509); cloudCert = SystemCredentials.lookup(Eucalyptus.class).getCertificate(); } catch (Exception e) { LOG.fatal(e, e); throw e; } ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(byteOut); ZipArchiveEntry entry = null; String fingerPrint = Certs.getFingerPrint(keyPair.getPublic()); if (fingerPrint != null) { String baseName = X509Download.NAME_SHORT + "-" + u.getName() + "-" + fingerPrint.replaceAll(":", "").toLowerCase().substring(0, 8); zipOut.setComment("To setup the environment run: source /path/to/eucarc"); StringBuilder sb = new StringBuilder(); //TODO:GRZE:FIXME velocity String userNumber = u.getAccount().getAccountNumber(); sb.append("EUCA_KEY_DIR=$(cd $(dirname ${BASH_SOURCE:-$0}); pwd -P)"); final Optional<String> computeUrl = remotePublicify(Compute.class); if (computeUrl.isPresent()) { sb.append(entryFor("EC2_URL", null, computeUrl)); } else { sb.append("\necho WARN: Eucalyptus URL is not configured. >&2"); ServiceBuilder<? extends ServiceConfiguration> builder = ServiceBuilders.lookup(Compute.class); ServiceConfiguration localConfig = builder.newInstance(Internets.localHostAddress(), Internets.localHostAddress(), Internets.localHostAddress(), Eucalyptus.INSTANCE.getPort()); sb.append("\nexport EC2_URL=" + ServiceUris.remotePublicify(localConfig)); } sb.append(entryFor("S3_URL", "An OSG is either not registered or not configured. S3_URL is not set. " + "Please register an OSG and/or set a valid s3 endpoint and download credentials again. " + "Or set S3_URL manually to http://OSG-IP:8773/services/objectstorage", remotePublicify(ObjectStorage.class))); sb.append(entryFor("EUARE_URL", "EUARE URL is not configured.", remotePublicify(Euare.class))); sb.append(entryFor("TOKEN_URL", "TOKEN URL is not configured.", remotePublicify(Tokens.class))); sb.append(entryFor("AWS_AUTO_SCALING_URL", "Auto Scaling service URL is not configured.", remotePublicify(AutoScaling.class))); sb.append(entryFor("AWS_CLOUDFORMATION_URL", null, remotePublicify(CloudFormation.class))); sb.append(entryFor("AWS_CLOUDWATCH_URL", "Cloud Watch service URL is not configured.", remotePublicify(CloudWatch.class))); sb.append(entryFor("AWS_ELB_URL", "Load Balancing service URL is not configured.", remotePublicify(LoadBalancing.class))); sb.append("\nexport EUSTORE_URL=" + StackConfiguration.DEFAULT_EUSTORE_URL); sb.append("\nexport EC2_PRIVATE_KEY=${EUCA_KEY_DIR}/" + baseName + "-pk.pem"); sb.append("\nexport EC2_CERT=${EUCA_KEY_DIR}/" + baseName + "-cert.pem"); sb.append("\nexport EC2_JVM_ARGS=-Djavax.net.ssl.trustStore=${EUCA_KEY_DIR}/jssecacerts"); sb.append("\nexport EUCALYPTUS_CERT=${EUCA_KEY_DIR}/cloud-cert.pem"); sb.append("\nexport EC2_ACCOUNT_NUMBER='" + u.getAccount().getAccountNumber() + "'"); sb.append("\nexport EC2_ACCESS_KEY='" + userAccessKey + "'"); sb.append("\nexport EC2_SECRET_KEY='" + userSecretKey + "'"); sb.append("\nexport AWS_ACCESS_KEY='" + userAccessKey + "'"); sb.append("\nexport AWS_SECRET_KEY='" + userSecretKey + "'"); sb.append("\nexport AWS_CREDENTIAL_FILE=${EUCA_KEY_DIR}/iamrc"); sb.append("\nexport EC2_USER_ID='" + userNumber + "'"); sb.append( "\nalias ec2-bundle-image=\"ec2-bundle-image --cert ${EC2_CERT} --privatekey ${EC2_PRIVATE_KEY} --user ${EC2_ACCOUNT_NUMBER} --ec2cert ${EUCALYPTUS_CERT}\""); sb.append( "\nalias ec2-upload-bundle=\"ec2-upload-bundle -a ${EC2_ACCESS_KEY} -s ${EC2_SECRET_KEY} --url ${S3_URL}\""); sb.append("\n"); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("eucarc")); entry.setUnixMode(0600); zipOut.write(sb.toString().getBytes("UTF-8")); zipOut.closeArchiveEntry(); sb = new StringBuilder(); sb.append("AWSAccessKeyId=").append(userAccessKey).append('\n'); sb.append("AWSSecretKey=").append(userSecretKey); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("iamrc")); entry.setUnixMode(0600); zipOut.write(sb.toString().getBytes("UTF-8")); zipOut.closeArchiveEntry(); /** write the private key to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry("cloud-cert.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes(cloudCert)); zipOut.closeArchiveEntry(); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("jssecacerts")); entry.setUnixMode(0600); KeyStore tempKs = KeyStore.getInstance("jks"); tempKs.load(null); tempKs.setCertificateEntry("eucalyptus", cloudCert); ByteArrayOutputStream bos = new ByteArrayOutputStream(); tempKs.store(bos, "changeit".toCharArray()); zipOut.write(bos.toByteArray()); zipOut.closeArchiveEntry(); /** write the private key to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-pk.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes("RSA PRIVATE KEY", Crypto.getCertificateProvider().getEncoded(keyPair.getPrivate()))); zipOut.closeArchiveEntry(); /** write the X509 certificate to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-cert.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes(x509)); zipOut.closeArchiveEntry(); } /** close the zip output stream and return the bytes **/ zipOut.close(); return byteOut.toByteArray(); }
From source file:org.apache.ant.compress.taskdefs.Zip.java
private void configure(ZipArchiveOutputStream o) { o.setLevel(level);//from w w w. ja v a2 s .com o.setComment(comment); o.setFallbackToUTF8(fallBackToUTF8); o.setUseLanguageEncodingFlag(useLanguageEncodingFlag); o.setCreateUnicodeExtraFields(createUnicodeExtraFields.getPolicy()); o.setUseZip64(zip64Mode.getPolicy()); }
From source file:org.dspace.content.packager.AbstractMETSDisseminator.java
/** * Make a Zipped up METS package for the given DSpace Object * * @param context DSpace Context//from ww w .j a v a2 s.co m * @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.mycore.services.zipper.MCRZipServlet.java
@Override protected ZipArchiveOutputStream createContainer(ServletOutputStream sout, String comment) { ZipArchiveOutputStream zout = new ZipArchiveOutputStream(new BufferedOutputStream(sout)); zout.setComment(comment); zout.setLevel(Deflater.BEST_COMPRESSION); return zout;// ww w . j av a 2 s . c om }