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:Zip.java

/**
 * Create a Writer on a given file, transparently compressing the data to a
 * Zip file whose name is the provided file path, with a ".zip" extension
 * added.//w  w w.j av a  2s  .  c  om
 *
 * @param file the file (with no zip extension)
 *
 * @return a writer on the zip entry
 */
public static Writer createWriter(File file) {
    try {
        String path = file.getCanonicalPath();
        FileOutputStream fos = new FileOutputStream(path + ".zip");
        ZipOutputStream zos = new ZipOutputStream(fos);
        ZipEntry ze = new ZipEntry(file.getName());
        zos.putNextEntry(ze);

        return new OutputStreamWriter(zos);
    } catch (FileNotFoundException ex) {
        System.err.println(ex.toString());
        System.err.println(file + " not found");
    } catch (Exception ex) {
        System.err.println(ex.toString());
    }

    return null;
}

From source file:org.syncope.core.scheduling.ReportJob.java

@Override
public void execute(final JobExecutionContext context) throws JobExecutionException {

    Report report = reportDAO.find(reportId);
    if (report == null) {
        throw new JobExecutionException("Report " + reportId + " not found");
    }/* w  w  w.  j  a va2  s.c  o m*/

    // 1. create execution
    ReportExec execution = new ReportExec();
    execution.setStatus(ReportExecStatus.STARTED);
    execution.setStartDate(new Date());
    execution.setReport(report);
    execution = reportExecDAO.save(execution);

    // 2. define a SAX handler for generating result as XML
    TransformerHandler handler;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    zos.setLevel(Deflater.BEST_COMPRESSION);
    try {
        SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        handler = transformerFactory.newTransformerHandler();
        Transformer serializer = handler.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");

        // a single ZipEntry in the ZipOutputStream
        zos.putNextEntry(new ZipEntry(report.getName()));

        // streaming SAX handler in a compressed byte array stream
        handler.setResult(new StreamResult(zos));
    } catch (Exception e) {
        throw new JobExecutionException("While configuring for SAX generation", e, true);
    }

    execution.setStatus(ReportExecStatus.RUNNING);
    execution = reportExecDAO.save(execution);

    ConfigurableListableBeanFactory beanFactory = ApplicationContextManager.getApplicationContext()
            .getBeanFactory();

    // 3. actual report execution
    StringBuilder reportExecutionMessage = new StringBuilder();
    StringWriter exceptionWriter = new StringWriter();
    try {
        // report header
        handler.startDocument();
        AttributesImpl atts = new AttributesImpl();
        atts.addAttribute("", "", ATTR_NAME, XSD_STRING, report.getName());
        handler.startElement("", "", ELEMENT_REPORT, atts);

        // iterate over reportlet instances defined for this report
        for (ReportletConf reportletConf : report.getReportletConfs()) {
            Class reportletClass = null;
            try {
                reportletClass = Class.forName(reportletConf.getReportletClassName());
            } catch (ClassNotFoundException e) {
                LOG.error("Reportlet class not found: {}", reportletConf.getReportletClassName(), e);

            }

            if (reportletClass != null) {
                Reportlet autowired = (Reportlet) beanFactory.createBean(reportletClass,
                        AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
                autowired.setConf(reportletConf);

                // invoke reportlet
                try {
                    autowired.extract(handler);
                } catch (Exception e) {
                    execution.setStatus(ReportExecStatus.FAILURE);

                    Throwable t = e instanceof ReportException ? e.getCause() : e;
                    exceptionWriter.write(t.getMessage() + "\n\n");
                    t.printStackTrace(new PrintWriter(exceptionWriter));
                    reportExecutionMessage.append(exceptionWriter.toString()).append("\n==================\n");
                }
            }
        }

        // report footer
        handler.endElement("", "", ELEMENT_REPORT);
        handler.endDocument();

        if (!ReportExecStatus.FAILURE.name().equals(execution.getStatus())) {

            execution.setStatus(ReportExecStatus.SUCCESS);
        }
    } catch (Exception e) {
        execution.setStatus(ReportExecStatus.FAILURE);

        exceptionWriter.write(e.getMessage() + "\n\n");
        e.printStackTrace(new PrintWriter(exceptionWriter));
        reportExecutionMessage.append(exceptionWriter.toString());

        throw new JobExecutionException(e, true);
    } finally {
        try {
            zos.closeEntry();
            zos.close();
            baos.close();
        } catch (IOException e) {
            LOG.error("While closing StreamResult's backend", e);
        }

        execution.setExecResult(baos.toByteArray());
        execution.setMessage(reportExecutionMessage.toString());
        execution.setEndDate(new Date());
        reportExecDAO.save(execution);
    }
}

From source file:ZipUtilTest.java

public void testUnpackEntryFromStreamToFile() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File file = File.createTempFile("temp", null);
    try {/*w w w .  j  a  v  a2s . co  m*/
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file));
        try {
            zos.putNextEntry(new ZipEntry(name));
            zos.write(contents);
            zos.closeEntry();
        } finally {
            IOUtils.closeQuietly(zos);
        }

        FileInputStream fis = new FileInputStream(file);

        File outputFile = File.createTempFile("temp-output", null);

        boolean result = ZipUtil.unpackEntry(fis, name, outputFile);
        assertTrue(result);

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(outputFile));
        byte[] actual = new byte[1024];
        int read = bis.read(actual);
        bis.close();

        assertEquals(new String(contents), new String(actual, 0, read));
    } finally {
        FileUtils.deleteQuietly(file);
    }
}

