Example usage for java.util.zip ZipOutputStream ZipOutputStream

List of usage examples for java.util.zip ZipOutputStream ZipOutputStream

Introduction

In this page you can find the example usage for java.util.zip ZipOutputStream ZipOutputStream.

Prototype

public ZipOutputStream(OutputStream out) 

Source Link

Document

Creates a new ZIP output stream.

Usage

From source file:io.wcm.tooling.commons.contentpackagebuilder.ContentPackage.java

/**
 * @param os Output stream/*  w w w.  j av  a 2s.  c o  m*/
 * @throws IOException
 */
ContentPackage(PackageMetadata metadata, OutputStream os) throws IOException {
    this.metadata = metadata;
    this.zip = new ZipOutputStream(os);

    this.transformerFactory = TransformerFactory.newInstance();
    this.transformerFactory.setAttribute("indent-number", 2);
    try {
        this.transformer = transformerFactory.newTransformer();
        this.transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        this.transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    } catch (TransformerException ex) {
        throw new RuntimeException("Failed to set up XML transformer: " + ex.getMessage(), ex);
    }

    this.xmlContentBuilder = new XmlContentBuilder(metadata.getXmlNamespaces());

    buildPackageMetadata();
}

From source file:ch.silviowangler.dox.export.DoxExporterImpl.java

@Override
public File export() throws IOException {

    logger.info("About to export repository");

    final Set<ch.silviowangler.dox.api.DocumentClass> documentClasses = documentService.findDocumentClasses();

    if (!documentClasses.isEmpty()) {
        File target = new File(new File(System.getProperty("java.io.tmpdir")),
                "DOX-Export-" + System.currentTimeMillis() + ".zip");

        logger.debug("Creating new ZIP file '{}'", target.getAbsolutePath());
        target.createNewFile();//from  ww w  . j av a  2  s .  co m

        try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(target))) {

            Repository repository = retrieveRepository(documentClasses);

            // do work on current file
            XStream xStream = getXStreamForRepository();

            final String data = xStream.toXML(repository);
            logXml(xStream, repository);
            writeToZipOutputStream(out, data, "repository.xml");

            // Process files
            xStream = getXStreamDocument();
            final Set<DocumentReference> documentReferences = documentService.retrieveAllDocumentReferences();

            logger.debug("Found {} document references to export", documentReferences.size());

            for (DocumentReference documentReference : documentReferences) {
                logger.debug("Processing document reference {}", documentReference.getId());
                logXml(xStream, documentReference);
                writeToZipOutputStream(out, xStream.toXML(documentReference),
                        "repository/" + documentReference.getHash() + ".xml");

                try {
                    PhysicalDocument physicalDocument = documentService
                            .findPhysicalDocument(documentReference.getId());
                    writeToZipOutputStream(out, physicalDocument.getContent(),
                            "repository/" + documentReference.getHash() + ".bin");
                } catch (DocumentNotFoundException | DocumentNotInStoreException e) {
                    logger.error("Unable to retrieve physical document for document with id {} (hash: '{}')",
                            documentReference.getId(), documentReference.getHash());
                }
            }
            out.finish();
            return target;

        } catch (IOException e) {
            logger.error("Unable to create ZIP file {}", target.getAbsolutePath(), e);
            throw e;
        }
    }
    logger.warn("There are no document classes. There is nothing to export. Aborting");
    throw new IllegalStateException("There is nothing to export");
}

From source file:com.joliciel.talismane.machineLearning.AbstractMachineLearningModel.java

