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

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

Introduction

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

Prototype

public ZipArchiveOutputStream(File file) throws IOException 

Source Link

Document

Creates a new ZIP OutputStream writing to a File.

Usage

From source file:org.apache.karaf.tooling.ArchiveMojo.java

public File archive(File source, File dest, Artifact artifact) throws //ArchiverException,
IOException {//from   w w w  .j  a  v a 2  s.  co  m
    String serverName = null;
    if (targetFile != null) {
        serverName = targetFile.getName();
    } else {
        serverName = artifact.getArtifactId() + "-" + artifact.getVersion();
    }
    dest = new File(dest, serverName + "." + artifact.getType());

    String prefix = "";
    if (usePathPrefix) {
        prefix = pathPrefix.trim();
        if (prefix.length() > 0 && !prefix.endsWith("/")) {
            prefix += "/";
        }
    }

    if ("tar.gz".equals(artifact.getType())) {
        try (OutputStream fOut = Files.newOutputStream(dest.toPath());
                OutputStream bOut = new BufferedOutputStream(fOut);
                OutputStream gzOut = new GzipCompressorOutputStream(bOut);
                TarArchiveOutputStream tOut = new TarArchiveOutputStream(gzOut);
                DirectoryStream<Path> children = Files.newDirectoryStream(source.toPath())

        ) {
            tOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
            tOut.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);
            for (Path child : children) {
                addFileToTarGz(tOut, child, prefix);
            }
        }
    } else if ("zip".equals(artifact.getType())) {
        try (OutputStream fOut = Files.newOutputStream(dest.toPath());
                OutputStream bOut = new BufferedOutputStream(fOut);
                ZipArchiveOutputStream tOut = new ZipArchiveOutputStream(bOut);
                DirectoryStream<Path> children = Files.newDirectoryStream(source.toPath())

        ) {
            for (Path child : children) {
                addFileToZip(tOut, child, prefix);
            }
        }
    } else {
        throw new IllegalArgumentException("Unknown target type: " + artifact.getType());
    }

    return dest;
}

From source file:org.apache.openejb.maven.plugin.BuildTomEEMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    super.execute();

    if (formats == null) {
        formats = Collections.emptyMap();
    }//from w w w . j av a2 s  .c  o m

    String prefix = catalinaBase.getParentFile().getAbsolutePath();
    if (!prefix.endsWith(File.separator)) {
        prefix += File.separator;
    }
    if (skipArchiveRootFolder) {
        prefix += catalinaBase.getName() + File.separator;
    }

    if (zip || formats.containsKey("zip")) {
        getLog().info("Zipping Custom TomEE Distribution");

        final String zip = formats.get("zip");
        final File output = zip != null ? new File(zip) : zipFile;
        try (final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new FileOutputStream(output))) {
            for (final String entry : catalinaBase.list()) {
                zip(zos, new File(catalinaBase, entry), prefix);
            }
        } catch (final IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }

        attach("zip", output);
    }
    if (formats != null) {
        formats.remove("zip"); //handled previously for compatibility

        for (final Map.Entry<String, String> format : formats.entrySet()) {
            final String key = format.getKey();
            getLog().info(key + "-ing Custom TomEE Distribution");

            if ("tar.gz".equals(key)) {
                final String out = format.getValue();
                final File output = out != null ? new File(out)
                        : new File(base.getParentFile(), base.getName() + "." + key);
                Files.mkdirs(output.getParentFile());

                try (final TarArchiveOutputStream tarGz = new TarArchiveOutputStream(
                        new GZIPOutputStream(new FileOutputStream(output)))) {
                    tarGz.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
                    for (final String entry : catalinaBase.list()) {
                        tarGz(tarGz, new File(catalinaBase, entry), prefix);
                    }
                } catch (final IOException e) {
                    throw new MojoExecutionException(e.getMessage(), e);
                }

                attach(key, output);
            } else {
                throw new MojoExecutionException(key + " format not supported");
            }
        }
    }
}

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

/**
 * Creates the distribution file.//  w  w  w .jav  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 zipDir(String zipFile, String dir) throws IOException {
    File dirObj = new File(dir);
    ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(zipFile));
    log.info("Creating : " + zipFile);
    try {//from   w  ww.  j a v  a  2s .  c om
        addDir(dirObj, out, "");
    } finally {
        out.close();
    }
}

From source file:org.apache.tika.batch.fs.FSOutputStreamFactory.java

/**
 * This tries to create a file based on the {@link org.apache.tika.batch.fs.FSUtil.HANDLE_EXISTING}
 * value that was passed in during initialization.
 * <p>//w w  w.j  av  a  2  s .  c o  m
 * If {@link #handleExisting} is set to "SKIP" and the output file already exists,
 * this will return null.
 * <p>
 * If an output file can be found, this will try to mkdirs for that output file.
 * If mkdirs() fails, this will throw an IOException.
 * <p>
 * Finally, this will open an output stream for the appropriate output file.
 * @param metadata must have a value set for FSMetadataProperties.FS_ABSOLUTE_PATH or
 *                 else NullPointerException will be thrown!
 * @return OutputStream
 * @throws java.io.IOException, NullPointerException
 */
