Example usage for java.util.zip ZipOutputStream flush

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

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the compressed output stream.

Usage

From source file:hd3gtv.embddb.network.DataBlock.java

byte[] getBytes(Protocol protocol) throws IOException {
    checkIfNotEmpty();//  ww w  . j a v  a2 s  .co  m

    ByteArrayOutputStream byte_array_out_stream = new ByteArrayOutputStream(Protocol.BUFFER_SIZE);

    DataOutputStream dos = new DataOutputStream(byte_array_out_stream);
    dos.write(Protocol.APP_SOCKET_HEADER_TAG);
    dos.writeInt(Protocol.VERSION);

    /**
     * Start header name
     */
    dos.writeByte(0);
    byte[] request_name_data = request_name.getBytes(Protocol.UTF8);
    dos.writeInt(request_name_data.length);
    dos.write(request_name_data);

    /**
     * Start datas payload
     */
    dos.writeByte(1);

    /**
     * Get datas from zip
     */
    ZipOutputStream zos = new ZipOutputStream(dos);
    zos.setLevel(3);
    entries.forEach(entry -> {
        try {
            entry.toZip(zos);
        } catch (IOException e) {
            log.error("Can't add to zip", e);
        }
    });
    zos.flush();
    zos.finish();
    zos.close();

    dos.flush();
    dos.close();

    byte[] result = byte_array_out_stream.toByteArray();

    if (log.isTraceEnabled()) {
        log.trace("Make raw datas for " + request_name + Hexview.LINESEPARATOR + Hexview.tracelog(result));
    }

    return result;
}

From source file:org.wso2.carbon.registry.resource.services.utils.ContentUtil.java

private static void zipDir(String dirToZip, ZipOutputStream zos)
        throws org.wso2.carbon.registry.api.RegistryException {
    try {/*ww  w . j  av  a 2  s. c  o  m*/

        File zipDir = new File(dirToZip);
        String[] dirList = zipDir.list();
        byte[] readBuffer = new byte[1024];
        int bytesIn = 0;
        for (int i = 0; i < dirList.length; i++) {
            File f = new File(zipDir, dirList[i]);
            if (f.isDirectory()) {
                zipDir(f.getPath(), zos);
                continue;
            } else {
                FileInputStream fis = new FileInputStream(f.getPath());
                ZipEntry anEntry = new ZipEntry(
                        f.getPath().contains("dependencies") ? "dependencies" + File.separator + f.getName()
                                : f.getName());
                zos.putNextEntry(anEntry);
                while ((bytesIn = fis.read(readBuffer)) != -1) {
                    zos.write(readBuffer, 0, bytesIn);
                }
                zos.flush();
                fis.close();
            }
        }

    } catch (Exception e) {
        throw new org.wso2.carbon.registry.api.RegistryException("Error occurred while zipping the file");
    }
}

From source file:org.geoserver.rest.catalog.DataStoreFileUploadTest.java

@Test
public void testPropertyFileUploadZipped() throws Exception {
    byte[] bytes = propertyFile();

    //compress//from  w w  w  .  j  av a  2  s.c  om
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ZipOutputStream zout = new ZipOutputStream(out);
    zout.putNextEntry(new ZipEntry("pds.properties"));
    zout.write(bytes);
    zout.flush();
    zout.close();

    put(ROOT_PATH + "/workspaces/gs/datastores/pds/file.properties", out.toByteArray(), "application/zip");

    Document dom = getAsDOM("wfs?request=getfeature&typename=gs:pds");
    assertFeatures(dom);

}

From source file:au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils.java

/** Compress the files in the backup folder for a project.
 * @param projectId The project ID/*from   ww  w.j  a  v a2s . com*/
 * @throws IOException Any exception when reading/writing data.
 */
