Example usage for java.util.zip ZipEntry ZipEntry

List of usage examples for java.util.zip ZipEntry ZipEntry

Introduction

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

Prototype

public ZipEntry(ZipEntry e) 

Source Link

Document

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

Usage

From source file:eu.europa.esig.dss.asic.signature.ASiCService.java

@Override
public DSSDocument extendDocument(final DSSDocument toExtendDocument, final ASiCSignatureParameters parameters)
        throws DSSException {
    try {/*from  ww  w .  java 2s  .  c o  m*/
        final DocumentValidator validator = SignedDocumentValidator.fromDocument(toExtendDocument);
        final DocumentValidator subordinatedValidator = validator.getSubordinatedValidator();
        final DocumentSignatureService specificService = getSpecificService(
                parameters.aSiC().getUnderlyingForm());
        specificService.setTspSource(tspSource);

        final AbstractSignatureParameters underlyingParameters = getParameters(parameters);
        final DSSDocument detachedContent = parameters.getDetachedContent();
        final DSSDocument detachedContents = getDetachedContents(subordinatedValidator, detachedContent);
        underlyingParameters.setDetachedContent(detachedContents);
        final DSSDocument signature = subordinatedValidator.getDocument();
        final DSSDocument signedDocument = specificService.extendDocument(signature, underlyingParameters);

        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        final ZipOutputStream zipOutputStream = new ZipOutputStream(output);
        final ZipInputStream zipInputStream = new ZipInputStream(toExtendDocument.openStream());
        ZipEntry entry;
        while ((entry = getNextZipEntry(zipInputStream)) != null) {

            final String name = entry.getName();
            final ZipEntry newEntry = new ZipEntry(name);
            if (ASiCContainerValidator.isMimetype(name)) {

                storeMimetype(parameters.aSiC(), zipOutputStream);
            } else if (ASiCContainerValidator.isXAdES(name) || ASiCContainerValidator.isCAdES(name)) {

                createZipEntry(zipOutputStream, newEntry);
                final InputStream inputStream = signedDocument.openStream();
                IOUtils.copy(inputStream, zipOutputStream);
                IOUtils.closeQuietly(inputStream);
            } else {

                createZipEntry(zipOutputStream, newEntry);
                IOUtils.copy(zipInputStream, zipOutputStream);
            }
        }
        IOUtils.closeQuietly(zipInputStream);
        IOUtils.closeQuietly(zipOutputStream);
        DSSDocument asicSignature = new InMemoryDocument(output.toByteArray(), null,
                getMimeType(parameters.aSiC().getContainerForm()));
        asicSignature.setName(DSSUtils.getFinalFileName(toExtendDocument, SigningOperation.EXTEND,
                parameters.getSignatureLevel()));
        return asicSignature;
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

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;
        }/*  www. j a v a2s  .c om*/

        // 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:azkaban.common.utils.Utils.java

private static void zipFile(String path, File input, ZipOutputStream zOut) throws IOException {
    if (input.isDirectory()) {
        File[] files = input.listFiles();
        if (files != null) {
            for (File f : files) {
                String childPath = path + input.getName() + (f.isDirectory() ? "/" : "");
                zipFile(childPath, f, zOut);
            }//from  ww  w. ja  v a 2 s .c  o m
        }
    } else {
        String childPath = path + (path.length() > 0 ? "/" : "") + input.getName();
        ZipEntry entry = new ZipEntry(childPath);
        zOut.putNextEntry(entry);
        InputStream fileInputStream = new BufferedInputStream(new FileInputStream(input));
        IOUtils.copy(fileInputStream, zOut);
        fileInputStream.close();
    }
}

From source file:io.wcm.tooling.commons.contentpackagebuilder.ContentPackage.java

/**
 * Writes an XML document as binary file entry to the ZIP output stream.
 * @param path Content path/*from   w  ww .j  a va  2s .c  o m*/
 * @param doc XML conent
 * @throws IOException
 */
private void writeXmlDocument(String path, Document doc) throws IOException {
    zip.putNextEntry(new ZipEntry(path));
    try {
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(zip);
        transformer.transform(source, result);
    } catch (TransformerException ex) {
        throw new IOException("Failed to generate XML: " + ex.getMessage(), ex);
    } finally {
        zip.closeEntry();
    }
}

From source file:com.sencko.basketball.stats.advanced.FIBAJsonParser.java

private static void addToCache(String cacheName, Game game)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    logger.log(Level.FINEST, "Saving file {0} to cache", cacheName);
    File file = new File("archive.zip");
    File file1 = null;//from ww w.j  av a2 s.c  o m
    if (file.exists()) {
        //copy to archive1, return
        file1 = new File("archive1.zip");
        if (file1.exists()) {
            if (!file1.delete()) {
                logger.log(Level.WARNING, "Unable to delete file {0}", file1.getCanonicalPath());
                return;
            }
        }
        if (!file.renameTo(file1)) {
            logger.log(Level.WARNING, "Unable to rename file {0} to {1}",
                    new Object[] { file.getCanonicalPath(), file1.getCanonicalPath() });
            // unable to move to archive1 and whole operation fails!!!
            return;
        }
    }

    try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file))) {
        out.setLevel(9);
        // name the file inside the zip  file 
        out.putNextEntry(new ZipEntry(cacheName));
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out, "UTF-8");
        JsonWriter jsonWriter = new JsonWriter(outputStreamWriter);
        jsonWriter.setIndent("  ");
        builder.create().toJson(game, Game.class, jsonWriter);
        jsonWriter.flush();

        if (file1 != null) {
            try (ZipFile zipFile = new ZipFile(file1)) {
                Enumeration<? extends ZipEntry> files = zipFile.entries();
                while (files.hasMoreElements()) {
                    ZipEntry entry = files.nextElement();
                    try (InputStream in = zipFile.getInputStream(entry)) {
                        out.putNextEntry(new ZipEntry(entry.getName()));

                        IOUtils.copy(in, out);
                    }
                }
            }
            file1.delete();

        }
    }
}