@Override
public OutputStream getOutputStream(Metadata metadata) throws IOException {
    String initialRelativePath = metadata.get(FSProperties.FS_REL_PATH);
    Path outputPath = FSUtil.getOutputPath(outputRoot, initialRelativePath, handleExisting, suffix);
    if (outputPath == null) {
        return null;
    }
    if (!Files.isDirectory(outputPath.getParent())) {
        Files.createDirectories(outputPath.getParent());
        //TODO: shouldn't need this any more in java 7, right?
        if (!Files.isDirectory(outputPath.getParent())) {
            throw new IOException("Couldn't create parent directory for:" + outputPath.toAbsolutePath());
        }
    }

    OutputStream os = Files.newOutputStream(outputPath);
    switch (compression) {
    case BZIP2:
        os = new BZip2CompressorOutputStream(os);
        break;
    case GZIP:
        os = new GZIPOutputStream(os);
        break;
    case ZIP:
        os = new ZipArchiveOutputStream(os);
        break;
    }
    return new BufferedOutputStream(os);
}

From source file:org.apache.tika.parser.pkg.TikaArchiveStreamFactory.java

@Override
public ArchiveOutputStream createArchiveOutputStream(final String archiverName, final OutputStream out,
        final String actualEncoding) throws ArchiveException {
    if (archiverName == null) {
        throw new IllegalArgumentException("Archivername must not be null.");
    }/*from w  ww. java 2 s .  c o  m*/
    if (out == null) {
        throw new IllegalArgumentException("OutputStream must not be null.");
    }

    if (AR.equalsIgnoreCase(archiverName)) {
        return new ArArchiveOutputStream(out);
    }
    if (ZIP.equalsIgnoreCase(archiverName)) {
        final ZipArchiveOutputStream zip = new ZipArchiveOutputStream(out);
        if (actualEncoding != null) {
            zip.setEncoding(actualEncoding);
        }
        return zip;
    }
    if (TAR.equalsIgnoreCase(archiverName)) {
        if (actualEncoding != null) {
            return new TarArchiveOutputStream(out, actualEncoding);
        }
        return new TarArchiveOutputStream(out);
    }
    if (JAR.equalsIgnoreCase(archiverName)) {
        if (actualEncoding != null) {
            return new JarArchiveOutputStream(out, actualEncoding);
        }
        return new JarArchiveOutputStream(out);
    }
    if (CPIO.equalsIgnoreCase(archiverName)) {
        if (actualEncoding != null) {
            return new CpioArchiveOutputStream(out, actualEncoding);
        }
        return new CpioArchiveOutputStream(out);
    }
    if (SEVEN_Z.equalsIgnoreCase(archiverName)) {
        throw new StreamingNotSupportedException(SEVEN_Z);
    }

    final ArchiveStreamProvider archiveStreamProvider = getArchiveOutputStreamProviders()
            .get(toKey(archiverName));
    if (archiveStreamProvider != null) {
        return archiveStreamProvider.createArchiveOutputStream(archiverName, out, actualEncoding);
    }

    throw new ArchiveException("Archiver: " + archiverName + " not found.");
}

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>// w  w  w  .  j  av  a2s  .  c o 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

public void writeTo(Map<String, byte[]> parts, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {
    ZipArchiveOutputStream zip = new ZipArchiveOutputStream(entityStream);

    zip.setMethod(ZipArchiveOutputStream.STORED);

    for (Map.Entry<String, byte[]> entry : parts.entrySet()) {
        zipStoreBuffer(zip, entry.getKey(), entry.getValue());
    }/*  ww  w .j  a va 2s. co  m*/

    zip.close();
}

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

public static ArchiveOutputStream createArchiveOutputStream(OutputStream outputStream, ArchiveType archiveType)
        throws IOException {
    ArchiveOutputStream result = null;/*ww  w .  ja  v a 2 s  .c  om*/
    switch (archiveType) {
    case ZIP:
        result = new ZipArchiveOutputStream(outputStream);
        break;
    case TAR:
        result = new TarArchiveOutputStream(outputStream);
        ((TarArchiveOutputStream) result).setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        break;
    case TARGZ:
        result = new TarArchiveOutputStream(new GzipCompressorOutputStream(outputStream));
        ((TarArchiveOutputStream) result).setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        break;
    case TGZ:
        result = new TarArchiveOutputStream(new GzipCompressorOutputStream(outputStream));
        ((TarArchiveOutputStream) result).setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        break;
    }

    if (result == null) {
        throw new IllegalArgumentException("Unsupported archive type: '" + archiveType + "'");
    }

    return result;
}

From source file:org.callimachusproject.io.CarOutputStream.java

public CarOutputStream(OutputStream out) throws IOException {
    this.zipStream = new ZipArchiveOutputStream(out);
    zipStream.setUseZip64(Zip64Mode.Always);
}