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:com.aurel.track.exchange.track.exporter.TrackExportBL.java

public static ZipOutputStream exportWorkItemsWithAttachments(List<ReportBean> reportBeanList, Integer personID,
        OutputStream outputStream) {

    ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);

    Document document = exportWorkItems(reportBeanList, personID);
    ZipEntry dataEntry = new ZipEntry(ExchangeFieldNames.EXCHANGE_ZIP_ENTRY);
    try {//from w  w  w  . j a  va2s.  co  m
        zipOutputStream.putNextEntry(dataEntry);
    } catch (IOException e) {
        LOGGER.error("Adding the XML data to the zip failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    ReportBeansToXML.convertToXml(zipOutputStream, document);
    //zipOutputStream.closeEntry();
    //get the attachments for each workItem (if exist)
    if (reportBeanList != null) {
        for (ReportBean reportBean : reportBeanList) {
            TWorkItemBean workItemBean = reportBean.getWorkItemBean();
            Integer workItemID = workItemBean.getObjectID();
            String workItemAttachmentsDirectory = AttachBL.getFullDirName(null, workItemID);
            File file = new File(workItemAttachmentsDirectory);
            if (file.exists() && file.isDirectory()) {
                ReportBL.zipFiles(file, zipOutputStream, file.getAbsolutePath());
            }
        }
    }
    try {
        zipOutputStream.close();
    } catch (IOException e) {
        LOGGER.warn("Closing the zip failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    return zipOutputStream;
}

From source file:hudson.FilePathTest.java

private InputStream someZippedContent() throws IOException {
    final ByteArrayOutputStream buf = new ByteArrayOutputStream();
    final ZipOutputStream zip = new ZipOutputStream(buf);

    zip.putNextEntry(new ZipEntry("abc"));
    zip.write("abc".getBytes());
    zip.close();/*from www  .  j a v a2  s  .  co  m*/

    return new ByteArrayInputStream(buf.toByteArray());
}

From source file:it.cnr.icar.eric.common.Utility.java

public static ZipOutputStream createZipOutputStream(String baseDir, String[] relativeFilePaths, OutputStream os)
        throws FileNotFoundException, IOException {
    if (baseDir.startsWith("file:/")) {
        baseDir = baseDir.substring(5);//  www  . j a v a  2  s. c om
    }
    ZipOutputStream zipoutputstream = new ZipOutputStream(os);

    zipoutputstream.setMethod(ZipOutputStream.STORED);

    for (int i = 0; i < relativeFilePaths.length; i++) {
        File file = new File(baseDir + FILE_SEPARATOR + relativeFilePaths[i]);

        byte[] buffer = new byte[1000];

        int n;

        FileInputStream fis;

        // Calculate the CRC-32 value.  This isn't strictly necessary
        //   for deflated entries, but it doesn't hurt.

        CRC32 crc32 = new CRC32();

        fis = new FileInputStream(file);

        while ((n = fis.read(buffer)) > -1) {
            crc32.update(buffer, 0, n);
        }

        fis.close();

        // Create a zip entry.

        ZipEntry zipEntry = new ZipEntry(relativeFilePaths[i]);

        zipEntry.setSize(file.length());
        zipEntry.setTime(file.lastModified());
        zipEntry.setCrc(crc32.getValue());

        // Add the zip entry and associated data.

        zipoutputstream.putNextEntry(zipEntry);

        fis = new FileInputStream(file);

        while ((n = fis.read(buffer)) > -1) {
            zipoutputstream.write(buffer, 0, n);
        }

        fis.close();

        zipoutputstream.closeEntry();
    }

    return zipoutputstream;
}

From source file:net.gbmb.collector.example.SimpleLogPush.java

private String storeArchive(Collection collection) throws IOException {
    String cid = collection.getId();
    java.util.Collection<CollectionRecord> records = collectionRecords.get(cid);

    // index//from   w  ww  .  j a  v  a2 s .com
    ByteArrayOutputStream indexStream = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
    PrintStream output = new PrintStream(indexStream);
    // zip
    ByteArrayOutputStream archiveStream = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
    ZipOutputStream zos = new ZipOutputStream(archiveStream);
    output.println("Serialize collection: " + collection.getId());
    output.println("  creation date: " + collection.getCreationDate());
    output.println("  end date:      " + collection.getEndDate());
    for (CollectionRecord cr : records) {
        output.print(cr.getRecordDate());
        output.print(" ");
        output.println(cr.getContent());
        if (cr.getAttachment() != null) {
            String attName = cr.getAttachment();
            output.println("  > " + attName);
            ZipEntry entry = new ZipEntry(cr.getAttachment());
            zos.putNextEntry(entry);
            InputStream content = temporaryStorage.get(cid, attName);
            IOUtils.copy(content, zos);
        }
    }
    // add the index file
    output.close();
    ZipEntry index = new ZipEntry("index");
    zos.putNextEntry(index);
    IOUtils.write(indexStream.toByteArray(), zos);
    // close zip
    zos.close();
    ByteArrayInputStream content = new ByteArrayInputStream(archiveStream.toByteArray());

    // send to final storage
    return finalStorage.store(cid, content);
}

From source file:mergedoc.core.MergeManager.java

/**
 * ????Java ???//from   w  w w.  ja v a  2  s  .c  om
 * API ???????????? ZIP
 * ??????
 *
 * @param  in  
 * @param  out ZIP 
 * @throws MergeDocException ??????
 * @throws SAXException SAX ????
 * @throws IOException ????
 */
private void merge(ArchiveInputStream in, ZipOutputStream out)
        throws MergeDocException, SAXException, IOException {
    Merger merger = new Merger(pref.getDocDirectory());
    merger.setDocEncoding(pref.getDocEncoding());

    ArchiveInputStream.Entry inEntry = null;
    while ((inEntry = in.getNextEntry()) != null) {

        if (workingState.isCanceled()) {
            return;
        }
        String entryName = inEntry.getName();
        out.putNextEntry(new ZipEntry(entryName));
        workingState.changeWorkingText(entryName);

        //debug ?
        //if (!entryName.equals("java/lang/String.java")) continue;
        //if (!entryName.endsWith("/SuppressWarnings.java")) continue;
        //if (!entryName.endsWith("/System.java")) continue;

        if (entryName.endsWith(".java") && !entryName.endsWith("/package-info.java")) {

            // Java ??
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            copyStream(in, baos);
            String source = baos.toString(pref.getInputEncoding());
            source = FastStringUtils.optimizeLineSeparator(source);
            source = FastStringUtils.untabify(source);

            // Java  API ?
            Pattern classPat = PatternCache.getPattern(".*/(.*)\\.java");
            Matcher classMat = classPat.matcher(entryName);
            if (classMat.find()) {
                String result = merger.merge(source, classMat.group(1));
                String className = merger.getMergedClassName();
                if (className != null) {
                    result = doFilter(className, result);
                }
                byte[] resultBuf = result.getBytes(pref.getOutputEncoding());
                out.write(resultBuf);
            } else {
                copyStream(in, out);
            }
        } else {
            // Java ??
            copyStream(in, out);
        }
    }
}

From source file:de.thorstenberger.examServer.webapp.action.PDFBulkExport.java

/**
 * @param tasklet/*from w  w w . jav a  2s  . co  m*/
 * @param userId
 * @param zos
 * @return
 * @throws IOException
 */
private boolean addGeneratedPDFS(final Tasklet tasklet, final String userId, final ZipOutputStream zos)
        throws IOException {
    final ExamServerManager esm = (ExamServerManager) getBean("examServerManager");
    boolean wroteAtLeastOneFile = false;
    // find all existing pdfs for this user and this taskId
    for (final File pdfFile : new File(esm.getHomeDir(), userId).listFiles(getPdfFileFilter(tasklet, userId))) {
        log.info(String.format("adding existing pdf '%s'", pdfFile.getName()));

        wroteAtLeastOneFile = true;
        // add pdf to zip
        final ZipEntry ze = new ZipEntry(pdfFile.getName());
        zos.putNextEntry(ze);
        final InputStream is = new FileInputStream(pdfFile);
        IOUtils.copy(is, zos);
        is.close();
    }
    return wroteAtLeastOneFile;
}

From source file:ml.shifu.shifu.util.IndependentTreeModelUtils.java

public boolean convertBinaryToZipSpec(File treeModelFile, File outputZipFile) {
    FileInputStream treeModelInputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {//from  w  w w. j a v a2s . c  o  m
        treeModelInputStream = new FileInputStream(treeModelFile);
        IndependentTreeModel treeModel = IndependentTreeModel.loadFromStream(treeModelInputStream);
        List<List<TreeNode>> trees = treeModel.getTrees();
        treeModel.setTrees(null);
        if (CollectionUtils.isEmpty(trees)) {
            logger.error("No trees found in the tree model.");
            return false;
        }

        zipOutputStream = new ZipOutputStream(new FileOutputStream(outputZipFile));

        ZipEntry modelEntry = new ZipEntry(MODEL_CONF);
        zipOutputStream.putNextEntry(modelEntry);
        ByteArrayOutputStream byos = new ByteArrayOutputStream();
        JSONUtils.writeValue(new OutputStreamWriter(byos), treeModel);
        zipOutputStream.write(byos.toByteArray());
        IOUtils.closeQuietly(byos);

        ZipEntry treesEntry = new ZipEntry(MODEL_TREES);
        zipOutputStream.putNextEntry(treesEntry);
        DataOutputStream dataOutputStream = new DataOutputStream(zipOutputStream);
        dataOutputStream.writeInt(trees.size());
        for (List<TreeNode> forest : trees) {
            dataOutputStream.writeInt(forest.size());
            for (TreeNode treeNode : forest) {
                treeNode.write(dataOutputStream);
            }
        }
        IOUtils.closeQuietly(dataOutputStream);
    } catch (IOException e) {
        logger.error("Error occurred when convert the tree model to zip format.", e);
        return false;
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
        IOUtils.closeQuietly(treeModelInputStream);
    }

    return true;
}

From source file:ZipImploder.java

/**
 * process a single file for a .zip file
 * //from  w w  w  . ja v  a 2s  .  c o  m
 * @param zos
 * @param f
 * @throws IOException
 */
public void processFile(ZipOutputStream zos, File f) throws IOException {
    String path = f.getCanonicalPath();
    path = path.replace('\\', '/');
    String xpath = removeDrive(removeLead(path));
    ZipEntry ze = new ZipEntry(xpath);
    ze.setTime(f.lastModified());
    ze.setSize(f.length());
    zos.putNextEntry(ze);
    fileCount++;
    try {
        copyFileEntry(zos, f);
    } finally {
        zos.closeEntry();
    }
}

From source file:edu.dfci.cccb.mev.dataset.rest.controllers.WorkspaceController.java

private void zipAnnotations(String name, String dimension, ZipOutputStream zout)
        throws DatasetNotFoundException, IOException {
    Dataset dataset = workspace.get(name);
    long projectId = projectManager.getProjectID(dataset.name() + dimension);
    if (projectId > -1) {
        File annotations = new TemporaryFile();
        GZIPOutputStream gos = new GZIPOutputStream(new FileOutputStream(annotations));
        TarOutputStream tos = new TarOutputStream(gos);
        projectManager.exportProject(projectId, tos);
        tos.flush();//from  www  . j ava 2  s  . c  o m
        tos.close();
        zout.putNextEntry(new ZipEntry(String.format("annotations_%s.tar.gz", dimension)));
        IOUtils.copy(new FileInputStream(annotations), zout);
        zout.closeEntry();
    }
}