Example usage for java.util.zip ZipOutputStream putNextEntry

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

Introduction

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

Prototype

public void putNextEntry(ZipEntry e) throws IOException 

Source Link

Document

Begins writing a new ZIP file entry and positions the stream to the start of the entry data.

Usage

From source file:edu.harvard.med.screensaver.service.cherrypicks.CherryPickRequestPlateMapFilesBuilder.java

/**
 * for  [#3206] Generate a distinct plate/copy list for CPR download file
 *//* w w  w  .  jav  a  2 s .c o  m*/
private void buildDistinctPlateCopyFile(CherryPickRequest cherryPickRequest,
        Set<CherryPickAssayPlate> forPlates, ZipOutputStream zipOut) throws IOException {
    PrintWriter out = new CSVPrintWriter(new OutputStreamWriter(zipOut), NEWLINE);
    zipOut.putNextEntry(new ZipEntry(DISTINCT_PLATE_COPY_LIST_FILE_NAME));
    for (String string : DISTINCT_PLATECOPYLIST_FILE_HEADERS) {
        out.print(string);
    }
    out.println();

    // TODO: consider caching this while building the CPR
    Set<Plate> sourcePlates = Sets.newHashSet();

    for (CherryPickAssayPlate plate : forPlates) {
        for (LabCherryPick lcp : plate.getLabCherryPicks()) {
            lcp = genericEntityDao.reloadEntity(lcp, true);
            sourcePlates.add(librariesDao.findPlate(lcp.getSourceWell().getPlateNumber(),
                    lcp.getSourceCopy().getName()));
        }
    }
    // sort by plate/copy/location
    List<Plate> list = Lists.newArrayList(sourcePlates);
    Collections.sort(list, new Comparator<Plate>() {
        @Override
        public int compare(Plate o1, Plate o2) {
            if (o1.equals(o2)) {
                return o1.getLocation().compareTo(o2.getLocation());
            }
            return o1.compareTo(o2); // note Plate.compare() does a plate/copy compare
        }
    });
    for (Plate p : list) {
        out.print(p.getPlateNumber());
        out.print(p.getCopy().getName());
        out.print(p.getLocation() == null ? "" : p.getLocation().toDisplayString());
        out.println();
    }
}

From source file:gov.nih.nci.caarray.application.fileaccess.FileAccessUtils.java

/**
 * Adds the given file to the given zip output stream using the given name as the zip entry name. This method will
 * NOT call finish on the zip output stream at the end.
 * //  w ww  .  jav a2  s  .  co  m
 * @param zos the zip output stream to add the file to. This stream must already be open.
 * @param file the file to put in the zip.
 * @param name the name to use for this zip entry.
 * @param addAsStored if true, then the file will be added to the zip as a STORED entry (e.g. without applying
 *            compression to it); if false, then the file will be added to the zip as a DEFLATED entry.
 * @throws IOException if there is an error writing to the stream
 */
public void writeZipEntry(ZipOutputStream zos, File file, String name, boolean addAsStored) throws IOException {
    final ZipEntry ze = new ZipEntry(name);
    ze.setMethod(addAsStored ? ZipEntry.STORED : ZipEntry.DEFLATED);
    if (addAsStored) {
        ze.setSize(file.length());
        ze.setCrc(FileUtils.checksumCRC32(file));
    }
    zos.putNextEntry(ze);
    final InputStream is = FileUtils.openInputStream(file);
    IOUtils.copy(is, zos);
    zos.closeEntry();
    zos.flush();
    IOUtils.closeQuietly(is);
}

From source file:ServerJniTest.java