@Override
public final void persist(File modelFile) {
    try {/*from   w w w  . ja va  2 s. com*/
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(modelFile, false));
        Writer writer = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));

        zos.putNextEntry(new ZipEntry("algorithm.txt"));
        writer.write(this.getAlgorithm().name());
        writer.flush();
        zos.flush();

        for (String descriptorKey : descriptors.keySet()) {
            zos.putNextEntry(new ZipEntry(descriptorKey + "_descriptors.txt"));
            List<String> descriptorList = descriptors.get(descriptorKey);
            for (String descriptor : descriptorList) {
                writer.write(descriptor + "\n");
                writer.flush();
            }
            zos.flush();

        }

        zos.putNextEntry(new ZipEntry("attributes.txt"));
        for (String name : this.modelAttributes.keySet()) {
            String value = this.modelAttributes.get(name);
            writer.write(name + "\t" + value + "\n");
            writer.flush();
        }

        for (String name : this.dependencies.keySet()) {
            Object dependency = this.dependencies.get(name);
            zos.putNextEntry(new ZipEntry(name + "_dependency.obj"));
            ObjectOutputStream oos = new ObjectOutputStream(zos);
            try {
                oos.writeObject(dependency);
            } finally {
                oos.flush();
            }
            zos.flush();
        }

        this.persistOtherEntries(zos);

        if (this.externalResources != null) {
            zos.putNextEntry(new ZipEntry("externalResources.obj"));
            ObjectOutputStream oos = new ObjectOutputStream(zos);
            try {
                oos.writeObject(externalResources);
            } finally {
                oos.flush();
            }
            zos.flush();
        }

        this.writeDataToStream(zos);

        zos.putNextEntry(new ZipEntry("model.bin"));
        this.writeModelToStream(zos);
        zos.flush();

        zos.close();
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    }
}

From source file:eu.openanalytics.rsb.message.MultiFilesResult.java

/**
 * Zips all the files contained in a multifiles result except if the result is
 * not successful, in that case returns the first file (which should be the only
 * one and contain a plain text error message).
 * //w w  w  . j a  va2 s.  co  m
 * @param result
 * @return
 * @throws FileNotFoundException
 * @throws IOException
 */
public static File zipResultFilesIfNotError(final MultiFilesResult result)
        throws FileNotFoundException, IOException {
    final File[] resultFiles = result.getPayload();

    if ((!result.isSuccess()) && (resultFiles.length == 1)) {
        return resultFiles[0];
    }

    final File resultZipFile = new File(result.getTemporaryDirectory(), result.getJobId() + ".zip");
    final ZipOutputStream resultZOS = new ZipOutputStream(new FileOutputStream(resultZipFile));

    for (final File resultFile : resultFiles) {
        resultZOS.putNextEntry(new ZipEntry(resultFile.getName()));

        final FileInputStream fis = new FileInputStream(resultFile);
        IOUtils.copy(fis, resultZOS);
        IOUtils.closeQuietly(fis);

        resultZOS.closeEntry();
    }

    IOUtils.closeQuietly(resultZOS);
    return resultZipFile;
}

From source file:de.berlios.jedi.logic.editor.JispPackageJispFileStorer.java

/**
 * Gets the equivalent JispFile for the JispPackage.
 * /*from w w  w. ja  v a 2  s .  co  m*/
 * @return The JispFile.
 * @throws JispIncompletePackageException
 *             If metadata or icons aren't complete.
 * @throws UnsupportedOperationException
 *             If server doesn't support UTF-8 encoding.
 */
public JispFile toJispFile() throws JispIncompletePackageException, UnsupportedOperationException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    outZipped = new ZipOutputStream(out);

    store();

    try {
        outZipped.close();
    } catch (IOException e) {
        LogFactory.getLog(JispPackageJispFileStorer.class).warn("The ZipOutputStream couldn't be closed", e);
    }

    return new JispFile(out.toByteArray());
}

From source file:herddb.upgrade.ZIPUtils.java

public static byte[] createZipFromDirectory(File directory, Charset fileNamesCharset,
        ZipEnhancer additionalData) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    String source = directory.getAbsolutePath().replace("\\", "/");
    int skipprefix = source.length();
    try (ZipOutputStream zos = new ZipOutputStream(out);) {
        addFileToZip(skipprefix, directory, zos);
        if (additionalData != null) {
            additionalData.accept(zos);//  w w w . j  av  a 2s .c  om
        }
    }
    return out.toByteArray();
}

From source file:com.jaspersoft.jasperserver.export.io.ZipOutput.java

public void open() {
    try {//from w w  w  . j av  a  2 s.  c om
        zipOut = new ZipOutputStream(getOutputStream());
        zipOut.setLevel(level);
    } catch (IOException e) {
        log.error(e);
        throw new JSExceptionWrapper(e);
    }

    directories = new HashSet();
}

