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:com.marklogic.contentpump.OutputArchive.java

private void newOutputStream() throws IOException {
    // use the constructor filename for the first zip,
    // then add filecount to subsequent archives, if any.
    int count = fileCount.getAndIncrement();
    currPath = newPackagePath(basePath, count, 6);
    if (outputStream != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("closing output archive: " + currPath);
        }/*from   w w  w  .  j  a va 2 s. c  o  m*/
        outputStream.flush();
        outputStream.close();
    }
    currentFileBytes = 0;
    currentEntries = 0;

    Path zpath = new Path(currPath);
    FileSystem fs = zpath.getFileSystem(conf);
    if (fs.exists(zpath)) {
        throw new IOException(zpath + " already exists.");
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating output archive: " + zpath);
        LOG.debug("Default charset: " + Charset.defaultCharset());
    }
    // if fs instanceof DistributedFileSystem, use hadoop api; otherwise,
    // use java api
    if (fs instanceof DistributedFileSystem) {
        FSDataOutputStream fsout = fs.create(zpath, false);
        outputStream = new ZipOutputStream(fsout);
    } else {
        File f = new File(zpath.toUri().getPath());
        if (!f.exists()) {
            f.getParentFile().mkdirs();
            f.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(f, false);
        outputStream = new ZipOutputStream(fos);
    }

}

From source file:ZipTransformTest.java

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

    File file1 = File.createTempFile("temp", null);
    File file2 = File.createTempFile("temp", null);
    try {/* w  ww . j  ava  2s  . com*/
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file1));
        try {
            zos.putNextEntry(new ZipEntry(name));
            zos.write(contents);
            zos.closeEntry();
        } finally {
            IOUtils.closeQuietly(zos);
        }

        // Transform the ZIP file
        ZipUtil.transformEntry(file1, name, new StreamZipEntryTransformer() {
            protected void transform(ZipEntry zipEntry, InputStream in, OutputStream out) throws IOException {
                IOUtils.copy(in, out);
            }
        }, file2);

        // Test the ZipUtil
        byte[] actual = ZipUtil.unpackEntry(file2, name);
        assertNotNull(actual);
        assertEquals(new String(contents), new String(actual));
    } finally {
        FileUtils.deleteQuietly(file1);
        FileUtils.deleteQuietly(file2);
    }
}

From source file:ZipHandler.java

/**
 * makes a zip file named <xmlFileName> from <xmlURL> at path <zipURL>
 * @param zipURL/*  w w w.j a v  a  2s  .c o  m*/
 * @param xmlURL
 * @param xmlFileName
 */

public static void makeStructZip(String zipURL, String xmlURL, String xmlFileName) throws IOException {
    FileOutputStream fos = new FileOutputStream(new File(zipURL));
    ZipOutputStream zos = new ZipOutputStream(fos);
    //         zos.setLevel();
    FileInputStream fis = new FileInputStream(xmlURL);
    zos.putNextEntry(new ZipEntry(xmlFileName + ".xml"));
    writeInOutputStream(fis, zos);
    zos.closeEntry();
    fis.close();
    zos.close();
}

From source file:S3DataManager.java

public UploadToS3Output uploadSourceToS3(Run<?, ?> build, Launcher launcher, TaskListener listener)
        throws Exception {
    Validation.checkS3SourceUploaderConfig(projectName, workspace);

    String localfileName = this.projectName + "-" + "source.zip";
    String sourceFilePath = workspace.getRemote();
    String zipFilePath = sourceFilePath.substring(0, sourceFilePath.lastIndexOf(File.separator))
            + File.separator + localfileName;
    File zipFile = new File(zipFilePath);

    if (!zipFile.getParentFile().exists()) {
        boolean dirMade = zipFile.getParentFile().mkdirs();
        if (!dirMade) {
            throw new Exception("Unable to create directory: " + zipFile.getParentFile().getAbsolutePath());
        }/*from ww w .j a va2  s .com*/
    }

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilePath));
    try {
        zipSource(sourceFilePath, out, sourceFilePath);
    } finally {
        out.close();
    }

    File sourceZipFile = new File(zipFilePath);
    PutObjectRequest putObjectRequest = new PutObjectRequest(s3InputBucket, s3InputKey, sourceZipFile);

    // Add MD5 checksum as S3 Object metadata
    String zipFileMD5;
    try (FileInputStream fis = new FileInputStream(zipFilePath)) {
        zipFileMD5 = new String(org.apache.commons.codec.binary.Base64.encodeBase64(DigestUtils.md5(fis)),
                "UTF-8");
    }
    ObjectMetadata objectMetadata = new ObjectMetadata();
    objectMetadata.setContentMD5(zipFileMD5);
    objectMetadata.setContentLength(sourceZipFile.length());
    putObjectRequest.setMetadata(objectMetadata);

    LoggingHelper.log(listener, "Uploading code to S3 at location " + putObjectRequest.getBucketName() + "/"
            + putObjectRequest.getKey() + ". MD5 checksum is " + zipFileMD5);
    PutObjectResult putObjectResult = s3Client.putObject(putObjectRequest);

    return new UploadToS3Output(putObjectRequest.getBucketName() + "/" + putObjectRequest.getKey(),
            putObjectResult.getVersionId());
}

