Example usage for org.apache.commons.compress.archivers ArchiveStreamFactory ZIP

List of usage examples for org.apache.commons.compress.archivers ArchiveStreamFactory ZIP

Introduction

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

Prototype

String ZIP

To view the source code for org.apache.commons.compress.archivers ArchiveStreamFactory ZIP.

Click Source Link

Document

Constant used to identify the ZIP archive format.

Usage

From source file:com.mediaworx.ziputils.Zipper.java

/**
 * Creates a new zip file.//w w  w  . ja  va  2  s  .  c om
 * @param zipFilename           filename for the zip
 * @param zipTargetFolderPath   path of the target folder where the zip should be stored (it will be created if it
 *                              doesn't exist)
 * @throws IOException Exceptions from the underlying package framework are bubbled up
 */
public Zipper(String zipFilename, String zipTargetFolderPath) throws IOException {

    File targetFolder = new File(zipTargetFolderPath);
    if (!targetFolder.exists()) {
        FileUtils.forceMkdir(targetFolder);
    }

    if (!zipTargetFolderPath.endsWith(File.separator)) {
        zipTargetFolderPath = zipTargetFolderPath.concat(File.separator);
    }
    zipOutputStream = new FileOutputStream(zipTargetFolderPath + zipFilename);
    try {
        zip = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, zipOutputStream);
    } catch (ArchiveException e) {
        // This should never happen, because "zip" is a known archive type, but let's log it anyway
        LOG.error("Cant create an archive of type " + ArchiveStreamFactory.ZIP);
    }
}

From source file:net.sf.util.zip.FileNameUtil.java

/**
 *
 * @param fileName the file name// w w  w  .  j a  v a 2  s . c om
 * @return  Archive file type, as defined in ArchiveStreamFactory
 */
public static String getArchieveFileType(String fileName) {
    String s = fileName.toLowerCase();
    if (s.endsWith(".jar") || s.endsWith(".war") || s.endsWith(".ear"))
        return ArchiveStreamFactory.JAR;
    else if (s.endsWith(".tar"))
        return ArchiveStreamFactory.TAR;
    else if (s.endsWith(".zip"))
        return ArchiveStreamFactory.ZIP;

    return null;
}

From source file:com.synopsys.integration.util.CommonZipExpander.java

private void expandUnknownFile(File unknownFile, File targetExpansionDirectory)
        throws IOException, IntegrationException, ArchiveException {
    String format;//w w  w  .  j  a va 2  s  .  c  om
    // we need to use an InputStream where inputStream.markSupported() == true
    try (InputStream i = new BufferedInputStream(Files.newInputStream(unknownFile.toPath()))) {
        format = new ArchiveStreamFactory().detect(i);
    }

    beforeExpansion(unknownFile, targetExpansionDirectory);

    // in the case of zip files, commons-compress creates, but does not close, the ZipFile. To avoid this unclosed resource, we handle it ourselves.
    try {
        if (ArchiveStreamFactory.ZIP.equals(format)) {
            try (ZipFile zipFile = new ZipFile(unknownFile)) {
                expander.expand(zipFile, targetExpansionDirectory);
            }
        } else {
            expander.expand(unknownFile, targetExpansionDirectory);
        }
    } catch (IOException | ArchiveException e) {
        logger.error("Couldn't extract the archive file - check the file's permissions: " + e.getMessage());
        throw e;
    }

    afterExpansion(unknownFile, targetExpansionDirectory);
}

From source file:algorithm.ZipPackaging.java

@Override
protected List<RestoredFile> restore(File zipFile) throws IOException {
    List<RestoredFile> extractedFiles = new ArrayList<RestoredFile>();
    try {//from  w  ww. j  a  va  2s.c  o m
        InputStream inputStream = new FileInputStream(zipFile);
        ArchiveInputStream archiveInputStream = new ArchiveStreamFactory()
                .createArchiveInputStream(ArchiveStreamFactory.ZIP, inputStream);
        ZipArchiveEntry entry = (ZipArchiveEntry) archiveInputStream.getNextEntry();
        while (entry != null) {
            RestoredFile extractedFile = new RestoredFile(RESTORED_DIRECTORY + entry.getName());
            OutputStream outputStream = new FileOutputStream(extractedFile);
            IOUtils.copy(archiveInputStream, outputStream);
            outputStream.close();
            extractedFiles.add(extractedFile);
            entry = (ZipArchiveEntry) archiveInputStream.getNextEntry();
        }
        archiveInputStream.close();
        inputStream.close();
    } catch (ArchiveException e) {
    }
    for (RestoredFile file : extractedFiles) {
        file.algorithm = this;
        file.checksumValid = true;
        file.restorationNote = "The algorithm doesn't alter these files, so they are brought to its original state. No checksum validation executed.";
        // every file in a .zip archive is a payload file!
        file.wasPayload = true;
        /*
         * Checksum validation isn't executed, because the PayloadSegment
         * class isn't used and therewith the checksums of the original
         * files are unknown.
         */
        for (RestoredFile relatedFile : extractedFiles) {
            if (file != relatedFile) {
                file.relatedFiles.add(relatedFile);
            }
        }
    }
    return extractedFiles;
}