@Test
public void testDocumentRoot() throws Exception {
    File dir = null;//from   w  w w  .  j av a2 s  .  c o  m
    long handle = 0;
    try {
        dir = Files.createTempDir();
        // prepare data
        FileUtils.writeStringToFile(new File(dir, "test.txt"), STATIC_FILE_DATA);
        FileUtils.writeStringToFile(new File(dir, "foo.boo"), STATIC_FILE_DATA);
        File zipFile = new File(dir, "test.zip");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zipper = new ZipOutputStream(baos);
        zipper.putNextEntry(new ZipEntry("test/zipped.txt"));
        zipper.write(STATIC_ZIP_DATA.getBytes("UTF-8"));
        zipper.close();
        FileUtils.writeByteArrayToFile(zipFile, baos.toByteArray());
        String sout = wiltoncall("server_create", GSON.toJson(ImmutableMap.builder()
                .put("views", TestGateway.views()).put("tcpPort", TCP_PORT)
                .put("documentRoots",
                        ImmutableList.builder().add(ImmutableMap.builder().put("resource", "/static/files")
                                .put("dirPath", dir.getAbsolutePath())
                                .put("mimeTypes",
                                        ImmutableList.builder()
                                                .add(ImmutableMap.builder().put("extension", "boo")
                                                        .put("mime", "text/x-boo").build())
                                                .build())
                                .build())
                                .add(ImmutableMap.builder().put("resource", "/static")
                                        .put("zipPath", zipFile.getAbsolutePath())
                                        .put("zipInnerPrefix", "test/").build())
                                .build())
                .build()));
        Map<String, Long> shamap = GSON.fromJson(sout, LONG_MAP_TYPE);
        handle = shamap.get("serverHandle");
        assertEquals(HELLO_RESP, httpGet(ROOT_URL + "hello"));
        // deliberated repeated requests
        assertEquals(STATIC_FILE_DATA, httpGet(ROOT_URL + "static/files/test.txt"));
        assertEquals(STATIC_FILE_DATA, httpGet(ROOT_URL + "static/files/test.txt"));
        assertEquals(STATIC_FILE_DATA, httpGet(ROOT_URL + "static/files/test.txt"));
        assertEquals("text/plain", httpGetHeader(ROOT_URL + "static/files/test.txt", "Content-Type"));
        assertEquals(STATIC_FILE_DATA, httpGet(ROOT_URL + "static/files/foo.boo"));
        assertEquals("text/x-boo", httpGetHeader(ROOT_URL + "static/files/foo.boo", "Content-Type"));
        assertEquals(STATIC_ZIP_DATA, httpGet(ROOT_URL + "static/zipped.txt"));
        assertEquals(STATIC_ZIP_DATA, httpGet(ROOT_URL + "static/zipped.txt"));
        assertEquals(STATIC_ZIP_DATA, httpGet(ROOT_URL + "static/zipped.txt"));
    } finally {
        stopServerQuietly(handle);
        deleteDirQuietly(dir);
    }
}

From source file:com.googlecode.dex2jar.v3.Dex2jar.java

private void check(String dir, ZipOutputStream zos) throws IOException {
    if (dirs.contains(dir)) {
        return;//  w  w w  .j  av  a  2s  . c o  m
    }
    dirs.add(dir);
    int i = dir.lastIndexOf('/');
    if (i > 0) {
        check(dir.substring(0, i), zos);
    }
    zos.putNextEntry(new ZipEntry(dir + "/"));
    zos.closeEntry();
}

From source file:edu.harvard.med.screensaver.service.cherrypicks.CherryPickRequestPlateMapFilesBuilder.java

