Example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry ZipArchiveEntry

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry ZipArchiveEntry

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry ZipArchiveEntry.

Prototype

public ZipArchiveEntry(ZipArchiveEntry entry) throws ZipException 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

From source file:org.apache.sis.internal.maven.Assembler.java

/**
 * Creates the distribution file./* w  ww .  j a  v  a2  s. c  o m*/
 *
 * @throws MojoExecutionException if the plugin execution failed.
 */
@Override
public void execute() throws MojoExecutionException {
    final File sourceDirectory = new File(rootDirectory, ARTIFACT_PATH);
    if (!sourceDirectory.isDirectory()) {
        throw new MojoExecutionException("Directory not found: " + sourceDirectory);
    }
    final File targetDirectory = new File(rootDirectory, TARGET_DIRECTORY);
    final String version = project.getVersion();
    final String artifactBase = FINALNAME_PREFIX + version;
    try {
        final File targetFile = new File(distributionDirectory(targetDirectory), artifactBase + ".zip");
        final ZipArchiveOutputStream zip = new ZipArchiveOutputStream(targetFile);
        try {
            zip.setLevel(9);
            appendRecursively(sourceDirectory, artifactBase, zip, new byte[8192]);
            /*
             * At this point, all the "application/sis-console/src/main/artifact" and sub-directories
             * have been zipped.  Now generate the Pack200 file and zip it directly (without creating
             * a temporary "sis.pack.gz" file).
             */
            final Packer packer = new Packer(project.getName(), project.getUrl(), version, targetDirectory);
            final ZipArchiveEntry entry = new ZipArchiveEntry(
                    artifactBase + '/' + LIB_DIRECTORY + '/' + FATJAR_FILE + PACK_EXTENSION);
            entry.setMethod(ZipArchiveEntry.STORED);
            zip.putArchiveEntry(entry);
            packer.preparePack200(FATJAR_FILE + ".jar").pack(new FilterOutputStream(zip) {
                /*
                 * Closes the archive entry, not the ZIP file.
                 */
                @Override
                public void close() throws IOException {
                    zip.closeArchiveEntry();
                }
            });
        } finally {
            zip.close();
        }
    } catch (IOException e) {
        throw new MojoExecutionException(e.getLocalizedMessage(), e);
    }
}

From source file:org.apache.slider.tools.TestUtility.java

public static void addDir(File dirObj, ZipArchiveOutputStream zipFile, String prefix) throws IOException {
    for (File file : dirObj.listFiles()) {
        if (file.isDirectory()) {
            addDir(file, zipFile, prefix + file.getName() + File.separator);
        } else {// w ww. ja v a 2s .c  o m
            log.info("Adding to zip - " + prefix + file.getName());
            zipFile.putArchiveEntry(new ZipArchiveEntry(prefix + file.getName()));
            IOUtils.copy(new FileInputStream(file), zipFile);
            zipFile.closeArchiveEntry();
        }
    }
}

From source file:org.apache.tika.parser.utils.ZipSalvager.java

/**
 * This streams the broken zip and rebuilds a new zip that
 * is at least a valid zip file.  The contents of the final stream
 * may be truncated, but the result should be a valid zip file.
 * <p>//from w ww  .j  a v a 2s .co  m
 * This does nothing fancy to fix the underlying broken zip.
 *
 * @param brokenZip
 * @param salvagedZip
 */
public static void salvageCopy(InputStream brokenZip, File salvagedZip) {
    try (ZipArchiveOutputStream outputStream = new ZipArchiveOutputStream(salvagedZip)) {
        ZipArchiveInputStream zipArchiveInputStream = new ZipArchiveInputStream(brokenZip);
        ZipArchiveEntry zae = zipArchiveInputStream.getNextZipEntry();
        while (zae != null) {
            try {
                if (!zae.isDirectory() && zipArchiveInputStream.canReadEntryData(zae)) {
                    //create a new ZAE and copy over only the name so that
                    //if there is bad info (e.g. CRC) in brokenZip's zae, that
                    //won't be propagated or cause an exception
                    outputStream.putArchiveEntry(new ZipArchiveEntry(zae.getName()));
                    //this will copy an incomplete stream...so there
                    //could be truncation of the xml/contents, but the zip file
                    //should be intact.
                    boolean successfullyCopied = false;
                    try {
                        IOUtils.copy(zipArchiveInputStream, outputStream);
                        successfullyCopied = true;
                    } catch (IOException e) {
                        //this can hit a "truncated ZipFile" IOException
                    }
                    outputStream.flush();
                    outputStream.closeArchiveEntry();
                    if (!successfullyCopied) {
                        break;
                    }
                }
                zae = zipArchiveInputStream.getNextZipEntry();
            } catch (ZipException | EOFException e) {
                break;
            }

        }
        outputStream.flush();
        outputStream.finish();

    } catch (IOException e) {
        LOG.warn("problem fixing zip", e);
    }
}

