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:au.org.ala.biocache.service.DownloadService.java

/**
 * Writes the supplied download to the supplied output stream. It will include all the appropriate citations etc.
 * //ww  w.  j a  v  a  2  s .c  om
 * @param dd
 * @param requestParams
 * @param ip
 * @param out
 * @param includeSensitive
 * @param fromIndex
 * @throws Exception
 */
private void writeQueryToStream(DownloadDetailsDTO dd, DownloadRequestParams requestParams, String ip,
        OutputStream out, boolean includeSensitive, boolean fromIndex, boolean limit) throws Exception {

    String filename = requestParams.getFile();
    String originalParams = requestParams.toString();
    //Use a zip output stream to include the data and citation together in the download
    ZipOutputStream zop = new ZipOutputStream(out);
    String suffix = requestParams.getFileType().equals("shp") ? "zip" : requestParams.getFileType();
    zop.putNextEntry(new java.util.zip.ZipEntry(filename + "." + suffix));
    //put the facets
    if ("all".equals(requestParams.getQa())) {
        requestParams.setFacets(new String[] { "assertions", "data_resource_uid" });
    } else {
        requestParams.setFacets(new String[] { "data_resource_uid" });
    }
    Map<String, Integer> uidStats = null;
    try {
        if (fromIndex)
            uidStats = searchDAO.writeResultsFromIndexToStream(requestParams, zop, includeSensitive, dd, limit);
        else
            uidStats = searchDAO.writeResultsToStream(requestParams, zop, 100, includeSensitive, dd);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        unregisterDownload(dd);
    }
    zop.closeEntry();

    //add the Readme for the data field descriptions
    zop.putNextEntry(new java.util.zip.ZipEntry("README.html"));
    zop.write(("For more information about the fields that are being downloaded please consult <a href='"
            + dataFieldDescriptionURL + "'>Download Fields</a>.").getBytes());

    //add the readme for the Shape file header mappings if necessary
    if (dd.getHeaderMap() != null) {
        zop.putNextEntry(new java.util.zip.ZipEntry("Shape-README.html"));
        zop.write(
                ("The name of features is limited to 10 characters. Listed below are the mappings of feature name to download field:")
                        .getBytes());
        zop.write(("<table><td><b>Feature</b></td><td><b>Download Field<b></td>").getBytes());
        for (String key : dd.getHeaderMap().keySet()) {
            zop.write(("<tr><td>" + key + "</td><td>" + dd.getHeaderMap().get(key) + "</td></tr>").getBytes());
        }
        zop.write(("</table>").getBytes());
        //logger.debug("JSON::: " + objectMapper.writeValueAsString(dd));
    }

    //Add the data citation to the download
    if (uidStats != null && !uidStats.isEmpty() && citationsEnabled) {
        //add the citations for the supplied uids
        zop.putNextEntry(new java.util.zip.ZipEntry("citation.csv"));
        try {
            getCitations(uidStats, zop, requestParams.getSep(), requestParams.getEsc());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        zop.closeEntry();
    } else {
        logger.debug("Not adding citation. Enabled: " + citationsEnabled + " uids: " + uidStats);
    }
    zop.flush();
    zop.close();

    //now construct the sourceUrl for the log event
    String sourceUrl = originalParams.contains("qid:") ? webservicesRoot + "?" + requestParams.toString()
            : webservicesRoot + "?" + originalParams;

    //logger.debug("UID stats : " + uidStats);
    //log the stats to ala logger        
    LogEventVO vo = new LogEventVO(1002, requestParams.getReasonTypeId(), requestParams.getSourceTypeId(),
            requestParams.getEmail(), requestParams.getReason(), ip, null, uidStats, sourceUrl);
    logger.log(RestLevel.REMOTE, vo);
}

From source file:br.univali.celine.lms.utils.zip.Zip.java

public void zip(ArrayList<String> fileList, File destFile, int compressionLevel) throws Exception {

    if (destFile.exists())
        throw new Exception("File " + destFile.getName() + " already exists!!");

    int fileLength;
    byte[] buffer = new byte[4096];

    FileOutputStream fos = new FileOutputStream(destFile);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    ZipOutputStream zipFile = new ZipOutputStream(bos);
    zipFile.setLevel(compressionLevel);/*  w w w. ja va2  s .com*/

    for (int i = 0; i < fileList.size(); i++) {

        FileInputStream fis = new FileInputStream(fileList.get(i));
        BufferedInputStream bis = new BufferedInputStream(fis);
        ZipEntry ze = new ZipEntry(FilenameUtils.getName(fileList.get(i)));
        zipFile.putNextEntry(ze);

        while ((fileLength = bis.read(buffer, 0, 4096)) > 0)
            zipFile.write(buffer, 0, fileLength);

        zipFile.closeEntry();
        bis.close();
    }

    zipFile.close();

}

From source file:hudson.plugins.doclinks.artifacts.testtools.TestZipBuilder.java

private void compress(ZipOutputStream zos, File dir, String relative) throws IOException {
    for (String filename : dir.list()) {
        File file = new File(dir, filename);
        String path = StringUtils.isEmpty(relative) ? filename : String.format("%s/%s", relative, filename);
        if (file.isDirectory()) {
            if (!noEntryForDirectories) {
                ZipEntry entry = new ZipEntry(String.format("%s/", path));
                zos.putNextEntry(entry);
            }/*  ww w.  j  av a 2  s .co m*/
            compress(zos, file, path);
        } else {
            ZipEntry entry = new ZipEntry(path);
            zos.putNextEntry(entry);
            FileInputStream is = null;
            try {
                is = new FileInputStream(file);
                IOUtils.copy(is, zos);
            } finally {
                if (is != null) {
                    is.close();
                }
            }
        }
    }
}

From source file:com.aionemu.commons.log4j.appenders.TruncateToZipFileAppender.java

/**
 * This method creates archive with file instead of deleting it.
 *
 * @param file file to truncate/*from  w  ww .  ja  va 2s .  co  m*/
 */
protected void truncate(File file) {
    LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started.");

    // Linux systems doesn't provide file creation time, so we have to hope
    // that log files
    // were not modified manually after server starup
    // We can use here Windowns-only solution but that suck :(
    if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) {
        File backupRoot = new File(getBackupDir());
        if (!backupRoot.exists() && !backupRoot.mkdirs()) {
            throw new AppenderInitializationError("Can't create backup dir for backup storage");
        }

        SimpleDateFormat df;
        try {
            df = new SimpleDateFormat(getBackupDateFormat());
        } catch (Exception e) {
            throw new AppenderInitializationError(
                    "Invalid date formate for backup files: " + getBackupDateFormat(), e);
        }
        String date = df.format(new Date(file.lastModified()));

        File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");

        ZipOutputStream zos = null;
        FileInputStream fis = null;
        try {
            zos = new ZipOutputStream(new FileOutputStream(zipFile));
            ZipEntry entry = new ZipEntry(file.getName());
            entry.setMethod(ZipEntry.DEFLATED);
            entry.setCrc(FileUtils.checksumCRC32(file));
            zos.putNextEntry(entry);
            fis = FileUtils.openInputStream(file);

            byte[] buffer = new byte[1024];
            int readed;
            while ((readed = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, readed);
            }

        } catch (Exception e) {
            throw new AppenderInitializationError("Can't create zip file", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    // not critical error
                    LogLog.warn("Can't close zip file", e);
                }
            }

            if (fis != null) {
                try {
                    // not critical error
                    fis.close();
                } catch (IOException e) {
                    LogLog.warn("Can't close zipped file", e);
                }
            }
        }

        if (!file.delete()) {
            throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath());
        }
    }
}