From source file:com.mcleodmoores.mvn.natives.PackageMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (isSkip()) {
        getLog().debug("Skipping step");
        return;//from w w w  .  ja  v  a 2s  .  c  o  m
    }
    applyDefaults();
    final MavenProject project = (MavenProject) getPluginContext().get("project");
    final File targetDir = new File(project.getBuild().getDirectory());
    targetDir.mkdirs();
    final File targetFile = new File(targetDir, project.getArtifactId() + ".zip");
    getLog().debug("Writing to " + targetFile);
    final OutputStream output;
    try {
        output = getOutputStreams().open(targetFile);
    } catch (final IOException e) {
        throw new MojoFailureException("Can't write to " + targetFile);
    }
    final IOExceptionHandler errorLog = new MojoLoggingErrorCallback(this);
    if ((new IOCallback<OutputStream, Boolean>(output) {

        @Override
        protected Boolean apply(final OutputStream output) throws IOException {
            final byte[] buffer = new byte[4096];
            final ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(output));
            for (final Map.Entry<Source, String> sourceInfo : gatherSources().entrySet()) {
                final Source source = sourceInfo.getKey();
                getLog().info("Processing " + source.getPath() + " into " + sourceInfo.getValue() + " ("
                        + source.getPattern() + ")");
                final File folder = new File(source.getPath());
                final String[] files = folder.list(new PatternFilenameFilter(regex(source.getPattern())));
                if (files != null) {
                    for (final String file : files) {
                        getLog().debug("Adding " + file + " to archive");
                        final ZipEntry entry = new ZipEntry(sourceInfo.getValue() + file);
                        zip.putNextEntry(entry);
                        if ((new IOCallback<InputStream, Boolean>(
                                getInputStreams().open(new File(folder, file))) {

                            @Override
                            protected Boolean apply(final InputStream input) throws IOException {
                                int bytes;
                                while ((bytes = input.read(buffer, 0, buffer.length)) > 0) {
                                    zip.write(buffer, 0, bytes);
                                }
                                return Boolean.TRUE;
                            }

                        }).call(errorLog) != Boolean.TRUE) {
                            return Boolean.FALSE;
                        }
                        zip.closeEntry();
                    }
                } else {
                    getLog().debug("Source folder is empty or does not exist");
                }
            }
            zip.close();
            return Boolean.TRUE;
        }

    }).call(errorLog) != Boolean.TRUE) {
        throw new MojoFailureException("Error writing to " + targetFile);
    }
    project.getArtifact().setFile(targetFile);
}