From source file:org.apache.tika.server.writer.ZipWriter.java

private static void zipStoreBuffer(ZipArchiveOutputStream zip, String name, byte[] dataBuffer)
        throws IOException {
    ZipEntry zipEntry = new ZipEntry(name != null ? name : UUID.randomUUID().toString());
    zipEntry.setMethod(ZipOutputStream.STORED);

    zipEntry.setSize(dataBuffer.length);
    CRC32 crc32 = new CRC32();
    crc32.update(dataBuffer);/*from ww  w  .ja  va2 s .  c  o  m*/
    zipEntry.setCrc(crc32.getValue());

    try {
        zip.putArchiveEntry(new ZipArchiveEntry(zipEntry));
    } catch (ZipException ex) {
        if (name != null) {
            zipStoreBuffer(zip, "x-" + name, dataBuffer);
            return;
        }
    }

    zip.write(dataBuffer);

    zip.closeArchiveEntry();
}

From source file:org.artifactory.util.ArchiveUtils.java

/**
 * Use for writing streams - must specify file size in advance as well
 *//*from   w ww  . j a  v  a  2s. c om*/
public static ArchiveEntry createArchiveEntry(String relativePath, ArchiveType archiveType, long size) {
    switch (archiveType) {
    case ZIP:
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(relativePath);
        zipEntry.setSize(size);
        return zipEntry;
    case TAR:
    case TARGZ:
    case TGZ:
        TarArchiveEntry tarEntry = new TarArchiveEntry(relativePath);
        tarEntry.setSize(size);
        return tarEntry;
    }
    throw new IllegalArgumentException("Unsupported archive type: '" + archiveType + "'");
}

From source file:org.beangle.commons.archiver.ZipUtils.java

public static File zip(List<String> fileNames, String zipPath, String encoding) {
    try {// ww  w  .j  a v  a 2  s  . c om
        FileOutputStream f = new FileOutputStream(zipPath);
        ZipArchiveOutputStream zos = (ZipArchiveOutputStream) new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.ZIP, f);
        if (null != encoding) {
            zos.setEncoding(encoding);
        }
        for (int i = 0; i < fileNames.size(); i++) {
            String fileName = fileNames.get(i);
            String entryName = StringUtils.substringAfterLast(fileName, File.separator);
            ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
            zos.putArchiveEntry(entry);
            FileInputStream fis = new FileInputStream(fileName);
            IOUtils.copy(fis, zos);
            fis.close();
            zos.closeArchiveEntry();
        }
        zos.close();
        return new File(zipPath);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.beangle.ems.util.ZipUtils.java

/**
 * <p>//from ww w .j a va 2  s. co m
 * zip.
 * </p>
 * 
 * @param fileNames a {@link java.util.List} object.
 * @param zipPath a {@link java.lang.String} object.
 * @param encoding a {@link java.lang.String} object.
 * @return a {@link java.io.File} object.
 */
public static File zip(List<String> fileNames, String zipPath, String encoding) {
    try {
        FileOutputStream f = new FileOutputStream(zipPath);
        ZipArchiveOutputStream zos = (ZipArchiveOutputStream) new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.ZIP, f);
        if (null != encoding) {
            zos.setEncoding(encoding);
        }
        for (int i = 0; i < fileNames.size(); i++) {
            String fileName = fileNames.get(i);
            String entryName = Strings.substringAfterLast(fileName, File.separator);
            ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
            zos.putArchiveEntry(entry);
            FileInputStream fis = new FileInputStream(fileName);
            IOs.copy(fis, zos);
            fis.close();
            zos.closeArchiveEntry();
        }
        zos.close();
        return new File(zipPath);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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;/*  w ww . j  av a 2s  . 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  w w w  .  j ava2s  . c  o 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.callimachusproject.io.CarOutputStream.java

private synchronized void putArchiveEntry(String name, long time, String type, MetaTypeExtraField mtype)
        throws IOException {
    if (!closed.add(name))
        throw new IllegalStateException("Entry has already been added: " + name);
    ZipArchiveEntry entry = new ZipArchiveEntry(name);
    entry.setTime(time);//  w w w  .  ja v a2 s  . c o  m
    entry.addExtraField(mtype);
    if (type != null) {
        entry.addExtraField(new ContentTypeExtraField(type));
    }
    zipStream.putArchiveEntry(entry);
}