From source file:org.openmrs.module.omodexport.util.OmodExportUtil.java

/**
 * Utility module for exporting all modules. The exported modules will be in a zip file called
 * "modules.zip"//  ww  w  . jav  a 2 s  . c  om
 * 
 * @param response
 * @throws IOException
 */
public static void exportAllModules(HttpServletResponse response) throws IOException {

    Collection<Module> modules = ModuleFactory.getStartedModules();
    List<File> files = new ArrayList<File>();
    for (Module module : modules) {
        files.add(module.getFile());
    }
    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=\"modules.ZIP\"");

    ZipOutputStream out = new ZipOutputStream(response.getOutputStream());

    zipFiles(files, out);
}

From source file:com.mycollab.vaadin.resources.StreamDownloadResourceSupportExtDrive.java

@Override
public InputStream getStream() {
    if (resources.size() == 1) {
        Resource res = resources.iterator().next();
        if (!(res instanceof Folder)) {
            if (res.isExternalResource()) {
                ExternalResourceService service = ResourceUtils
                        .getExternalResourceService(ResourceUtils.getType(res));
                return service.download(ResourceUtils.getExternalDrive(res), res.getPath());
            } else {
                return resourceService.getContentStream(res.getPath());
            }/* w  w w  .  ja  v a 2s . c  om*/
        }
    }

    final PipedInputStream inStream = new PipedInputStream();
    final PipedOutputStream outStream;

    try {
        outStream = new PipedOutputStream(inStream);
    } catch (IOException ex) {
        LOG.error("Can not create outstream file", ex);
        return null;
    }

    Thread threadExport = new MyCollabThread(new Runnable() {
        @Override
        public void run() {
            try {
                ZipOutputStream zipOutStream = new ZipOutputStream(outStream);
                zipResource(zipOutStream, resources);
                zipOutStream.close();
                outStream.close();
            } catch (Exception e) {
                LOG.error("Error while saving content stream", e);
            }
        }
    });

    threadExport.start();
    return inStream;
}

From source file:com.eviware.soapui.integration.exporter.ProjectExporter.java

/**
 * Compress temporary directory and save it on given path.
 * //from  www  . j  a  v a  2s .  com
 * @param exportPath
 * @return
 * @throws IOException
 */
private boolean packageAll(String exportPath) {
    if (!exportPath.endsWith(".zip"))
        exportPath = exportPath + ".zip";

    BufferedInputStream origin = null;
    ZipOutputStream out;
    boolean result = true;
    try {
        FileOutputStream dest = new FileOutputStream(exportPath);
        out = new ZipOutputStream(new BufferedOutputStream(dest));
        byte data[] = new byte[BUFFER];
        // get a list of files from current directory

        String files[] = tmpDir.list();

        for (int i = 0; i < files.length; i++) {
            //            System.out.println( "Adding: " + files[i] );
            FileInputStream fi = new FileInputStream(new File(tmpDir, files[i]));
            origin = new BufferedInputStream(fi, BUFFER);
            ZipEntry entry = new ZipEntry(files[i]);
            out.putNextEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();
        }
        out.close();
    } catch (IOException e) {
        // TODO: handle exception
        result = false;
    }
    return result;
}

From source file:msearch.io.MSFilmlisteSchreiben.java

