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:com.amazon.aws.samplecode.travellog.util.DataExtractor.java

public void run() {
    try {/* w  ww  .  ja  v a  2  s . c om*/
        //Create temporary directory
        File tmpDir = File.createTempFile("travellog", "");
        tmpDir.delete(); //Wipe out temporary file to replace with a directory
        tmpDir.mkdirs();

        logger.log(Level.INFO, "Extract temp dir: " + tmpDir);

        //Store journal to props file
        Journal journal = dao.getJournal();
        Properties journalProps = buildProps(journal);
        File journalFile = new File(tmpDir, "journal");
        journalProps.store(new FileOutputStream(journalFile), "");

        //Iterate through entries and grab related photos
        List<Entry> entries = dao.getEntries(journal);
        int entryIndex = 1;
        int imageFileIndex = 1;
        for (Entry entry : entries) {
            Properties entryProps = buildProps(entry);
            File entryFile = new File(tmpDir, "entry." + (entryIndex++));
            entryProps.store(new FileOutputStream(entryFile), "");

            List<Photo> photos = dao.getPhotos(entry);
            int photoIndex = 1;
            for (Photo photo : photos) {
                Properties photoProps = buildProps(photo);

                InputStream photoData = S3PhotoUtil.loadOriginalPhoto(photo);
                String imageFileName = "imgdata." + (imageFileIndex++);
                File imageFile = new File(tmpDir, imageFileName);

                FileOutputStream outputStream = new FileOutputStream(imageFile);
                IOUtils.copy(photoData, outputStream);
                photoProps.setProperty("file", imageFileName);
                outputStream.close();
                photoData.close();

                File photoFile = new File(tmpDir, "photo." + (entryIndex - 1) + "." + (photoIndex++));
                photoProps.store(new FileOutputStream(photoFile), "");
            }

            List<Comment> comments = dao.getComments(entry);
            int commentIndex = 1;
            for (Comment comment : comments) {
                Properties commentProps = buildProps(comment);
                File commentFile = new File(tmpDir, "comment." + (entryIndex - 1) + "." + commentIndex++);
                commentProps.store(new FileOutputStream(commentFile), "");
            }
        }

        //Bundle up the folder as a zip
        final File zipOut;

        //If we have an output path store locally
        if (outputPath != null) {
            zipOut = new File(outputPath);
        } else {
            //storing to S3
            zipOut = File.createTempFile("export", ".zip");
        }

        zipOut.getParentFile().mkdirs(); //make sure directory structure is in place
        ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(zipOut);

        //Create the zip file
        File[] files = tmpDir.listFiles();
        for (File file : files) {
            ZipArchiveEntry archiveEntry = new ZipArchiveEntry(file.getName());
            byte[] fileData = FileUtils.readFileToByteArray(file);
            archiveEntry.setSize(fileData.length);
            zaos.putArchiveEntry(archiveEntry);
            zaos.write(fileData);
            zaos.flush();
            zaos.closeArchiveEntry();
        }
        zaos.close();

        //If outputpath
        if (outputPath == null) {
            TravelLogStorageObject obj = new TravelLogStorageObject();
            obj.setBucketName(bucketName);
            obj.setStoragePath(storagePath);
            obj.setData(FileUtils.readFileToByteArray(zipOut));
            obj.setMimeType("application/zip");

            S3StorageManager mgr = new S3StorageManager();
            mgr.store(obj, false, null); //Store with full redundancy and default permissions
        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }

}

From source file:com.atolcd.web.scripts.ZipContents.java

public void createZipFile(List<String> nodeIds, OutputStream os, boolean noaccent) throws IOException {
    File zip = null;/*from ww  w  .  j  a va  2s  . com*/

    try {
        if (nodeIds != null && !nodeIds.isEmpty()) {
            zip = TempFileProvider.createTempFile(TEMP_FILE_PREFIX, ZIP_EXTENSION);
            FileOutputStream stream = new FileOutputStream(zip);
            CheckedOutputStream checksum = new CheckedOutputStream(stream, new Adler32());
            BufferedOutputStream buff = new BufferedOutputStream(checksum);
            ZipArchiveOutputStream out = new ZipArchiveOutputStream(buff);
            out.setEncoding(encoding);
            out.setMethod(ZipArchiveOutputStream.DEFLATED);
            out.setLevel(Deflater.BEST_COMPRESSION);

            if (logger.isDebugEnabled()) {
                logger.debug("Using encoding '" + encoding + "' for zip file.");
            }

            try {
                for (String nodeId : nodeIds) {
                    NodeRef node = new NodeRef(storeRef, nodeId);
                    addToZip(node, out, noaccent, "");
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            } finally {
                out.close();
                buff.close();
                checksum.close();
                stream.close();

                if (nodeIds.size() > 0) {
                    InputStream in = new FileInputStream(zip);
                    try {
                        byte[] buffer = new byte[BUFFER_SIZE];
                        int len;

                        while ((len = in.read(buffer)) > 0) {
                            os.write(buffer, 0, len);
                        }
                    } finally {
                        IOUtils.closeQuietly(in);
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } finally {
        // try and delete the temporary file
        if (zip != null) {
            zip.delete();
        }
    }
}

From source file:com.excelsiorjet.api.util.Utils.java

public static void compressZipfile(File sourceDir, File outputFile) throws IOException {
    try (ZipArchiveOutputStream zipFile = new ZipArchiveOutputStream(
            new BufferedOutputStream(new FileOutputStream(outputFile)))) {
        compressDirectoryToZipfile(sourceDir.getAbsolutePath(), sourceDir.getAbsolutePath(), zipFile);
    }//w  w w  . jav  a 2 s.co m
}

From source file:gzipper.algorithms.Zip.java

@Override
public void run() {
    /*check whether archive with given name already exists; 
    if so, add index to file name an re-check*/
    if (_createArchive) {
        try {/*w  w w.  j av  a 2  s .  c  om*/
            File file = new File(_path + _archiveName + ".zip");
            while (file.exists()) {
                ++_nameIndex;
                _archiveName = _archiveName.substring(0, 7) + _nameIndex;
                file = new File(_path + _archiveName + ".zip");
            }
            _zos = new ZipArchiveOutputStream(
                    new BufferedOutputStream(new FileOutputStream(_path + _archiveName + ".zip")));
            _zos.setUseZip64(Zip64Mode.AsNeeded);
        } catch (IOException ex) {
            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, "Error creating output stream", ex);
            System.exit(1);
        }
    }
    while (_runFlag) {
        try {
            long startTime = System.nanoTime();

            if (_selectedFiles != null) {
                if (_createArchive != false) {
                    compress(_selectedFiles, "");
                } else {
                    extract(_path, _archiveName);
                }
            } else {
                throw new GZipperException("File selection must not be null");
            }
            _elapsedTime = System.nanoTime() - startTime;
            stop(); //stop thread after successful operation

        } catch (IOException | GZipperException ex) {
            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, "Error compressing archive", ex);
        } finally {
            stop(); //stop thread after successful operation
        }
    }
}

From source file:com.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testExtractBrokenSymlinkWithOwnerExecutePermissions() throws InterruptedException, IOException {
    assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS)));

    // Create a simple zip archive using apache's commons-compress to store executable info.
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        ZipArchiveEntry entry = new ZipArchiveEntry("link.txt");
        entry.setUnixMode((int) MostFiles.S_IFLNK);
        String target = "target.txt";
        entry.setSize(target.getBytes(Charsets.UTF_8).length);
        entry.setMethod(ZipEntry.STORED);

        // Mark the file as being executable.
        Set<PosixFilePermission> filePermissions = ImmutableSet.of(PosixFilePermission.OWNER_EXECUTE);

        long externalAttributes = entry.getExternalAttributes()
                + (MorePosixFilePermissions.toMode(filePermissions) << 16);
        entry.setExternalAttributes(externalAttributes);

        zip.putArchiveEntry(entry);//from   w ww  .  j a  v  a 2 s  .c o m
        zip.write(target.getBytes(Charsets.UTF_8));
        zip.closeArchiveEntry();
    }

    Path extractFolder = tmpFolder.newFolder();

    ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(),
            zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE);
    Path link = extractFolder.toAbsolutePath().resolve("link.txt");
    assertTrue(Files.isSymbolicLink(link));
    assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt"));
}