From source file:ch.admin.suis.msghandler.util.ZipUtils.java

/**
 * Creates a new unique ZIP file in the destination directory and adds to it
 * the provided collection of files.//from   www .  ja  v a  2s.c  o  m
 *
 * @param toDir The name of the file created
 * @param files The files to compress
 * @return A Zipped File
 * @throws IOException if the file cannot be created because of a IO error
 */
public static File compress(File toDir, Collection<File> files) throws IOException {
    final File zipFile = File.createTempFile("data", ".zip", toDir);

    // was there an exception?
    boolean exceptionThrown = false;

    try (ZipOutputStream zout = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(zipFile), BUFFER_SIZE))) {

        byte[] data = new byte[BUFFER_SIZE];

        for (File file : files) {
            // create the entry
            zout.putNextEntry(new ZipEntry(file.getName()));

            FileInputStream in = new FileInputStream(file);

            try (FileLock lock = in.getChannel().tryLock(0, Long.MAX_VALUE, true)) {
                isInValid(lock, in);
                int len;

                // write the file to the entry
                while ((len = in.read(data)) > 0) {
                    zout.write(data, 0, len);
                }
                lock.release();
            } finally {
                try {
                    in.close();
                } catch (IOException e) {
                    LOG.error("cannot properly close the opened file " + file.getAbsolutePath(), e);
                }
            }

        }
    } catch (IOException e) {
        LOG.error("error while creating the ZIP file " + zipFile.getAbsolutePath(), e);
        // mark for the finally block
        exceptionThrown = true;
        // rethrow - the finally block is only for the first exception
        throw e;
    } finally {
        // remove the file in case of an exception
        if (exceptionThrown && !zipFile.delete()) {
            LOG.error("cannot delete the file " + zipFile.getAbsolutePath());
        }
    }

    return zipFile;
}

From source file:com.joliciel.talismane.machineLearning.linearsvm.LinearSVMOneVsRestModel.java

