Example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry ZipArchiveEntry

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry ZipArchiveEntry

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry ZipArchiveEntry.

Prototype

public ZipArchiveEntry(ZipArchiveEntry entry) throws ZipException 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

From source file:big.BigZip.java

/**
 * Copies one file into the big archive//from www.j  a  v  a 2 s .  c om
 * @param fileToCopy
 * @param SHA1
 * @param filePathToWriteInTextLine
 * @return 
 */
public boolean quickWrite(final File fileToCopy, final String SHA1, final String filePathToWriteInTextLine) {
    // declare
    ByteArrayOutputStream outputZipStream = new ByteArrayOutputStream();
    try {
        // save this operation on the log of commits
        addTagStarted(fileToCopy.getName());
        //pointRestoreAndSave(fileToCopy);

        /* Create Archive Output Stream that attaches File Output Stream / and specifies type of compression */
        ArchiveOutputStream logical_zip = new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputZipStream);
        /* Create Archieve entry - write header information*/
        logical_zip.putArchiveEntry(new ZipArchiveEntry(fileToCopy.getName()));
        /* Copy input file */
        IOUtils.copy(new FileInputStream(fileToCopy), logical_zip);
        logical_zip.closeArchiveEntry();
        logical_zip.finish();
        logical_zip.flush();
        logical_zip.close();

        // get the bytes
        final ByteArrayInputStream byteInput = new ByteArrayInputStream(outputZipStream.toByteArray());

        byte[] buffer = new byte[8192];
        int length, counter = 0;
        // add the magic number to this file block
        outputStream.write(magicSignature.getBytes());
        // now copy the whole file into the BIG archive
        while ((length = byteInput.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
            counter += length;
        }
        // if there is something else to be flushed, do it now
        //outputStream.flush();

        // calculate the base path
        //final String resultingPath = fileToCopy.getAbsolutePath().replace(rootFolder, "");

        final String line = "\n" + utils.files.getPrettyFileSize(currentPosition) + " " + SHA1 + " "
                + filePathToWriteInTextLine;

        // write a new line in our index file
        writerFileIndex.write(line);
        //writer.flush();
        // increase the position counter
        currentPosition += counter + magicSignature.length();

        // close the log with success
        addTagEnded();
    } catch (Exception e) {
        System.err.println("BIG600 - Error copying file: " + fileToCopy.getAbsolutePath());
        return false;
    } finally {
    }
    return true;
}

From source file:net.duckling.ddl.service.export.impl.ExportServiceImpl.java