From source file:es.ucm.fdi.util.archive.ZipFormat.java

/**
 * Simulates creation of a zip file, but returns only the size of the zip
 * that results from the given input stream
 *//*from   w  w w.  ja  va2s .  com*/
public int compressedSize(InputStream is) throws IOException {
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ZipArchiveOutputStream zout = new ZipArchiveOutputStream(bos);) {
        zout.setMethod(ZipArchiveOutputStream.DEFLATED);
        ZipArchiveEntry entry = new ZipArchiveEntry("z");
        zout.putArchiveEntry(entry);
        int n;
        byte[] bytes = new byte[1024];
        while ((n = is.read(bytes)) > -1) {
            zout.write(bytes, 0, n);
        }
        is.close();
        zout.closeArchiveEntry();
        zout.finish();
        return bos.size();
    }
}

From source file:com.citytechinc.cq.component.maven.util.ComponentMojoUtil.java

/**
 * Add files to the already constructed Archive file by creating a new
 * Archive file, appending the contents of the existing Archive file to it,
 * and then adding additional entries for the newly constructed artifacts.
 * /*from w w w.  j  a v a2s .  c  om*/
 * @param classList
 * @param classLoader
 * @param classPool
 * @param buildDirectory
 * @param componentPathBase
 * @param defaultComponentPathSuffix
 * @param defaultComponentGroup
 * @param existingArchiveFile
 * @param tempArchiveFile
 * @throws OutputFailureException
 * @throws IOException
 * @throws InvalidComponentClassException
 * @throws InvalidComponentFieldException
 * @throws ParserConfigurationException
 * @throws TransformerException
 * @throws ClassNotFoundException
 * @throws CannotCompileException
 * @throws NotFoundException
 * @throws SecurityException
 * @throws NoSuchFieldException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws InstantiationException
 */