From source file:consulo.cold.runner.execute.target.artifacts.Generator.java

public void buildDistributionInArchive(String distZip, @Nullable String jdkArchivePath, String path,
        String archiveOutType) throws Exception {
    myListener.info("Build: " + path);

    ArchiveStreamFactory factory = new ArchiveStreamFactory();

    final File fileZip = new File(myDistPath, distZip);

    final List<String> executables = Arrays.asList(ourExecutable);

    try (OutputStream pathStream = createOutputStream(archiveOutType, path)) {
        ArchiveOutputStream archiveOutputStream = factory.createArchiveOutputStream(archiveOutType, pathStream);
        if (archiveOutputStream instanceof TarArchiveOutputStream) {
            ((TarArchiveOutputStream) archiveOutputStream).setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        }/* w  w w.j  a v a2 s  .  com*/

        // move Consulo to archive, and change permissions
        try (InputStream is = new FileInputStream(fileZip)) {
            try (ArchiveInputStream ais = factory.createArchiveInputStream(ArchiveStreamFactory.ZIP, is)) {
                ArchiveEntry tempEntry = ais.getNextEntry();
                while (tempEntry != null) {
                    final ArchiveEntryWrapper newEntry = createEntry(archiveOutType, tempEntry.getName(),
                            tempEntry);

                    newEntry.setMode(extractMode(tempEntry));
                    newEntry.setTime(tempEntry.getLastModifiedDate().getTime());

                    if (executables.contains(tempEntry.getName())) {
                        newEntry.setMode(0b111_101_101);
                    }

                    copyEntry(archiveOutputStream, ais, tempEntry, newEntry);

                    tempEntry = ais.getNextEntry();
                }
            }
        }

        boolean mac = distZip.contains("mac");

        // jdk check
        if (jdkArchivePath != null) {
            try (InputStream is = new FileInputStream(jdkArchivePath)) {
                try (GzipCompressorInputStream gz = new GzipCompressorInputStream(is)) {
                    try (ArchiveInputStream ais = factory.createArchiveInputStream(ArchiveStreamFactory.TAR,
                            gz)) {
                        ArchiveEntry tempEntry = ais.getNextEntry();
                        while (tempEntry != null) {
                            final String name = tempEntry.getName();

                            // is our path
                            if (!mac && name.startsWith("jre/")) {
                                final ArchiveEntryWrapper jdkEntry = createEntry(archiveOutType,
                                        "Consulo/platform/buildSNAPSHOT/" + name, tempEntry);
                                jdkEntry.setMode(extractMode(tempEntry));
                                jdkEntry.setTime(tempEntry.getLastModifiedDate().getTime());

                                copyEntry(archiveOutputStream, ais, tempEntry, jdkEntry);
                            } else if (mac && name.startsWith("jdk")) {
                                boolean needAddToArchive = true;
                                for (String prefix : ourMacSkipJdkList) {
                                    if (name.startsWith(prefix)) {
                                        needAddToArchive = false;
                                    }
                                }

                                if (needAddToArchive) {
                                    final ArchiveEntryWrapper jdkEntry = createEntry(archiveOutType,
                                            "Consulo.app/Contents/platform/buildSNAPSHOT/jre/" + name,
                                            tempEntry);
                                    jdkEntry.setMode(extractMode(tempEntry));
                                    jdkEntry.setTime(tempEntry.getLastModifiedDate().getTime());

                                    copyEntry(archiveOutputStream, ais, tempEntry, jdkEntry);
                                }
                            }

                            tempEntry = ais.getNextEntry();
                        }
                    }
                }
            }
        }

        archiveOutputStream.finish();
    }
}

From source file:io.magentys.maven.DonutMojo.java

private void zipDonutReport() throws IOException, ArchiveException {
    Optional<File> file = FileUtils
            .listFiles(outputDirectory, new RegexFileFilter("^(.*)donut-report.html$"), TrueFileFilter.INSTANCE)
            .stream().findFirst();/* w  w w . j  a  v  a2s  .  com*/
    if (!file.isPresent())
        throw new FileNotFoundException(
                String.format("Cannot find a donut report in folder: %s", outputDirectory.getAbsolutePath()));
    File zipFile = new File(outputDirectory, FilenameUtils.removeExtension(file.get().getName()) + ".zip");
    try (OutputStream os = new FileOutputStream(zipFile);
            ArchiveOutputStream aos = new ArchiveStreamFactory()
                    .createArchiveOutputStream(ArchiveStreamFactory.ZIP, os);
            BufferedInputStream is = new BufferedInputStream(new FileInputStream(file.get()))) {
        aos.putArchiveEntry(new ZipArchiveEntry(file.get().getName()));
        IOUtils.copy(is, aos);
        aos.closeArchiveEntry();
        aos.finish();
    }
}

From source file:consulo.cold.runner.execute.target.artifacts.Generator.java