From source file:de.nx42.maps4cim.util.Compression.java

/**
 * Compresses the input file using the zip file format and stores the
 * resulting zip file in the desired location
 * @param input the file to compress//w w w.j  a  va 2 s . c o  m
 * @param zipOutput the resulting zip file
 * @return the resulting zip file
 * @throws IOException if there is an error accessing the input file or
 * writing the output zip file
 */
public static File storeAsZip(File input, File zipOutput) throws IOException {
    // create new zip output stream
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipOutput));
    ZipEntry ze = new ZipEntry(input.getName());
    zos.putNextEntry(ze);

    // use file as input stream and copy bytes
    InputStream in = new FileInputStream(input);
    ByteStreams.copy(in, zos);

    // close current zip entry and all streams
    zos.closeEntry();
    in.close();
    zos.close();
    return zipOutput;
}

From source file:com.controlj.green.modstat.work.ModstatWork.java

@Override
public void run() {
    final ZipOutputStream zout;
    ByteArrayOutputStream out = new ByteArrayOutputStream(10000);
    zout = new ZipOutputStream(out);

    try {/*w w  w .  j a v a  2 s.co  m*/

        connection.runReadAction(FieldAccessFactory.newFieldAccess(), new ReadAction() {

            public void execute(@NotNull SystemAccess access) throws Exception {
                Location root = access.getTree(SystemTree.Network).resolve(rootPath);

                Collection<ModuleStatus> aspects = root.find(ModuleStatus.class, Acceptors.acceptAll());

                synchronized (this) {
                    progressLimit = aspects.size();
                }

                for (ModuleStatus aspect : aspects) {
                    Location location = aspect.getLocation();
                    try {
                        if (!location.getAspect(Device.class).isOutOfService()) {
                            String path = getReferencePath(location);

                            //System.out.println("Gathering modstat from "+path);

                            ZipEntry entry = new ZipEntry(path + ".txt");
                            entry.setMethod(ZipEntry.DEFLATED);
                            zout.putNextEntry(entry);
                            IOUtils.copy(new StringReader(aspect.getReportText()), zout);
                            zout.closeEntry();

                            synchronized (this) {
                                progress++;
                                if (isInterrupted()) {
                                    error = new Exception("Gathering Modstats interrupted");
                                    return;
                                }
                            }
                        }
                    } catch (NoSuchAspectException e) { // skip and go to the next one
                    }
                }

            }
        });
    } catch (Exception e) {
        synchronized (this) {
            error = e;
        }
        return;
    } finally {
        try {
            zout.close();
        } catch (IOException e) {
        } // we tried our best
    }
    if (!hasError()) {
        cache = out.toByteArray();
    }
}

From source file:biz.c24.io.spring.batch.writer.source.ZipFileWriterSource.java

@Override
public void initialise(StepExecution stepExecution) {
    // Extract the name of the file we're supposed to be writing to
    String fileName = resource != null ? resource.getPath()
            : stepExecution.getJobParameters().getString("output.file");

    // Remove any leading file:// if it exists
    if (fileName.startsWith("file://")) {
        fileName = fileName.substring("file://".length());
    }/* w  w  w .  ja  v  a 2s.  c  o m*/

    // Now create the name of our zipEntry
    // Strip off the leading path and the suffix (ie the zip extension)
    int tailStarts = fileName.lastIndexOf(pathSepString) + 1;
    int tailEnds = fileName.lastIndexOf('.');
    if (tailStarts < 0) {
        tailStarts = 0;
    }
    if (tailEnds < 0) {
        tailEnds = fileName.length();
    }

    String tailName = fileName.substring(tailStarts, tailEnds);

    try {
        FileOutputStream fileStream = new FileOutputStream(fileName);
        zipStream = new ZipOutputStream(fileStream);
        zipStream.putNextEntry(new ZipEntry(tailName));
        outputWriter = new OutputStreamWriter(zipStream, getEncoding());
    } catch (IOException ioEx) {
        throw new RuntimeException(ioEx);
    }

}