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:net.duckling.ddl.service.export.impl.ExportServiceImpl.java

private void writeAllPagesFile(String tname, Map<String, String> id2Title, ArchiveOutputStream out) {
    String htmlHeader = getTemplate(epubPath + HTML_TEM);
    htmlHeader = htmlHeader.replace("TITLE", "?");
    htmlHeader = htmlHeader.replace("../aone.css", "./aone.css");
    StringBuilder sb = new StringBuilder();
    sb.append(htmlHeader);//from w w  w  .j  a  va 2 s  . c om
    sb.append("<body><h1>?</h1><ul>");
    for (Entry<String, String> entry : id2Title.entrySet()) {
        sb.append("<li><a target=\"pageFrame\" href=\"").append(entry.getKey()).append("\">")
                .append(entry.getValue()).append("</a></li>");
    }
    sb.append("</ul></body>");
    InputStream in = new ByteArrayInputStream(sb.toString().getBytes());
    try {
        out.putArchiveEntry(new ZipArchiveEntry(tname + "/allPages.html"));
        IOUtils.copy(in, out);
        in.close();
        out.closeArchiveEntry();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:com.excelsiorjet.maven.plugin.JetMojo.java

private static void compressDirectoryToZipfile(String rootDir, String sourceDir, ZipArchiveOutputStream out)
        throws IOException {
    File[] files = new File(sourceDir).listFiles();
    assert files != null;
    for (File file : files) {
        if (file.isDirectory()) {
            compressDirectoryToZipfile(rootDir, sourceDir + File.separator + file.getName(), out);
        } else {/*from w ww.j  a v  a  2  s.  c  o m*/
            ZipArchiveEntry entry = new ZipArchiveEntry(file.getAbsolutePath().substring(rootDir.length() + 1));
            if (Utils.isUnix() && file.canExecute()) {
                entry.setUnixMode(0100777);
            }
            out.putArchiveEntry(entry);
            InputStream in = new BufferedInputStream(
                    new FileInputStream(sourceDir + File.separator + file.getName()));
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            out.closeArchiveEntry();
        }
    }
}

From source file:com.atolcd.web.scripts.ZipContents.java

public void addToZip(NodeRef node, ZipArchiveOutputStream out, boolean noaccent, String path)
        throws IOException {
    QName nodeQnameType = this.nodeService.getType(node);

    // Special case : links
    if (this.dictionaryService.isSubClass(nodeQnameType, ApplicationModel.TYPE_FILELINK)) {
        NodeRef linkDestinationNode = (NodeRef) nodeService.getProperty(node,
                ContentModel.PROP_LINK_DESTINATION);
        if (linkDestinationNode == null) {
            return;
        }//from  ww  w  .jav  a  2 s .  co m

        // Duplicate entry: check if link is not in the same space of the link destination
        if (nodeService.getPrimaryParent(node).getParentRef()
                .equals(nodeService.getPrimaryParent(linkDestinationNode).getParentRef())) {
            return;
        }

        nodeQnameType = this.nodeService.getType(linkDestinationNode);
        node = linkDestinationNode;
    }

    String nodeName = (String) nodeService.getProperty(node, ContentModel.PROP_NAME);
    nodeName = noaccent ? unAccent(nodeName) : nodeName;

    if (this.dictionaryService.isSubClass(nodeQnameType, ContentModel.TYPE_CONTENT)) {
        ContentReader reader = contentService.getReader(node, ContentModel.PROP_CONTENT);
        if (reader != null) {
            InputStream is = reader.getContentInputStream();

            String filename = path.isEmpty() ? nodeName : path + '/' + nodeName;

            ZipArchiveEntry entry = new ZipArchiveEntry(filename);
            entry.setTime(((Date) nodeService.getProperty(node, ContentModel.PROP_MODIFIED)).getTime());

            entry.setSize(reader.getSize());
            out.putArchiveEntry(entry);

            byte buffer[] = new byte[BUFFER_SIZE];
            while (true) {
                int nRead = is.read(buffer, 0, buffer.length);
                if (nRead <= 0) {
                    break;
                }

                out.write(buffer, 0, nRead);
            }
            is.close();
            out.closeArchiveEntry();
        } else {
            logger.warn("Could not read : " + nodeName + "content");
        }
    } else if (this.dictionaryService.isSubClass(nodeQnameType, ContentModel.TYPE_FOLDER)
            && !this.dictionaryService.isSubClass(nodeQnameType, ContentModel.TYPE_SYSTEM_FOLDER)) {
        List<ChildAssociationRef> children = nodeService.getChildAssocs(node);
        if (children.isEmpty()) {
            String folderPath = path.isEmpty() ? nodeName + '/' : path + '/' + nodeName + '/';
            out.putArchiveEntry(new ZipArchiveEntry(new ZipEntry(folderPath)));
        } else {
            for (ChildAssociationRef childAssoc : children) {
                NodeRef childNodeRef = childAssoc.getChildRef();

                addToZip(childNodeRef, out, noaccent, path.isEmpty() ? nodeName : path + '/' + nodeName);
            }
        }
    } else {
        logger.info("Unmanaged type: " + nodeQnameType.getPrefixedQName(this.namespaceService) + ", filename: "
                + nodeName);
    }
}

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

private void writeOverviewSummary(String tname, ArchiveOutputStream out) {
    String htmlHeader = getTemplate(epubPath + HTML_TEM);
    htmlHeader = htmlHeader.replace("TITLE", tname + " overview");
    StringBuilder sb = new StringBuilder();
    sb.append(htmlHeader);/*from   w  w  w. j av  a  2s  . co m*/
    sb.append("<body><h1>" + tname + "</h1></body>");
    InputStream in = new ByteArrayInputStream(sb.toString().getBytes());
    try {
        out.putArchiveEntry(new ZipArchiveEntry(tname + "/overviewSummary.html"));
        IOUtils.copy(in, out);
        in.close();
        out.closeArchiveEntry();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:cz.cuni.mff.ufal.AllBitstreamZipArchiveReader.java

@Override
public void generate() throws IOException, SAXException, ProcessingException {

    if (redirect != NO_REDIRECTION) {
        return;/*  w  w w .  j av a2  s .  co m*/
    }

    String name = item.getName() + ".zip";

    try {

        // first write everything to a temp file
        String tempDir = ConfigurationManager.getProperty("upload.temp.dir");
        String fn = tempDir + File.separator + "SWORD." + item.getID() + "." + UUID.randomUUID().toString()
                + ".zip";
        OutputStream outStream = new FileOutputStream(new File(fn));
        ZipArchiveOutputStream zip = new ZipArchiveOutputStream(outStream);
        zip.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        zip.setLevel(Deflater.NO_COMPRESSION);
        ConcurrentMap<String, AtomicInteger> usedFilenames = new ConcurrentHashMap<String, AtomicInteger>();

        Bundle[] originals = item.getBundles("ORIGINAL");
        if (needsZip64) {
            zip.setUseZip64(Zip64Mode.Always);
        }
        for (Bundle original : originals) {
            Bitstream[] bss = original.getBitstreams();
            for (Bitstream bitstream : bss) {
                String filename = bitstream.getName();
                String uniqueName = createUniqueFilename(filename, usedFilenames);
                ZipArchiveEntry ze = new ZipArchiveEntry(uniqueName);
                zip.putArchiveEntry(ze);
                InputStream is = bitstream.retrieve();
                Utils.copy(is, zip);
                zip.closeArchiveEntry();
                is.close();
            }
        }
        zip.close();

        File file = new File(fn);
        zipFileSize = file.length();

        zipInputStream = new TempFileInputStream(file);
    } catch (AuthorizeException e) {
        log.error(e.getMessage(), e);
        throw new ProcessingException("You do not have permissions to access one or more files.");
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new ProcessingException("Could not create ZIP, please download the files one by one. "
                + "The error has been stored and will be solved by our technical team.");
    }

    // Log download statistics
    for (int bitstreamID : bitstreamIDs) {
        DSpaceApi.updateFileDownloadStatistics(userID, bitstreamID);
    }

    response.setDateHeader("Last-Modified", item.getLastModified().getTime());

    // Try and make the download file name formated for each browser.
    try {
        String agent = request.getHeader("USER-AGENT");
        if (agent != null && agent.contains("MSIE")) {
            name = URLEncoder.encode(name, "UTF8");
        } else if (agent != null && agent.contains("Mozilla")) {
            name = MimeUtility.encodeText(name, "UTF8", "B");
        }
    } catch (UnsupportedEncodingException see) {
        name = "item_" + item.getID() + ".zip";
    }
    response.setHeader("Content-Disposition", "attachment;filename=" + name);

    byte[] buffer = new byte[BUFFER_SIZE];
    int length = -1;

    try {
        response.setHeader("Content-Length", String.valueOf(this.zipFileSize));

        while ((length = this.zipInputStream.read(buffer)) > -1) {
            out.write(buffer, 0, length);
        }
        out.flush();
    } finally {
        try {
            if (this.zipInputStream != null) {
                this.zipInputStream.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException ioe) {
            // Closing the stream threw an IOException but do we want this to propagate up to Cocoon?
            // No point since the user has already got the file contents.
            log.warn("Caught IO exception when closing a stream: " + ioe.getMessage());
        }
    }

}

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

/**
 * Creates and writes a ZIP archive entry file for the given indicator.
 *
 * @param zipOutput ZIP output where the entry goes into.
 * @param indSubject The indicator whose for whom the entry is written.
 * @param index 0-based index of the indicator (in the indicator list received from dataabse) that is being written.
 *
 * @throws IOException If any sort of output stream writing error occurs.
 * @throws XMLStreamException Thrown by methods from the {@link XMLStreamWriter} that is used by called methods.
 */// ww  w .jav a  2  s .  c  o m
private void createAndWriteDatasetEntry(ZipArchiveOutputStream zipOutput, SubjectDTO indSubject, int index)
        throws IOException, XMLStreamException {

    String id = indSubject.getObjectValue(Predicates.SKOS_NOTATION);
    if (StringUtils.isEmpty(id)) {
        id = URIUtil.extractURILabel(indSubject.getUri());
    }

    ZipArchiveEntry entry = new ZipArchiveEntry("datasets/" + id + ".rdf");
    zipOutput.putArchiveEntry(entry);
    writeDatasetEntry(zipOutput, indSubject, index);
    zipOutput.closeArchiveEntry();
}

From source file:com.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testNonCanonicalPaths() throws InterruptedException, IOException {
    String names[] = { "foo/./", "foo/./bar/", "foo/./bar/baz.cpp", "foo/./bar/baz.h", };

    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        for (String name : names) {
            zip.putArchiveEntry(new ZipArchiveEntry(name));
            zip.closeArchiveEntry();// w w  w  . j  ava2 s  .  co m
        }
    }

    Path extractFolder = tmpFolder.newFolder();

    ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(),
            zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES);
    for (String name : names) {
        assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve(name)));
    }
    ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(),
            zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES);
    for (String name : names) {
        assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve(name)));
    }
}