public static void buildArchiveFileForProjectAndClassList(List<CtClass> classList,
        WidgetRegistry widgetRegistry, TouchUIWidgetRegistry touchUIWidgetRegistry, ClassLoader classLoader,
        ClassPool classPool, File buildDirectory, String componentPathBase, String defaultComponentPathSuffix,
        String defaultComponentGroup, File existingArchiveFile, File tempArchiveFile,
        ComponentNameTransformer transformer, boolean generateTouchUiDialogs) throws OutputFailureException,
        IOException, InvalidComponentClassException, InvalidComponentFieldException,
        ParserConfigurationException, TransformerException, ClassNotFoundException, CannotCompileException,
        NotFoundException, SecurityException, NoSuchFieldException, IllegalArgumentException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException,
        TouchUIDialogWriteException, TouchUIDialogGenerationException {

    if (!existingArchiveFile.exists()) {
        throw new OutputFailureException("Archive file does not exist");
    }

    if (tempArchiveFile.exists()) {
        tempArchiveFile.delete();
    }

    tempArchiveFile.createNewFile();

    deleteTemporaryComponentOutputDirectory(buildDirectory);

    /*
     * Create archive input stream
     */
    ZipArchiveInputStream existingInputStream = new ZipArchiveInputStream(
            new FileInputStream(existingArchiveFile));

    /*
     * Create a zip archive output stream for the temp file
     */
    ZipArchiveOutputStream tempOutputStream = new ZipArchiveOutputStream(tempArchiveFile);

    /*
     * Iterate through all existing entries adding them to the new archive
     */
    ZipArchiveEntry curArchiveEntry;

    Set<String> existingArchiveEntryNames = new HashSet<String>();

    while ((curArchiveEntry = existingInputStream.getNextZipEntry()) != null) {
        existingArchiveEntryNames.add(curArchiveEntry.getName().toLowerCase());
        getLog().debug("Current File Name: " + curArchiveEntry.getName());
        tempOutputStream.putArchiveEntry(curArchiveEntry);
        IOUtils.copy(existingInputStream, tempOutputStream);
        tempOutputStream.closeArchiveEntry();
    }

    /*
     * Create content.xml within temp archive
     */
    ContentUtil.buildContentFromClassList(classList, tempOutputStream, existingArchiveEntryNames,
            buildDirectory, componentPathBase, defaultComponentPathSuffix, defaultComponentGroup, transformer);

    /*
     * Create Dialogs within temp archive
     */
    DialogUtil.buildDialogsFromClassList(transformer, classList, tempOutputStream, existingArchiveEntryNames,
            widgetRegistry, classLoader, classPool, buildDirectory, componentPathBase,
            defaultComponentPathSuffix);

    if (generateTouchUiDialogs) {
        TouchUIDialogUtil.buildDialogsFromClassList(classList, classLoader, classPool, touchUIWidgetRegistry,
                transformer, buildDirectory, componentPathBase, defaultComponentPathSuffix, tempOutputStream,
                existingArchiveEntryNames);
    }

    /*
     * Create edit config within temp archive
     */
    EditConfigUtil.buildEditConfigFromClassList(classList, tempOutputStream, existingArchiveEntryNames,
            buildDirectory, componentPathBase, defaultComponentPathSuffix, transformer);

    /*
     * Copy temp archive to the original archive position
     */
    tempOutputStream.finish();
    existingInputStream.close();
    tempOutputStream.close();

    existingArchiveFile.delete();
    tempArchiveFile.renameTo(existingArchiveFile);

}