From source file:com.l2jserver.service.core.logging.TruncateToZipFileAppender.java

/**
 * This method creates archive with file instead of deleting it.
 * //from   ww  w  .ja v a  2 s.c o  m
 * @param file
 *            file to truncate
 */
protected void truncate(File file) {
    LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started.");

    // Linux systems doesn't provide file creation time, so we have to hope
    // that log files
    // were not modified manually after server starup
    // We can use here Windowns-only solution but that suck :(
    if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) {
        File backupRoot = new File(getBackupDir());
        if (!backupRoot.exists() && !backupRoot.mkdirs()) {
            throw new Error("Can't create backup dir for backup storage");
        }

        SimpleDateFormat df;
        try {
            df = new SimpleDateFormat(getBackupDateFormat());
        } catch (Exception e) {
            throw new Error("Invalid date formate for backup files: " + getBackupDateFormat(), e);
        }
        String date = df.format(new Date(file.lastModified()));

        File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");

        ZipOutputStream zos = null;
        FileInputStream fis = null;
        try {
            zos = new ZipOutputStream(new FileOutputStream(zipFile));
            ZipEntry entry = new ZipEntry(file.getName());
            entry.setMethod(ZipEntry.DEFLATED);
            entry.setCrc(FileUtils.checksumCRC32(file));
            zos.putNextEntry(entry);
            fis = FileUtils.openInputStream(file);

            byte[] buffer = new byte[1024];
            int readed;
            while ((readed = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, readed);
            }

        } catch (Exception e) {
            throw new Error("Can't create zip file", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    // not critical error
                    LogLog.warn("Can't close zip file", e);
                }
            }

            if (fis != null) {
                try {
                    // not critical error
                    fis.close();
                } catch (IOException e) {
                    LogLog.warn("Can't close zipped file", e);
                }
            }
        }

        if (!file.delete()) {
            throw new Error("Can't delete old log file " + file.getAbsolutePath());
        }
    }
}