@SuppressWarnings("unchecked")
private void buildReadme(CherryPickRequest cherryPickRequest, ZipOutputStream zipOut) throws IOException {

    ZipEntry zipEntry = new ZipEntry(README_FILE_NAME);
    zipOut.putNextEntry(zipEntry);
    PrintWriter writer = new CustomNewlinePrintWriter(zipOut, NEWLINE);

    writer.println("This zip file contains plate mappings for Cherry Pick Request "
            + cherryPickRequest.getCherryPickRequestNumber());
    writer.println();/*w  w w.ja  va2  s  .  c  o  m*/

    {
        StringBuilder buf = new StringBuilder();
        for (CherryPickAssayPlate assayPlate : cherryPickRequest.getActiveCherryPickAssayPlates()) {
            buf.append(assayPlate.getName()).append("\t").append(assayPlate.getStatusLabel());
            if (assayPlate.isPlatedAndScreened()) {
                buf.append("\t(").append(assayPlate.getCherryPickScreenings().last().getDateOfActivity())
                        .append(" by ").append(assayPlate.getCherryPickScreenings().last().getPerformedBy()
                                .getFullNameFirstLast())
                        .append(')');
            } else if (assayPlate.isPlated()) {
                buf.append("\t(").append(assayPlate.getCherryPickLiquidTransfer().getDateOfActivity())
                        .append(" by ").append(assayPlate.getCherryPickLiquidTransfer().getPerformedBy()
                                .getFullNameFirstLast())
                        .append(')');
            }
            buf.append(NEWLINE);
        }
        if (buf.length() > 0) {
            writer.println("Cherry pick plates:");
            writer.print(buf.toString());
            writer.println();
        }
    }

    Map<CherryPickAssayPlate, Integer> platesRequiringReload = cherryPickRequestPlateMapper
            .getAssayPlatesRequiringSourcePlateReload(cherryPickRequest);
    if (platesRequiringReload.size() > 0) {
        writer.println("WARNING: Some cherry pick plates will be created from the same source plate!");
        writer.println(
                "You will need to reload one or more source plates for each of the following cherry pick plates:");
        for (CherryPickAssayPlate assayPlate : platesRequiringReload.keySet()) {
            writer.println("\tCherry pick plate '" + assayPlate.getName() + "' requires reload of source plate "
                    + platesRequiringReload.get(assayPlate));
        }
        writer.println();
    }

    {
        StringBuilder buf = new StringBuilder();
        MultiMap sourcePlateTypesForEachAssayPlate = getSourcePlateTypesForEachAssayPlate(cherryPickRequest);
        for (CherryPickAssayPlate assayPlate : cherryPickRequest.getActiveCherryPickAssayPlates()) {
            Set<PlateType> sourcePlateTypes = (Set<PlateType>) sourcePlateTypesForEachAssayPlate
                    .get(assayPlate.getName());
            if (sourcePlateTypes != null && sourcePlateTypes.size() > 1) {
                buf.append(assayPlate.getName()).append(NEWLINE);
            }
        }
        if (buf.length() > 0) {
            writer.println(
                    "WARNING: Some cherry pick plates will be created from multiple source plates of non-uniform plate types!");
            writer.println("The following cherry pick plates are specified across multiple files:");
            writer.print(buf.toString());
            writer.println();
        }
    }

    writer.flush();
}

From source file:com.googlecode.dex2jar.v3.Dex2jar.java

private void saveTo(byte[] data, String name, Object dist) throws IOException {
    if (dist instanceof ZipOutputStream) {
        ZipOutputStream zos = (ZipOutputStream) dist;
        ZipEntry entry = new ZipEntry(name + ".class");
        int i = name.lastIndexOf('/');
        if (i > 0) {
            check(name.substring(0, i), zos);
        }//from   ww  w .j av  a2 s.  c o m
        zos.putNextEntry(entry);
        zos.write(data);
        zos.closeEntry();
    } else {
        File dir = (File) dist;
        FileUtils.writeByteArrayToFile(new File(dir, name + ".class"), data);
    }
}

From source file:it.polimi.diceH2020.launcher.utility.FileUtility.java

private void addFileToZip(@NotNull File path, @NotNull File srcFile, @NotNull ZipOutputStream zip)
        throws IOException {
    if (srcFile.isDirectory()) {
        addFolderToZip(path, srcFile, zip);
    } else {//  w w  w .  jav  a2  s . com
        byte[] buf = new byte[1024];
        int len;
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(srcFile))) {
            zip.putNextEntry(makeEntry(path, srcFile));
            while ((len = in.read(buf)) > 0) {
                zip.write(buf, 0, len);
            }
        }
    }
}