public void filmlisteSchreibenJson(String datei, ListeFilme listeFilme) {
    MSLog.systemMeldung("Filme Schreiben (" + listeFilme.size() + " Filme) :");
    File file = new File(datei);
    File dir = new File(file.getParent());
    if (!dir.exists()) {
        if (!dir.mkdirs()) {
            MSLog.fehlerMeldung(915236478, MSLog.FEHLER_ART_PROG,
                    "MSearchIoXmlFilmlisteSchreiben.xmlSchreibenStart",
                    "Kann den Pfad nicht anlegen: " + dir.toString());
        }/*from w  w w .  j a v a2s .co  m*/
    }
    MSLog.systemMeldung("   --> Start Schreiben nach: " + datei);
    try {
        String sender = "", thema = "";
        JsonFactory jsonF = new JsonFactory();
        JsonGenerator jg;
        if (datei.endsWith(MSConst.FORMAT_XZ)) {
            LZMA2Options options = new LZMA2Options();
            XZOutputStream out = new XZOutputStream(new FileOutputStream(file), options);
            jg = jsonF.createGenerator(out);
        } else if (datei.endsWith(MSConst.FORMAT_BZ2)) {
            bZip2CompressorOutputStream = new BZip2CompressorOutputStream(new FileOutputStream(file),
                    9 /*Blocksize: 1 - 9*/);
            jg = jsonF.createGenerator(bZip2CompressorOutputStream, JsonEncoding.UTF8);
        } else if (datei.endsWith(MSConst.FORMAT_ZIP)) {
            zipOutputStream = new ZipOutputStream(new FileOutputStream(file));
            ZipEntry entry = new ZipEntry(MSConst.XML_DATEI_FILME);
            zipOutputStream.putNextEntry(entry);
            jg = jsonF.createGenerator(zipOutputStream, JsonEncoding.UTF8);
        } else {
            jg = jsonF.createGenerator(new File(datei), JsonEncoding.UTF8);
        }
        jg.useDefaultPrettyPrinter(); // enable indentation just to make debug/testing easier
        jg.writeStartObject();
        // Infos zur Filmliste
        jg.writeArrayFieldStart(ListeFilme.FILMLISTE);
        for (int i = 0; i < ListeFilme.MAX_ELEM; ++i) {
            jg.writeString(listeFilme.metaDaten[i]);
        }
        jg.writeEndArray();
        // Infos der Felder in der Filmliste
        jg.writeArrayFieldStart(ListeFilme.FILMLISTE);
        for (int i = 0; i < DatenFilm.COLUMN_NAMES_JSON.length; ++i) {
            jg.writeString(DatenFilm.COLUMN_NAMES[DatenFilm.COLUMN_NAMES_JSON[i]]);
        }
        jg.writeEndArray();
        //Filme schreiben
        ListIterator<DatenFilm> iterator;
        DatenFilm datenFilm;
        iterator = listeFilme.listIterator();
        while (iterator.hasNext()) {
            datenFilm = iterator.next();
            jg.writeArrayFieldStart(DatenFilm.FILME_);
            for (int i = 0; i < DatenFilm.COLUMN_NAMES_JSON.length; ++i) {
                int m = DatenFilm.COLUMN_NAMES_JSON[i];
                if (m == DatenFilm.FILM_SENDER_NR) {
                    if (datenFilm.arr[m].equals(sender)) {
                        jg.writeString("");
                    } else {
                        sender = datenFilm.arr[m];
                        jg.writeString(datenFilm.arr[m]);
                    }
                } else if (m == DatenFilm.FILM_THEMA_NR) {
                    if (datenFilm.arr[m].equals(thema)) {
                        jg.writeString("");
                    } else {
                        thema = datenFilm.arr[m];
                        jg.writeString(datenFilm.arr[m]);
                    }
                } else {
                    jg.writeString(datenFilm.arr[m]);
                }
            }
            jg.writeEndArray();
        }
        jg.writeEndObject();
        jg.close();
        MSLog.systemMeldung("   --> geschrieben!");
    } catch (Exception ex) {
        MSLog.fehlerMeldung(846930145, MSLog.FEHLER_ART_PROG, "IoXmlSchreiben.FilmeSchreiben", ex,
                "nach: " + datei);
    }
}

From source file:com.centurylink.mdw.common.service.JsonExport.java

/**
 * Default behavior adds zip entries for each property on the first (non-mdw) top-level object.
 *///ww  w  .ja  v a  2s  . c o  m