From source file:be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java

private void outputSignedOfficeOpenXMLDocument(byte[] signatureData)
        throws IOException, ParserConfigurationException, SAXException, TransformerException {
    LOG.debug("output signed Office OpenXML document");
    OutputStream signedOOXMLOutputStream = getSignedOfficeOpenXMLDocumentOutputStream();
    if (null == signedOOXMLOutputStream) {
        throw new NullPointerException("signedOOXMLOutputStream is null");
    }//w w w . j  a  v a 2s  . c o m

    String signatureZipEntryName = "_xmlsignatures/sig-" + UUID.randomUUID().toString() + ".xml";
    LOG.debug("signature ZIP entry name: " + signatureZipEntryName);
    /*
     * Copy the original OOXML content to the signed OOXML package. During
     * copying some files need to changed.
     */
    ZipOutputStream zipOutputStream = copyOOXMLContent(signatureZipEntryName, signedOOXMLOutputStream);

    /*
     * Add the OOXML XML signature file to the OOXML package.
     */
    ZipEntry zipEntry = new ZipEntry(signatureZipEntryName);
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();
}

From source file:de.jwi.zip.Zipper.java

public void zip(ZipOutputStream out, File f, File base) throws IOException {
    String name = f.getPath().replace('\\', '/');

    if (base != null) {
        String basename = base.getPath().replace('\\', '/');

        if (name.startsWith(basename)) {
            name = name.substring(basename.length());
        }//from  w  w w .j  a va2 s. c om
    }

    if (name.startsWith("/")) {
        name = name.substring(1);
    }

    ZipEntry entry = new ZipEntry(name);
    entry.setTime(f.lastModified());

    out.putNextEntry(entry);

    FileInputStream is = new FileInputStream(f);

    byte[] buf = new byte[BUFSIZE];

    try {
        int l;
        while ((l = is.read(buf)) > -1) {
            out.write(buf, 0, l);
        }
    } finally {
        is.close();
    }
    out.closeEntry();

}

From source file:com.music.service.PieceService.java

public void downloadPieces(OutputStream out, Collection<Piece> pieces) throws IOException {
    ZipOutputStream zip = new ZipOutputStream(out);
    for (Piece piece : pieces) {
        ZipEntry entry = new ZipEntry(piece.getTitle() + "-" + piece.getId() + ".mp3");
        zip.putNextEntry(entry);
        zip.write(IOUtils.toByteArray(getPieceFile(piece.getId())));
        zip.closeEntry();/*from w  w w. ja v a 2 s .c  o  m*/

        entry = new ZipEntry(piece.getTitle() + "-" + piece.getId() + ".midi");
        zip.putNextEntry(entry);
        zip.write(IOUtils.toByteArray(getPieceMidiFile(piece.getId())));
        zip.closeEntry();
    }

    ZipEntry license = new ZipEntry("license.txt");
    zip.putNextEntry(license);
    zip.write(IOUtils.toByteArray(getClass().getResourceAsStream("/emailTemplates/license.txt")));
    zip.closeEntry();
    zip.finish();
}

From source file:org.apache.uima.ruta.resource.TreeWordList.java

private void writeCompressedTWLFile(TextNode root, String path, String encoding) throws IOException {
    FileOutputStream fos = new FileOutputStream(path);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    ZipOutputStream zos = new ZipOutputStream(bos);
    OutputStreamWriter writer = new OutputStreamWriter(zos, encoding);
    zos.putNextEntry(new ZipEntry(path));
    writeTWLFile(root, writer);/*  w w w  .ja  v a2 s .  c om*/
    writer.flush();
    zos.closeEntry();
    writer.close();
}

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

@Override
public void writeModelToStream(OutputStream outputStream) {
    try {//from   ww w  .  j a v  a  2  s  .  com
        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);
    }
}