From source file:io.github.jeremgamer.maintenance.Maintenance.java

public void backupProcess(CommandSender sender) {

    Calendar cal = Calendar.getInstance();
    DateFormat dateFormat = new SimpleDateFormat("yyyy MM dd - HH mm ss");
    String zipFile = new File("").getAbsolutePath() + "/backups/" + dateFormat.format(cal.getTime()) + ".zip";
    File zip = new File(zipFile);
    String srcDir = new File("").getAbsolutePath();

    try {//from   w  w w . j  a  v a2s.c  o  m

        try {
            zip.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        File dir = new File(srcDir);

        List<File> filesList = (List<File>) FileUtils.listFilesAndDirs(dir, TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        File[] files = filesList.toArray(new File[filesList.size()]);

        OutputStream out = new FileOutputStream(zip);
        ArchiveOutputStream zipOutput = new ZipArchiveOutputStream(out);
        String filePath;

        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {

            } else if (files[i].getAbsolutePath().contains(new File("").getAbsolutePath() + "\\backups\\")) {

            } else {

                filePath = files[i].getAbsolutePath().substring(srcDir.length() + 1);

                try {
                    ZipArchiveEntry entry = new ZipArchiveEntry(filePath);
                    entry.setSize(new File(files[i].getAbsolutePath()).length());
                    zipOutput.putArchiveEntry(entry);
                    IOUtils.copy(new FileInputStream(files[i].getAbsolutePath()), zipOutput);
                    zipOutput.closeArchiveEntry();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        zipOutput.finish();
        zipOutput.close();
        out.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (IllegalArgumentException iae) {
        iae.printStackTrace();
    }

    sender.sendMessage(getConfig().getString("backupSuccess").replaceAll("&", ""));
    getLogger().info("Backup success!");
}

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

private void writeIndexFile(String tname, ArchiveOutputStream out) {
    String html = getTemplate(epubPath + CATALOG_TEM);
    html = html.replaceAll("TEAMNAME", tname);
    InputStream in = new ByteArrayInputStream(html.getBytes());
    try {//from ww  w. j ava2s.  c  om
        out.putArchiveEntry(new ZipArchiveEntry(tname + "/index.html"));
        IOUtils.copy(in, out);
        in.close();
        out.closeArchiveEntry();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:com.iisigroup.cap.log.TimeFolderSizeRollingFileAppender.java

public void zipFiles(List<String> fileList, String destUrl) throws IOException {

    FileUtils.forceMkdir(new File(FilenameUtils.getFullPathNoEndSeparator(destUrl)));
    BufferedInputStream origin = null;
    FileOutputStream fos = null;/* w ww  .j av  a  2 s .  c o  m*/
    BufferedOutputStream bos = null;
    ZipArchiveOutputStream out = null;
    byte data[] = new byte[BUFFER];
    try {
        fos = new FileOutputStream(destUrl);
        bos = new BufferedOutputStream(fos);
        out = new ZipArchiveOutputStream(bos);

        for (String fName : fileList) {
            File file = new File(fName);
            FileInputStream fi = new FileInputStream(file);
            origin = new BufferedInputStream(fi, BUFFER);
            ZipArchiveEntry entry = new ZipArchiveEntry(file.getName());
            out.putArchiveEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            out.closeArchiveEntry();
            fi.close();
            origin.close();
        }

    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
            }
        }
        if (origin != null) {
            try {
                origin.close();
            } catch (IOException e) {
            }
        }
    }
}