From source file:com.xpn.xwiki.export.html.HtmlPackager.java

/**
 * Add a directory and all its sub-directories to the package.
 * /* www.jav a2 s. c  o  m*/
 * @param directory the directory to add.
 * @param out the ZIP output stream where to put the skin.
 * @param basePath the path where to put the directory in the package.
 * @throws IOException error when adding the directory to package.
 */
private static void addDirToZip(File directory, ZipOutputStream out, String basePath,
        Collection<String> exportedSkinFiles) throws IOException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Adding dir [" + directory.getPath() + "] to the Zip file being generated.");
    }

    if (!directory.isDirectory()) {
        return;
    }

    File[] files = directory.listFiles();

    if (files == null) {
        return;
    }

    for (int i = 0; i < files.length; ++i) {
        File file = files[i];
        if (file.isDirectory()) {
            addDirToZip(file, out, basePath + file.getName() + ZIPPATH_SEPARATOR, exportedSkinFiles);
        } else {
            String path = basePath + file.getName();

            if (exportedSkinFiles != null && exportedSkinFiles.contains(path)) {
                continue;
            }

            FileInputStream in = new FileInputStream(file);

            try {
                // Starts a new Zip entry. It automatically closes the previous entry if present.
                out.putNextEntry(new ZipEntry(path));

                try {
                    IOUtils.copy(in, out);
                } finally {
                    out.closeEntry();
                }
            } finally {
                in.close();
            }
        }
    }
}

From source file:be.fedict.eid.dss.document.zip.ZIPSignatureOutputStream.java

@Override
public void close() throws IOException {
    super.close();

    byte[] signatureData = toByteArray();

    /*/* www . j  a  va2s.c o m*/
     * Copy the original ZIP content.
     */
    ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile));
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) {
            ZipEntry newZipEntry = new ZipEntry(zipEntry.getName());
            zipOutputStream.putNextEntry(newZipEntry);
            LOG.debug("copying " + zipEntry.getName());
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }
    zipInputStream.close();

    /*
     * Add the XML signature file to the ZIP package.
     */
    zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE);
    LOG.debug("writing " + zipEntry.getName());
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();
}

From source file:com.taobao.android.builder.tools.zip.ZipUtils.java

public static void addFileAndDirectoryToZip(File output, File srcDir, Map<String, ZipEntry> zipEntryMethodMap)
        throws Exception {
    if (output.isDirectory()) {
        throw new IOException("This is a directory!");
    }/*w ww  . j ava2  s .com*/
    if (!output.getParentFile().exists()) {
        output.getParentFile().mkdirs();
    }

    if (!output.exists()) {
        output.createNewFile();
    }
    List fileList = getSubFiles(srcDir);
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(output));
    ZipEntry ze = null;
    byte[] buf = new byte[1024];
    int readLen = 0;
    for (int i = 0; i < fileList.size(); i++) {
        File f = (File) fileList.get(i);
        ze = new ZipEntry(getAbsFileName(srcDir.getPath(), f));
        ze.setSize(f.length());
        ze.setTime(f.lastModified());
        if (zipEntryMethodMap != null) {
            ZipEntry originEntry = zipEntryMethodMap.get(f.getAbsolutePath());
            if (originEntry != null) {
                ze.setCompressedSize(originEntry.getCompressedSize());
                ze.setCrc(originEntry.getCrc());
                ze.setMethod(originEntry.getMethod());
            }
        }
        zos.putNextEntry(ze);
        InputStream is = new BufferedInputStream(new FileInputStream(f));
        while ((readLen = is.read(buf, 0, 1024)) != -1) {
            zos.write(buf, 0, readLen);
        }
        is.close();
    }
    zos.close();
}