From source file:com.thejustdo.util.Utils.java

/**
 * Creates a ZIP file containing all the files inside a directory.
 * @param location Directory to read.//from   w ww .j av  a2 s  .co  m
 * @param pathname Name and path where to store the file.
 * @throws FileNotFoundException If can't find the initial directory.
 * @throws IOException If can't read/write.
 */
public static void zipDirectory(File location, File pathname) throws FileNotFoundException, IOException {

    BufferedInputStream origin;
    FileOutputStream dest = new FileOutputStream(pathname);
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
    byte data[] = new byte[2048];

    // 1. Get a list of files from current directory
    String files[] = location.list();
    File f;

    // 2. Adding each file to the zip-set.
    for (String s : files) {
        log.info(String.format("Adding: %s", s));
        f = new File(location, s);
        FileInputStream fi = new FileInputStream(f);
        origin = new BufferedInputStream(fi, 2048);
        ZipEntry entry = new ZipEntry(location.getName() + File.separator + s);
        out.putNextEntry(entry);
        int count;
        while ((count = origin.read(data, 0, 2048)) != -1) {
            out.write(data, 0, count);
        }
        origin.close();
    }
    out.close();
}

From source file:com.cisco.ca.cstg.pdi.services.ConfigurationServiceImpl.java

private void addToZipOutputStream(String filePath, ZipOutputStream zip) throws IOException {
    byte[] buf = new byte[1024];
    int len;/*ww  w  .  j  a  v a2 s . c o  m*/
    File input = new File(filePath);
    try (FileInputStream in = new FileInputStream(input)) {
        zip.putNextEntry(new ZipEntry(input.getName()));
        while ((len = in.read(buf)) > 0) {
            zip.write(buf, 0, len);
        }
        zip.flush();
    }
}

From source file:de.unisaarland.swan.export.ExportUtil.java

private void marshalScheme(Project proj, ZipOutputStream zos) throws IOException {
    final Scheme schemeOrig = proj.getScheme();
    final de.unisaarland.swan.export.model.xml.scheme.Scheme schemeExport = (de.unisaarland.swan.export.model.xml.scheme.Scheme) mapperFacade
            .map(schemeOrig, SCHEME_EXPORT_CLASS);

    String fileName = schemeExport.getName() + ".xml";
    File schemefile = new File(fileName);

    marshalXMLToSingleFile(schemeExport, schemefile);

    zos.putNextEntry(new ZipEntry(fileName));
    zos.write(FileUtils.readFileToByteArray(schemefile));
    zos.closeEntry();/*from   w w  w. j a v  a2s. c  o m*/
}

From source file:com.cloudera.sqoop.orm.CompilationManager.java

/**
 * Searches through a directory and its children for .class
 * files to add to a jar.//from ww w.j av  a 2s  . c  o m
 *
 * @param dir - The root directory to scan with this algorithm.
 * @param jstream - The JarOutputStream to write .class files to.
 */
private void addClassFilesFromDir(File dir, JarOutputStream jstream) throws IOException {
    LOG.debug("Scanning for .class files in directory: " + dir);
    List<File> dirEntries = FileListing.getFileListing(dir);
    String baseDirName = dir.getAbsolutePath();
    if (!baseDirName.endsWith(File.separator)) {
        baseDirName = baseDirName + File.separator;
    }

    // For each input class file, create a zipfile entry for it,
    // read the file into a buffer, and write it to the jar file.
    for (File entry : dirEntries) {
        if (!entry.isDirectory()) {
            // Chomp off the portion of the full path that is shared
            // with the base directory where class files were put;
            // we only record the subdir parts in the zip entry.
            String fullPath = entry.getAbsolutePath();
            String chompedPath = fullPath.substring(baseDirName.length());

            boolean include = chompedPath.endsWith(".class") && sources
                    .contains(chompedPath.substring(0, chompedPath.length() - ".class".length()) + ".java");

            if (include) {
                // include this file.
                LOG.debug("Got classfile: " + entry.getPath() + " -> " + chompedPath);
                ZipEntry ze = new ZipEntry(chompedPath);
                jstream.putNextEntry(ze);
                copyFileToStream(entry, jstream);
                jstream.closeEntry();
            }
        }
    }
}