From source file:com.excelsiorjet.maven.plugin.JetMojo.java

static void compressZipfile(File sourceDir, File outputFile) throws IOException {
    ZipArchiveOutputStream zipFile = new ZipArchiveOutputStream(
            new BufferedOutputStream(new FileOutputStream(outputFile)));
    compressDirectoryToZipfile(sourceDir.getAbsolutePath(), sourceDir.getAbsolutePath(), zipFile);
    IOUtils.closeQuietly(zipFile);//from  ww w . ja  va 2s  .  co m
}

From source file:eionet.cr.util.odp.ODPDatasetsPacker.java

/**
 * The main execution method.//from  ww w.  jav a  2  s .  c  o  m
 *
 * @param outputStream Output stream where the zipped file should be written into.
 *
 * @throws IOException If any sort of output stream writing error occurs.
 * @throws XMLStreamException Thrown by methods from the {@link XMLStreamWriter} that is used by called methods.
 */
public void execute(OutputStream outputStream) throws IOException, XMLStreamException {

    if (!isPrepareCalled) {
        throw new IllegalStateException("Prepare has not been called yet!");
    }

    int i = 0;
    ZipArchiveOutputStream zipOutput = null;
    try {
        zipOutput = new ZipArchiveOutputStream(outputStream);
        for (SubjectDTO indicatorSubject : indicatorSubjects) {
            createAndWriteDatasetEntry(zipOutput, indicatorSubject, i++);
        }
        createAndWriteManifestEntry(zipOutput);
    } finally {
        IOUtils.closeQuietly(zipOutput);
    }
}

From source file:fr.gael.dhus.datastore.processing.impl.ProcessProductPrepareDownload.java

/**
 * Creates a zip file at the specified path with the contents of the 
 * specified directory./*www .j  a  v  a  2s  . co m*/
 * @param Input directory path. The directory were is located directory to archive.
 * @param The full path of the zip file.
 * @return the checksum accordig to fr.gael.dhus.datastore.processing.impl.zip.digest variable.
 * @throws IOException If anything goes wrong
 */
protected Map<String, String> processZip(String inpath, File output) throws IOException {
    // Retrieve configuration settings
    String[] algorithms = cfgManager.getDownloadConfiguration().getChecksumAlgorithms().split(",");
    int compressionLevel = cfgManager.getDownloadConfiguration().getCompressionLevel();

    FileOutputStream fOut = null;
    BufferedOutputStream bOut = null;
    ZipArchiveOutputStream tOut = null;
    MultipleDigestOutputStream dOut = null;

    try {
        fOut = new FileOutputStream(output);
        if ((algorithms != null) && (algorithms.length > 0)) {
            try {
                dOut = new MultipleDigestOutputStream(fOut, algorithms);
                bOut = new BufferedOutputStream(dOut);
            } catch (NoSuchAlgorithmException e) {
                logger.error("Problem computing checksum algorithms.", e);
                dOut = null;
                bOut = new BufferedOutputStream(fOut);
            }

        } else
            bOut = new BufferedOutputStream(fOut);
        tOut = new ZipArchiveOutputStream(bOut);
        tOut.setLevel(compressionLevel);

        addFileToZip(tOut, inpath, "");
    } finally {
        try {
            tOut.finish();
            tOut.close();
            bOut.close();
            if (dOut != null)
                dOut.close();
            fOut.close();
        } catch (Exception e) {
            logger.error("Exception raised during ZIP stream close", e);
        }
    }
    if (dOut != null) {
        Map<String, String> checksums = new HashMap<String, String>();
        for (String algorithm : algorithms) {
            String chk = dOut.getMessageDigestAsHexadecimalString(algorithm);
            if (chk != null)
                checksums.put(algorithm, chk);
        }
        return checksums;
    }
    return null;
}