private void writeOverview(String tag, String tname, int[] rids, ArchiveOutputStream out, VWBContext context,
        boolean isEpub) {
    String htmlHeader = getTemplate(epubPath + HTML_TEM);
    htmlHeader = htmlHeader.replace("TITLE", "" + tname);
    htmlHeader = htmlHeader.replaceAll("[\\.]{2}", "\\.");

    StringBuilder sb = new StringBuilder();
    if (isEpub) {
        sb.append(EPUB_XML_HEADER);// w ww  .j  a va 2 s  . c om
        sb.append(htmlHeader);
        sb.append("<body><h1></h1><ul>");
        for (int rid : rids) {
            writeOverviewItemByResource(context, rid, sb, tag, tname, true);
        }
    } else {
        sb.append(htmlHeader);
        sb.append("<body><h1></h1><ul>");
        for (int rid : rids) {
            writeOverviewItemByResource(context, rid, sb, tag, tname, false);
        }
    }
    sb.append("</ul></body></html>");
    InputStream in = new ByteArrayInputStream(sb.toString().getBytes());
    try {
        out.putArchiveEntry(new ZipArchiveEntry(tname + "/overview.html"));
        IOUtils.copy(in, out);
        in.close();
        out.closeArchiveEntry();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:net.duckling.ddl.service.export.impl.ExportServiceImpl.java

private void writeOverview(String tname, Map<String, List<Tag>> tagMap, ArchiveOutputStream out,
        VWBContext context, boolean isEpub) {
    String htmlHeader = getTemplate(epubPath + HTML_TEM);
    htmlHeader = htmlHeader.replace("TITLE", "" + tname);
    htmlHeader = htmlHeader.replaceAll("[\\.]{2}", "\\.");

    StringBuilder sb = new StringBuilder();
    if (isEpub) {
        sb.append(EPUB_XML_HEADER);//from  w w  w .  ja  va 2  s  . c o  m
        sb.append(htmlHeader);
        sb.append("<body><h1></h1><ul>");
        writeOverviewItemByTag(context, tagMap, sb, true);
    } else {
        sb.append(htmlHeader);
        sb.append("<body><h1></h1><ul>");
        writeOverviewItemByTag(context, tagMap, sb, false);
    }
    sb.append("</ul></body></html>");
    InputStream in = new ByteArrayInputStream(sb.toString().getBytes());
    try {
        out.putArchiveEntry(new ZipArchiveEntry(tname + "/overview.html"));
        IOUtils.copy(in, out);
        in.close();
        out.closeArchiveEntry();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:com.iorga.webappwatcher.EventLogManager.java

private void writeEventLogToHttpServletResponse(final ArchiveOutputStream outputStream,
        final InputStream inputStream, final File file, final String fileName) throws IOException {
    ArchiveEntry archiveEntry = outputStream.createArchiveEntry(file, fileName);
    if (!file.getName().equals(fileName)) {
        // the original file is not the same as the final file, i.e. an original .gz which is uncompressed on the fly, we can't know the file size
        archiveEntry = new ZipArchiveEntry(fileName);
    }// ww  w. j  a  v a2  s . com
    outputStream.putArchiveEntry(archiveEntry);
    try {
        IOUtils.copy(inputStream, outputStream);
    } catch (final Exception e) {
        log.warn("Problem while copying file " + fileName, e);
    } finally {
        outputStream.closeArchiveEntry();
        inputStream.close();
    }
}

From source file:big.BigZip.java

/**
 * Copies one file into the big archive//from  w  ww.ja va 2  s . com
 * @param stream
 * @param SHA1
 * @param filePathToWriteInTextLine
 * @return 
 * @throws java.io.IOException 
 */
public boolean quickWriteGenericStream(final InputStream stream, final String SHA1,
        final String filePathToWriteInTextLine) throws IOException {
    // declare
    ByteArrayOutputStream outputZipStream = new ByteArrayOutputStream();
    ByteArrayInputStream byteInput = null;
    try {
        // save this operation on the log of commits
        addTagStarted(filePathToWriteInTextLine);
        // Create Archive Output Stream that attaches File Output Stream / and specifies type of compression
        ArchiveOutputStream logical_zip = new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputZipStream);
        // Create Archive entry - write header information
        ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(filePathToWriteInTextLine);
        logical_zip.putArchiveEntry(zipArchiveEntry);
        // Copy input file

        IOUtils.copy(stream, logical_zip);

        logical_zip.closeArchiveEntry();
        logical_zip.finish();
        logical_zip.flush();
        logical_zip.close();

        // get the bytes
        byteInput = new ByteArrayInputStream(outputZipStream.toByteArray());

        byte[] buffer = new byte[8192];
        int length, counter = 0;
        // add the magic number to this file block
        outputStream.write(magicSignature.getBytes());
        // now copy the whole file into the BIG archive
        while ((length = byteInput.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
            counter += length;
        }

        final String line = "\n" + utils.files.getPrettyFileSize(currentPosition) + " " + SHA1 + " "
                + filePathToWriteInTextLine;

        // write a new line in our index file
        writerFileIndex.write(line);
        //writer.flush();
        // increase the position counter
        currentPosition += counter + magicSignature.length();

        // close the log with success
        addTagEnded();
    } catch (Exception e) {
        System.err.println("BIG600 - Error copying file: " + filePathToWriteInTextLine);
        return false;
    } finally {
        if (byteInput != null) {
            byteInput.close();
        }
        stream.close();
        outputZipStream.close();
        outputStream.close();
    }
    return true;
}

From source file:net.duckling.ddl.service.export.impl.ExportServiceImpl.java

private void writeCss(String tname, ArchiveOutputStream out) {
    String css = getTemplate(epubPath + AONE_CSS);
    InputStream in = new ByteArrayInputStream(css.getBytes());
    String entry = tname != null ? tname + "/aone.css" : "aone.css";
    try {/*from  ww w. ja v a2 s .c o  m*/
        out.putArchiveEntry(new ZipArchiveEntry(entry));
        IOUtils.copy(in, out);
        in.close();
        out.closeArchiveEntry();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:big.BigZip.java

/**
 * Requires an InputStream, it will calculate the SHA1 checksum at the same
 * time that it writes data onto the big file. The input stream is expected
 * to be closed outside of this method./*from w  w w  . ja  v  a2s  . c  o  m*/
 * @param stream
 * @param filePathToWriteInTextLine
 * @throws java.io.IOException 
 */
public void quickWriteStreamStandalone(final InputStream stream, final String filePathToWriteInTextLine)
        throws Exception {
    // declare
    ByteArrayOutputStream outputZipStream = new ByteArrayOutputStream();
    ByteArrayInputStream byteInput = null;
    // Create Archive Output Stream that attaches File Output Stream / and specifies type of compression
    ArchiveOutputStream logical_zip = new ArchiveStreamFactory()
            .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputZipStream);
    // Create Archive entry - write header information
    ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(filePathToWriteInTextLine);
    logical_zip.putArchiveEntry(zipArchiveEntry);
    // prepare the SHA1 signature generation
    final MessageDigest hash = MessageDigest.getInstance("SHA1");

    // Copy input file
    byte[] buffer = new byte[16384];
    int length;

    // decompress from the original zip file, compress to our zip format
    // calculate the SHA1 signature on the same loop to save resource
    while ((length = stream.read(buffer)) > 0) {
        logical_zip.write(buffer, 0, length);
        hash.update(buffer, 0, length);
    }

    // compute the file signature
    byte[] digest = hash.digest();
    final String SHA1 = utils.hashing.checksum.convertHash(digest);

    // close the zip related objects
    logical_zip.closeArchiveEntry();
    logical_zip.finish();
    logical_zip.flush();
    logical_zip.close();
    logical_zip = null;

    // define the line that will be written on the index file
    final String line = "\n".concat(utils.files.getPrettyFileSize(currentPosition)).concat(" ").concat(SHA1)
            .concat(" ").concat(filePathToWriteInTextLine);

    // get the bytes
    byteInput = new ByteArrayInputStream(outputZipStream.toByteArray());
    int counter = 0;

    // add the magic number to this file block
    outputStream.write(magicSignature.getBytes());
    // now copy the whole file into the BIG archive
    while ((length = byteInput.read(buffer)) > 0) {
        outputStream.write(buffer, 0, length);
        counter += length;
    }
    // write a new line in our index file
    writerFileIndex.write(line);
    // increase the position counter
    currentPosition += counter + magicSignature.length();
    // close the streams that were created
    byteInput.close();
    outputZipStream.close();
}

From source file:ee.sk.digidoc.SignedDoc.java

/**
 * Writes the SignedDoc to an output file
 * and automatically calculates DataFile sizes
 * and digests//from ww w  . ja  v  a 2  s  .c o  m
 * @param outputFile output file name
 * @param fTempSdoc temporrary file, copy of original for copying items
 * @throws DigiDocException for all errors
 */
public void writeToStream(OutputStream os/*, File fTempSdoc*/) throws DigiDocException {
    DigiDocException ex1 = validateFormatAndVersion();
    if (ex1 != null)
        throw ex1;
    try {
        DigiDocXmlGenFactory genFac = new DigiDocXmlGenFactory(this);
        if (m_format.equals(SignedDoc.FORMAT_BDOC)) {
            ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os);
            zos.setEncoding("UTF-8");
            if (m_logger.isDebugEnabled())
                m_logger.debug("OS: " + ((os != null) ? "OK" : "NULL"));
            // write mimetype
            if (m_logger.isDebugEnabled())
                m_logger.debug("Writing: " + MIMET_FILE_NAME);
            ZipArchiveEntry ze = new ZipArchiveEntry(MIMET_FILE_NAME);
            if (m_comment == null)
                m_comment = DigiDocGenFactory.getUserInfo(m_format, m_version);
            ze.setComment(m_comment);
            ze.setMethod(ZipArchiveEntry.STORED);
            java.util.zip.CRC32 crc = new java.util.zip.CRC32();
            if (m_version.equals(BDOC_VERSION_1_0)) {
                ze.setSize(SignedDoc.MIMET_FILE_CONTENT_10.getBytes().length);
                crc.update(SignedDoc.MIMET_FILE_CONTENT_10.getBytes());
            }
            if (m_version.equals(BDOC_VERSION_1_1)) {
                ze.setSize(SignedDoc.MIMET_FILE_CONTENT_11.getBytes().length);
                crc.update(SignedDoc.MIMET_FILE_CONTENT_11.getBytes());
            }
            if (m_version.equals(BDOC_VERSION_2_1)) {
                ze.setSize(SignedDoc.MIMET_FILE_CONTENT_20.getBytes().length);
                crc.update(SignedDoc.MIMET_FILE_CONTENT_20.getBytes());
            }
            ze.setCrc(crc.getValue());
            zos.putArchiveEntry(ze);
            if (m_version.equals(BDOC_VERSION_1_0)) {
                zos.write(SignedDoc.MIMET_FILE_CONTENT_10.getBytes());
            }
            if (m_version.equals(BDOC_VERSION_1_1)) {
                zos.write(SignedDoc.MIMET_FILE_CONTENT_11.getBytes());
            }
            if (m_version.equals(BDOC_VERSION_2_1)) {
                zos.write(SignedDoc.MIMET_FILE_CONTENT_20.getBytes());
            }
            zos.closeArchiveEntry();
            // write manifest.xml
            if (m_logger.isDebugEnabled())
                m_logger.debug("Writing: " + MANIF_FILE_NAME);
            ze = new ZipArchiveEntry(MANIF_DIR_META_INF);
            ze = new ZipArchiveEntry(MANIF_FILE_NAME);
            ze.setComment(DigiDocGenFactory.getUserInfo(m_format, m_version));
            zos.putArchiveEntry(ze);
            //if(m_logger.isDebugEnabled())
            //   m_logger.debug("Writing manif:\n" + m_manifest.toString());
            zos.write(m_manifest.toXML());
            zos.closeArchiveEntry();
            // write data files
            for (int i = 0; i < countDataFiles(); i++) {
                DataFile df = getDataFile(i);
                if (m_logger.isDebugEnabled())
                    m_logger.debug("Writing DF: " + df.getFileName() + " content: " + df.getContentType()
                            + " df-cache: "
                            + ((df.getDfCacheFile() != null) ? df.getDfCacheFile().getAbsolutePath() : "NONE"));
                InputStream is = null;
                if (df.hasAccessToDataFile())
                    is = df.getBodyAsStream();
                else
                    is = findDataFileAsStream(df.getFileName());
                if (is != null) {
                    File dfFile = new File(df.getFileName());
                    String fileName = dfFile.getName();
                    ze = new ZipArchiveEntry(fileName);
                    if (df.getComment() == null)
                        df.setComment(DigiDocGenFactory.getUserInfo(m_format, m_version));
                    ze.setComment(df.getComment());
                    ze.setSize(dfFile.length());
                    ze.setTime(
                            (df.getLastModDt() != null) ? df.getLastModDt().getTime() : dfFile.lastModified());
                    zos.putArchiveEntry(ze);
                    byte[] data = new byte[2048];
                    int nRead = 0, nTotal = 0;
                    crc = new java.util.zip.CRC32();
                    while ((nRead = is.read(data)) > 0) {
                        zos.write(data, 0, nRead);
                        nTotal += nRead;
                        crc.update(data, 0, nRead);
                    }
                    ze.setSize(nTotal);
                    ze.setCrc(crc.getValue());
                    zos.closeArchiveEntry();
                    is.close();
                }
            }
            for (int i = 0; i < countSignatures(); i++) {
                Signature sig = getSignature(i);
                String sFileName = sig.getPath();
                if (sFileName == null) {
                    if (m_version.equals(BDOC_VERSION_2_1))
                        sFileName = SIG_FILE_NAME_20 + (i + 1) + ".xml";
                    else
                        sFileName = SIG_FILE_NAME + (i + 1) + ".xml";
                }
                if (!sFileName.startsWith("META-INF"))
                    sFileName = "META-INF/" + sFileName;
                if (m_logger.isDebugEnabled())
                    m_logger.debug("Writing SIG: " + sFileName + " orig: "
                            + ((sig.getOrigContent() != null) ? "OK" : "NULL"));
                ze = new ZipArchiveEntry(sFileName);
                if (sig.getComment() == null)
                    sig.setComment(DigiDocGenFactory.getUserInfo(m_format, m_version));
                ze.setComment(sig.getComment());
                String sSig = null;
                if (sig.getOrigContent() != null)
                    sSig = new String(sig.getOrigContent(), "UTF-8");
                else
                    sSig = sig.toString();
                if (sSig != null && !sSig.startsWith("<?xml"))
                    sSig = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + sSig;
                byte[] sdata = sSig.getBytes("UTF-8");
                if (m_logger.isDebugEnabled())
                    m_logger.debug("Writing SIG: " + sFileName + " xml:\n---\n "
                            + ((sSig != null) ? sSig : "NULL") + "\n---\n ");
                ze.setSize(sdata.length);
                crc = new java.util.zip.CRC32();
                crc.update(sdata);
                ze.setCrc(crc.getValue());
                zos.putArchiveEntry(ze);
                zos.write(sdata);
                zos.closeArchiveEntry();
            }
            zos.close();
        } else if (m_format.equals(SignedDoc.FORMAT_DIGIDOC_XML)) { // ddoc format
            os.write(xmlHeader().getBytes());
            for (int i = 0; i < countDataFiles(); i++) {
                DataFile df = getDataFile(i);
                df.writeToFile(os);
                os.write("\n".getBytes());
            }
            for (int i = 0; i < countSignatures(); i++) {
                Signature sig = getSignature(i);
                if (sig.getOrigContent() != null)
                    os.write(sig.getOrigContent());
                else
                    os.write(genFac.signatureToXML(sig));
                os.write("\n".getBytes());
            }
            os.write(xmlTrailer().getBytes());
        }
    } catch (DigiDocException ex) {
        throw ex; // allready handled
    } catch (Exception ex) {
        DigiDocException.handleException(ex, DigiDocException.ERR_WRITE_FILE);
    }
}

From source file:eionet.cr.util.odp.ODPDatasetsPacker.java

/**
 *
 * @param zipOutput/*from  w  w  w.  j a  va 2 s  .  com*/
 * @throws XMLStreamException
 * @throws IOException
 */
private void createAndWriteManifestEntry(ZipArchiveOutputStream zipOutput)
        throws XMLStreamException, IOException {

    ZipArchiveEntry entry = new ZipArchiveEntry("manifest.xml");
    zipOutput.putArchiveEntry(entry);

    // Prepare STAX indenting writer based on a Java XMLStreamWriter that is based on the given zipped output.
    XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(zipOutput, ENCODING);
    IndentingXMLStreamWriter writer = new IndentingXMLStreamWriter(xmlWriter);

    int i = 1;
    writeManifestHeader(writer);
    for (SubjectDTO indicatorSubject : indicatorSubjects) {
        writeOdpAction(writer, indicatorSubject, i++);
    }
    writeManifestFooter(writer);

    zipOutput.closeArchiveEntry();
}

From source file:net.duckling.ddl.service.export.impl.ExportServiceImpl.java

private void writePage(String path, int resourceId, VWBContext context, ArchiveOutputStream out,
        Map<String, String> id2Title, List<String> allPages, boolean isEpub) {
    Resource page = resourceService.getResource(resourceId);
    StringBuilder sbuf = new StringBuilder();
    String pagePath = path + "/" + resourceId + ".html";
    if (null != page) {
        String resKey = "" + page.getRid() + "_" + page.getTid() + "_" + LynxConstants.TYPE_PAGE;
        if (null != getResTagPath(resKey)) { // ??
            return;
        }/*from  ww w  . jav  a  2s  .co  m*/
        downResPath.put(resKey, pagePath);
        String html = renderingService.getHTML(context, page);
        // site.getHTML(context, page);
        sbuf.append(getHtmlHeader(page, isEpub));
        sbuf.append("<h1 class=\"title\">" + page.getTitle() + "</h1>");
        sbuf.append(getProcessedHtml(html, context, path, out, id2Title, allPages, isEpub));// ?????
        sbuf.append(getHtmlFooter());
    } else {
        sbuf.append(getPageNotFoundHtml(resourceId, isEpub));
    }
    InputStream in = new ByteArrayInputStream(sbuf.toString().getBytes());
    try {
        out.putArchiveEntry(new ZipArchiveEntry(pagePath));
        IOUtils.copy(in, out);
        in.close();
        out.closeArchiveEntry();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
    String tagname = path.substring(path.indexOf('/') + 1);
    String title = (null == page) ? FAKE_PAGE_TITLE : page.getTitle();
    id2Title.put(tagname + "/" + resourceId + ".html", title);
    if (allPages != null) {
        allPages.add(tagname + "/" + resourceId + ".html");
    }
}