@Override
public void writeModelToStream(OutputStream outputStream) {
    try {//from w ww. ja  va 2s  .co m
        ZipOutputStream zos = new ZipOutputStream(outputStream);
        zos.setLevel(ZipOutputStream.STORED);
        int i = 0;
        for (Model model : models) {
            LOG.debug("Writing model " + i + " for outcome " + outcomes.get(i));
            ZipEntry zipEntry = new ZipEntry("model" + i);
            i++;
            zos.putNextEntry(zipEntry);
            Writer writer = new OutputStreamWriter(zos, "UTF-8");
            Writer unclosableWriter = new UnclosableWriter(writer);
            model.save(unclosableWriter);
            zos.closeEntry();
            zos.flush();
        }
    } catch (UnsupportedEncodingException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:com.amalto.core.storage.hibernate.TypeMapping.java

private static Object _serializeValue(Object value, FieldMetadata sourceField, FieldMetadata targetField,
        Session session) {/*from  w w w.j  a  va2s . c  o m*/
    if (targetField == null) {
        return value;
    }
    if (!targetField.isMany()) {
        Boolean targetZipped = targetField.<Boolean>getData(MetadataRepository.DATA_ZIPPED);
        Boolean sourceZipped = sourceField.<Boolean>getData(MetadataRepository.DATA_ZIPPED);
        if (sourceZipped == null && Boolean.TRUE.equals(targetZipped)) {
            try {
                ByteArrayOutputStream characters = new ByteArrayOutputStream();
                OutputStream bos = new Base64OutputStream(characters);
                ZipOutputStream zos = new ZipOutputStream(bos);
                ZipEntry zipEntry = new ZipEntry("content"); //$NON-NLS-1$
                zos.putNextEntry(zipEntry);
                zos.write(String.valueOf(value).getBytes("UTF-8")); //$NON-NLS-1$
                zos.closeEntry();
                zos.flush();
                zos.close();
                return new String(characters.toByteArray());
            } catch (IOException e) {
                throw new RuntimeException("Unexpected compression exception", e); //$NON-NLS-1$
            }
        }
        String targetSQLType = targetField.getType().getData(TypeMapping.SQL_TYPE);
        if (targetSQLType != null && SQL_TYPE_CLOB.equals(targetSQLType)) {
            if (value != null) {
                return Hibernate.getLobCreator(session).createClob(String.valueOf(value));
            } else {
                return null;
            }
        }
    }
    return value;
}

From source file:org.fenixedu.start.controller.StartController.java

private ResponseEntity<byte[]> build(Map<String, byte[]> project, ProjectRequest request) throws IOException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ZipOutputStream zip = new ZipOutputStream(stream);

    for (Map.Entry<String, byte[]> mapEntry : project.entrySet()) {
        ZipEntry entry = new ZipEntry(request.getArtifactId() + "/" + mapEntry.getKey());
        zip.putNextEntry(entry);/*from   ww  w.j  a v  a  2 s  .co  m*/
        zip.write(mapEntry.getValue());
        zip.closeEntry();
    }

    zip.close();

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/zip");
    headers.add("Content-Disposition", "attachment; filename=\"" + request.getArtifactId() + ".zip\"");
    return new ResponseEntity<>(stream.toByteArray(), headers, HttpStatus.OK);
}

From source file:com.sqli.liferay.imex.util.xml.ZipUtils.java

public void zipFiles(File archive, File inputDir) throws IOException {

    FileOutputStream dest = new FileOutputStream(archive);
    CheckedOutputStream checksum = new CheckedOutputStream(dest, new Adler32());
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(checksum));

    zipEntries(out, inputDir, inputDir);

    out.close();// w  ww. ja v  a2 s .com
    log.debug("checksum:" + checksum.getChecksum().getValue());

}

From source file:io.druid.java.util.common.CompressionUtils.java

/**
 * Zips the contents of the input directory to the output stream. Sub directories are skipped
 *
 * @param directory The directory whose contents should be added to the zip in the output stream.
 * @param out       The output stream to write the zip data to. Caller is responsible for closing this stream.
 *
 * @return The number of bytes (uncompressed) read from the input directory.
 *
 * @throws IOException/*from  w  ww .  j ava 2s.  c  om*/
 */
public static long zip(File directory, OutputStream out) throws IOException {
    if (!directory.isDirectory()) {
        throw new IOE("directory[%s] is not a directory", directory);
    }

    final ZipOutputStream zipOut = new ZipOutputStream(out);

    long totalSize = 0;
    for (File file : directory.listFiles()) {
        log.info("Adding file[%s] with size[%,d].  Total size so far[%,d]", file, file.length(), totalSize);
        if (file.length() >= Integer.MAX_VALUE) {
            zipOut.finish();
            throw new IOE("file[%s] too large [%,d]", file, file.length());
        }
        zipOut.putNextEntry(new ZipEntry(file.getName()));
        totalSize += Files.asByteSource(file).copyTo(zipOut);
    }
    zipOut.closeEntry();
    // Workaround for http://hg.openjdk.java.net/jdk8/jdk8/jdk/rev/759aa847dcaf
    zipOut.flush();
    zipOut.finish();

    return totalSize;
}

From source file:fr.simon.marquis.secretcodes.util.ExportContentProvider.java

private void saveZipFile() {
    File[] files = getContext().getFilesDir().listFiles();
    String zipPath = getContext().getFilesDir().getAbsolutePath() + "/" + ZIP_FILE_NAME;
    try {/*  w w w . j a  v a 2  s  .  com*/
        BufferedInputStream origin = null;
        FileOutputStream zipFile = new FileOutputStream(zipPath);

        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(zipFile));

        byte data[] = new byte[BUFFER];
        for (int i = 0; i < files.length; i++) {
            FileInputStream fi = new FileInputStream(files[i]);
            origin = new BufferedInputStream(fi, BUFFER);
            ZipEntry entry = new ZipEntry(
                    files[i].getAbsolutePath().substring(files[i].getAbsolutePath().lastIndexOf("/") + 1));
            out.putNextEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();
        }

        out.close();
        Log.d(this.getClass().getSimpleName(),
                "zipFile created at " + zipPath + " with " + files.length + " files");
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(this.getClass().getSimpleName(),
                "error while zipping at " + zipPath + " with " + files.length + " files", e);
    }

}