public static void compressBackupFolder(final String projectId) throws IOException {
    String backupPath = getBackupPath(projectId);
    if (!Files.isDirectory(Paths.get(backupPath))) {
        // No such directory, so nothing to do.
        return;
    }
    String projectSlug = makeSlug(projectId);
    // The name of the ZIP file that does/will contain all
    // backups for this project.
    Path zipFilePath = Paths.get(backupPath).resolve(projectSlug + ".zip");
    // A temporary ZIP file. Any existing content in the zipFilePath
    // will be copied into this, followed by any other files in
    // the directory that have not yet been added.
    Path tempZipFilePath = Paths.get(backupPath).resolve("temp" + ".zip");

    File tempZipFile = tempZipFilePath.toFile();
    if (!tempZipFile.exists()) {
        tempZipFile.createNewFile();
    }

    ZipOutputStream tempZipOut = new ZipOutputStream(new FileOutputStream(tempZipFile));

    File existingZipFile = zipFilePath.toFile();
    if (existingZipFile.exists()) {
        ZipFile zipIn = new ZipFile(existingZipFile);

        Enumeration<? extends ZipEntry> entries = zipIn.entries();
        while (entries.hasMoreElements()) {
            ZipEntry e = entries.nextElement();
            logger.debug("compressBackupFolder copying: " + e.getName());
            tempZipOut.putNextEntry(e);
            if (!e.isDirectory()) {
                copy(zipIn.getInputStream(e), tempZipOut);
            }
            tempZipOut.closeEntry();
        }
        zipIn.close();
    }

    File dir = new File(backupPath);
    File[] files = dir.listFiles();

    for (File source : files) {
        if (!source.getName().toLowerCase().endsWith(".zip")) {
            logger.debug("compressBackupFolder compressing and " + "deleting file: " + source.toString());
            if (zipFile(tempZipOut, source)) {
                source.delete();
            }
        }
    }

    tempZipOut.flush();
    tempZipOut.close();
    tempZipFile.renameTo(existingZipFile);
}

From source file:com.espringtran.compressor4j.processor.Bzip2Processor.java

/**
 * Compress data//www . j a va  2s.  com
 * 
 * @param fileCompressor
 *            FileCompressor object
 * @return
 * @throws Exception
 */
@Override
public byte[] compressData(FileCompressor fileCompressor) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BZip2CompressorOutputStream cos = new BZip2CompressorOutputStream(baos);
    ZipOutputStream zos = new ZipOutputStream(cos);
    try {
        zos.setLevel(fileCompressor.getLevel().getValue());
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setComment(fileCompressor.getComment());
        for (BinaryFile binaryFile : fileCompressor.getMapBinaryFile().values()) {
            zos.putNextEntry(new ZipEntry(binaryFile.getDesPath()));
            zos.write(binaryFile.getData());
            zos.closeEntry();
        }
        zos.flush();
        zos.finish();
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on compress data", e);
    } finally {
        zos.close();
        cos.close();
        baos.close();
    }
    return baos.toByteArray();
}

From source file:com.espringtran.compressor4j.processor.GzipProcessor.java

/**
 * Compress data/*from w  ww.j a  v  a  2 s.c  o  m*/
 * 
 * @param fileCompressor
 *            FileCompressor object
 * @return
 * @throws Exception
 */
@Override
public byte[] compressData(FileCompressor fileCompressor) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GzipCompressorOutputStream cos = new GzipCompressorOutputStream(baos);
    ZipOutputStream zos = new ZipOutputStream(cos);
    try {
        zos.setLevel(fileCompressor.getLevel().getValue());
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setComment(fileCompressor.getComment());
        for (BinaryFile binaryFile : fileCompressor.getMapBinaryFile().values()) {
            zos.putNextEntry(new ZipEntry(binaryFile.getDesPath()));
            zos.write(binaryFile.getData());
            zos.closeEntry();
        }
        zos.flush();
        zos.finish();
    } catch (Exception e) {
        FileCompressor.LOGGER.error("Error on compress data", e);
    } finally {
        zos.close();
        cos.close();
        baos.close();
    }
    return baos.toByteArray();
}

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