public String exportZipBase64() throws JSONException, IOException {
    Map<String, JSONObject> objectMap = JsonUtil.getJsonObjects(jsonable.getJson());
    JSONObject mdw = null;
    JSONObject contents = null;
    for (String name : objectMap.keySet()) {
        if ("mdw".equals(name))
            mdw = objectMap.get(name);
        else if (contents == null)
            contents = objectMap.get(name);
    }
    if (contents == null)
        throw new IOException("Cannot find expected contents property");
    else
        objectMap = JsonUtil.getJsonObjects(contents);
    if (mdw != null)
        objectMap.put(".mdw", mdw);

    byte[] buffer = new byte[ZIP_BUFFER_KB * 1024];
    ZipOutputStream zos = null;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        zos = new ZipOutputStream(outputStream);
        for (String name : objectMap.keySet()) {
            JSONObject json = objectMap.get(name);
            ZipEntry ze = new ZipEntry(name);
            zos.putNextEntry(ze);
            InputStream inputStream = new ByteArrayInputStream(json.toString(2).getBytes());
            int len;
            while ((len = inputStream.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
        }
    } finally {
        if (zos != null) {
            zos.closeEntry();
            zos.close();
        }
    }
    byte[] bytes = outputStream.toByteArray();
    return new String(Base64.encodeBase64(bytes));
}

From source file:msearch.filmlisten.MSFilmlisteSchreiben.java

public void filmlisteSchreibenJson(String datei, ListeFilme listeFilme) {
    MSLog.systemMeldung("Filme schreiben (" + listeFilme.size() + " Filme) :");
    File file = new File(datei);
    File dir = new File(file.getParent());
    if (!dir.exists()) {
        if (!dir.mkdirs()) {
            MSLog.fehlerMeldung(915236478, MSLog.FEHLER_ART_PROG,
                    "MSearchIoXmlFilmlisteSchreiben.xmlSchreibenStart",
                    "Kann den Pfad nicht anlegen: " + dir.toString());
        }//  ww w. j a  v a  2  s  .co  m
    }
    MSLog.systemMeldung("   --> Start Schreiben nach: " + datei);
    try {
        String sender = "", thema = "";
        JsonFactory jsonF = new JsonFactory();
        JsonGenerator jg;
        if (datei.endsWith(MSConst.FORMAT_XZ)) {
            LZMA2Options options = new LZMA2Options();
            XZOutputStream out = new XZOutputStream(new FileOutputStream(file), options);
            jg = jsonF.createGenerator(out);
        } else if (datei.endsWith(MSConst.FORMAT_BZ2)) {
            bZip2CompressorOutputStream = new BZip2CompressorOutputStream(new FileOutputStream(file),
                    9 /*Blocksize: 1 - 9*/);
            jg = jsonF.createGenerator(bZip2CompressorOutputStream, JsonEncoding.UTF8);
        } else if (datei.endsWith(MSConst.FORMAT_ZIP)) {
            zipOutputStream = new ZipOutputStream(new FileOutputStream(file));
            ZipEntry entry = new ZipEntry(MSConst.XML_DATEI_FILME);
            zipOutputStream.putNextEntry(entry);
            jg = jsonF.createGenerator(zipOutputStream, JsonEncoding.UTF8);
        } else {
            jg = jsonF.createGenerator(new File(datei), JsonEncoding.UTF8);
        }
        jg.useDefaultPrettyPrinter(); // enable indentation just to make debug/testing easier
        jg.writeStartObject();
        // Infos zur Filmliste
        jg.writeArrayFieldStart(ListeFilme.FILMLISTE);
        for (int i = 0; i < ListeFilme.MAX_ELEM; ++i) {
            jg.writeString(listeFilme.metaDaten[i]);
        }
        jg.writeEndArray();
        // Infos der Felder in der Filmliste
        jg.writeArrayFieldStart(ListeFilme.FILMLISTE);
        for (int i = 0; i < DatenFilm.COLUMN_NAMES_JSON.length; ++i) {
            jg.writeString(DatenFilm.COLUMN_NAMES[DatenFilm.COLUMN_NAMES_JSON[i]]);
        }
        jg.writeEndArray();
        //Filme schreiben
        ListIterator<DatenFilm> iterator;
        DatenFilm datenFilm;
        iterator = listeFilme.listIterator();
        while (iterator.hasNext()) {
            datenFilm = iterator.next();
            jg.writeArrayFieldStart(DatenFilm.FILME_);
            for (int i = 0; i < DatenFilm.COLUMN_NAMES_JSON.length; ++i) {
                int m = DatenFilm.COLUMN_NAMES_JSON[i];
                if (m == DatenFilm.FILM_SENDER_NR) {
                    if (datenFilm.arr[m].equals(sender)) {
                        jg.writeString("");
                    } else {
                        sender = datenFilm.arr[m];
                        jg.writeString(datenFilm.arr[m]);
                    }
                } else if (m == DatenFilm.FILM_THEMA_NR) {
                    if (datenFilm.arr[m].equals(thema)) {
                        jg.writeString("");
                    } else {
                        thema = datenFilm.arr[m];
                        jg.writeString(datenFilm.arr[m]);
                    }
                } else {
                    jg.writeString(datenFilm.arr[m]);
                }
            }
            jg.writeEndArray();
        }
        jg.writeEndObject();
        jg.close();
        MSLog.systemMeldung("   --> geschrieben!");
    } catch (Exception ex) {
        MSLog.fehlerMeldung(846930145, MSLog.FEHLER_ART_PROG, "IoXmlSchreiben.FilmeSchreiben", ex,
                "nach: " + datei);
    }
}