private OutputStream createOutputStream(String type, String prefix) throws Exception {
    final String fileName;
    if (type.equals(ArchiveStreamFactory.ZIP)) {
        fileName = prefix + ".zip";
    } else if (type.equals(ArchiveStreamFactory.TAR)) {
        fileName = prefix + ".tar.gz";
    } else {/*from w w w  .  ja  v a2s . com*/
        throw new IllegalArgumentException(type);
    }

    File child = new File(myTargetDir, fileName);

    final OutputStream outputStream = new FileOutputStream(child);
    if (type.equals(ArchiveStreamFactory.TAR)) {
        return new GzipCompressorOutputStream(outputStream);
    }
    return outputStream;
}

From source file:big.BigZip.java

/**
  * Copies one file into the big archive
  * @param fileToCopy/*from   www  . j  a  va2 s . co m*/
  * @return 
  */
public boolean writeFile(final File fileToCopy) {

    // declare
    ByteArrayOutputStream outputZipStream = new ByteArrayOutputStream();
    try {
        /* Create Archive Output Stream that attaches File Output Stream / and specifies type of compression */
        ArchiveOutputStream logical_zip = new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputZipStream);
        /* Create Archieve entry - write header information*/
        logical_zip.putArchiveEntry(new ZipArchiveEntry(fileToCopy.getName()));
        /* Copy input file */
        IOUtils.copy(new FileInputStream(fileToCopy), logical_zip);
        logical_zip.closeArchiveEntry();
        logical_zip.finish();
        logical_zip.flush();
        logical_zip.close();

        // get the bytes
        final ByteArrayInputStream byteInput = new ByteArrayInputStream(outputZipStream.toByteArray());

        byte[] buffer = new byte[8192];
        int length, counter = 0;
        // add the magic number to this file block
        outputStream.write(magicSignature.getBytes());
        // now copy the whole file into the BIG archive
        while ((length = byteInput.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
            counter += length;
        }
        // if there is something else to be flushed, do it now
        outputStream.flush();

        // calculate the base path
        final String resultingPath = fileToCopy.getAbsolutePath().replace(basePath, "");

        // calculate the SHA1 signature
        final String output = utils.hashing.checksum.generateFileChecksum("SHA-1", fileToCopy);

        // write a new line in our index file
        writerFileIndex.write(
                "\n" + utils.files.getPrettyFileSize(currentPosition) + " " + output + " " + resultingPath);
        // increase the position counter
        currentPosition += counter + magicSignature.length();
    } catch (Exception e) {
        System.err.println("BIG346 - Error copying file: " + fileToCopy.getAbsolutePath());
        return false;
    }

    finally {
    }
    return true;
}

From source file:net.duckling.ddl.service.export.impl.ExportServiceImpl.java

private ArchiveOutputStream getArchiveOutputStream(HttpServletResponse resp) {
    ArchiveOutputStream aos = null;//from w  ww . j  a v  a  2s  .  c o  m
    try {
        aos = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP,
                resp.getOutputStream());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    } catch (ArchiveException e) {
        LOG.error(e.getMessage(), e);
    }
    return aos;
}

From source file:big.BigZip.java

/**
 * Copies one file into the big archive//from   w  w w .  j  av a2  s  .co m
 * @param fileToCopy
 * @param SHA1
 * @param filePathToWriteInTextLine
 * @return 
 */
public boolean quickWrite(final File fileToCopy, final String SHA1, final String filePathToWriteInTextLine) {
    // declare
    ByteArrayOutputStream outputZipStream = new ByteArrayOutputStream();
    try {
        // save this operation on the log of commits
        addTagStarted(fileToCopy.getName());
        //pointRestoreAndSave(fileToCopy);

        /* Create Archive Output Stream that attaches File Output Stream / and specifies type of compression */
        ArchiveOutputStream logical_zip = new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputZipStream);
        /* Create Archieve entry - write header information*/
        logical_zip.putArchiveEntry(new ZipArchiveEntry(fileToCopy.getName()));
        /* Copy input file */
        IOUtils.copy(new FileInputStream(fileToCopy), logical_zip);
        logical_zip.closeArchiveEntry();
        logical_zip.finish();
        logical_zip.flush();
        logical_zip.close();

        // get the bytes
        final ByteArrayInputStream byteInput = new ByteArrayInputStream(outputZipStream.toByteArray());

        byte[] buffer = new byte[8192];
        int length, counter = 0;
        // add the magic number to this file block
        outputStream.write(magicSignature.getBytes());
        // now copy the whole file into the BIG archive
        while ((length = byteInput.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
            counter += length;
        }
        // if there is something else to be flushed, do it now
        //outputStream.flush();

        // calculate the base path
        //final String resultingPath = fileToCopy.getAbsolutePath().replace(rootFolder, "");

        final String line = "\n" + utils.files.getPrettyFileSize(currentPosition) + " " + SHA1 + " "
                + filePathToWriteInTextLine;

        // write a new line in our index file
        writerFileIndex.write(line);
        //writer.flush();
        // increase the position counter
        currentPosition += counter + magicSignature.length();

        // close the log with success
        addTagEnded();
    } catch (Exception e) {
        System.err.println("BIG600 - Error copying file: " + fileToCopy.getAbsolutePath());
        return false;
    } finally {
    }
    return true;
}