@Override
public final void persist(File modelFile) {
    try {/* w w w  . ja  va2s  .  c o  m*/
        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:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java

protected void attachOutput(ReportExecutionJob job, MimeMessageHelper messageHelper, ReportOutput output,
        boolean useZipFormat) throws MessagingException, JobExecutionException {
    String attachmentName;/*from  w  ww. j  a v  a  2  s  . c  o  m*/
    DataContainer attachmentData;
    if (output.getChildren().isEmpty()) {
        attachmentName = output.getFilename();
        attachmentData = output.getData();
    } else if (useZipFormat) { // use zip format
        attachmentData = job.createDataContainer();
        boolean close = true;
        ZipOutputStream zipOut = new ZipOutputStream(attachmentData.getOutputStream());
        try {
            zipOutput(job, output, zipOut);
            zipOut.finish();
            zipOut.flush();
            close = false;
            zipOut.close();
        } catch (IOException e) {
            throw new JSExceptionWrapper(e);
        } finally {
            if (close) {
                try {
                    zipOut.close();
                } catch (IOException e) {
                    log.error("Error closing stream", e);
                }
            }
        }

        attachmentName = output.getFilename() + ".zip";
    } else { // NO ZIP FORMAT
        attachmentName = output.getFilename();
        try {
            attachmentName = MimeUtility.encodeWord(attachmentName, job.getCharacterEncoding(), null);
        } catch (UnsupportedEncodingException e) {
            throw new JSExceptionWrapper(e);
        }
        StringBuffer primaryPage = null;
        for (Iterator it = output.getChildren().iterator(); it.hasNext();) {
            ReportOutput child = (ReportOutput) it.next();
            String childName = child.getFilename();

            // NOTE:  add the ".dat" extension to all image resources
            // email client will automatically append ".dat" extension to all the files with no extension
            // should do it in JasperReport side
            if (output.getFileType().equals(ContentResource.TYPE_HTML)) {
                if (primaryPage == null)
                    primaryPage = new StringBuffer(new String(output.getData().getData()));
                int fromIndex = 0;
                while ((fromIndex = primaryPage.indexOf("src=\"" + childName + "\"", fromIndex)) > 0) {
                    primaryPage.insert(fromIndex + 5 + childName.length(), ".dat");
                }
                childName = childName + ".dat";
            }

            try {
                childName = MimeUtility.encodeWord(childName, job.getCharacterEncoding(), null);
            } catch (UnsupportedEncodingException e) {
                throw new JSExceptionWrapper(e);
            }
            messageHelper.addAttachment(childName, new DataContainerResource(child.getData()));
        }
        if (primaryPage == null) {
            messageHelper.addAttachment(attachmentName, new DataContainerResource(output.getData()));
        } else {
            messageHelper.addAttachment(attachmentName,
                    new DataContainerResource(new MemoryDataContainer(primaryPage.toString().getBytes())));
        }
        return;
    }
    try {
        attachmentName = MimeUtility.encodeWord(attachmentName, job.getCharacterEncoding(), null);
    } catch (UnsupportedEncodingException e) {
        throw new JSExceptionWrapper(e);
    }
    messageHelper.addAttachment(attachmentName, new DataContainerResource(attachmentData));
}

From source file:de.uzk.hki.da.pkg.ZipArchiveBuilder.java

private void addFileToArchive(String path, File srcFile, ZipOutputStream zip, boolean includeFolder)
        throws Exception {

    if (srcFile.isDirectory()) {
        addFolderToArchive(path, srcFile, zip, includeFolder);
    } else {//from   w  ww .  j av a  2  s  .com
        byte[] buf = new byte[1024];
        int len;
        FileInputStream in = new FileInputStream(srcFile);
        zip.putNextEntry(new ZipEntry(path + "/" + srcFile.getName()));
        while ((len = in.read(buf)) > 0) {
            zip.write(buf, 0, len);
        }
        in.close();
    }

    zip.flush();

}

From source file:com.replaymod.sponge.recording.AbstractRecorder.java

@Override
public void endRecording(OutputStream out, ReplayMetaData metaData) throws IllegalStateException, IOException {
    if (metaData == null) {
        Preconditions.checkState(rawOutputs.remove(out),
                "Specified output is unknown or meta data is missing.");
        out.flush();//from ww w .  j a  va2s . co  m
        out.close();
    } else {
        ZipOutputStream zipOut = outputs.remove(out);
        if (zipOut == null) {
            throw new IllegalStateException("Specified output is unknown or contains raw data.");
        }

        zipOut.closeEntry();

        zipOut.putNextEntry(new ZipEntry("metaData.json"));
        zipOut.write(toJson(metaData).getBytes());
        zipOut.closeEntry();

        zipOut.flush();
        zipOut.close();
    }
}