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:freenet.client.async.ContainerInserter.java

private String createZipBucket(OutputStream os) throws IOException {
    if (logMINOR)
        Logger.minor(this, "Create a ZIP Bucket");

    ZipOutputStream zos = new ZipOutputStream(os);
    try {//www .ja v  a 2 s . co  m
        ZipEntry ze;

        for (ContainerElement ph : containerItems) {
            ze = new ZipEntry(ph.targetInArchive);
            ze.setTime(0);
            zos.putNextEntry(ze);
            BucketTools.copyTo(ph.data, zos, ph.data.size());
            zos.closeEntry();
        }
    } finally {
        zos.close();
    }

    return ARCHIVE_TYPE.ZIP.mimeTypes[0];
}

From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java

private static void addOriginSigsRels(final String signatureZipEntryName, final ZipOutputStream zipOutputStream)
        throws ParserConfigurationException, IOException, TransformerException {
    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);

    final Document originSignRelsDocument = documentBuilderFactory.newDocumentBuilder().newDocument();

    final Element relationshipsElement = originSignRelsDocument.createElementNS(RELATIONSHIPS_SCHEMA,
            "Relationships"); //$NON-NLS-1$
    relationshipsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", RELATIONSHIPS_SCHEMA); //$NON-NLS-1$
    originSignRelsDocument.appendChild(relationshipsElement);

    final Element relationshipElement = originSignRelsDocument.createElementNS(RELATIONSHIPS_SCHEMA,
            "Relationship"); //$NON-NLS-1$
    final String relationshipId = "rel-" + UUID.randomUUID().toString(); //$NON-NLS-1$
    relationshipElement.setAttribute("Id", relationshipId); //$NON-NLS-1$
    relationshipElement.setAttribute("Type", //$NON-NLS-1$
            "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature"); //$NON-NLS-1$

    relationshipElement.setAttribute("Target", FilenameUtils.getName(signatureZipEntryName)); //$NON-NLS-1$
    relationshipsElement.appendChild(relationshipElement);

    zipOutputStream.putNextEntry(new ZipEntry("_xmlsignatures/_rels/origin.sigs.rels")); //$NON-NLS-1$
    writeDocumentNoClosing(originSignRelsDocument, zipOutputStream, false);
}

From source file:io.druid.java.util.common.CompressionUtilsTest.java

@Test
public void testDecompressZip() throws IOException {
    final File tmpDir = temporaryFolder.newFolder("testDecompressZip");
    final File zipFile = new File(tmpDir, testFile.getName() + ".zip");
    Assert.assertFalse(zipFile.exists());
    try (final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile))) {
        out.putNextEntry(new ZipEntry("cool.file"));
        ByteStreams.copy(new FileInputStream(testFile), out);
        out.closeEntry();/*from  w  w  w.j ava 2 s.co m*/
    }
    try (final InputStream inputStream = CompressionUtils.decompress(new FileInputStream(zipFile),
            zipFile.getName())) {
        assertGoodDataStream(inputStream);
    }
}

From source file:fedora.server.storage.translation.AtomDOSerializer.java

/**
 * AUDIT datastream is rebuilt from the latest in-memory audit trail which
 * is a separate array list in the DigitalObject class. Audit trail
 * datastream re-created from audit records. There is only ONE version of
 * the audit trail datastream//w w w  .  ja v  a2 s. c  o  m
 * 
 * @throws ObjectIntegrityException
 * @throws StreamIOException 
 */
private void addAuditDatastream() throws ObjectIntegrityException, StreamIOException {
    if (m_obj.getAuditRecords().size() == 0) {
        return;
    }
    String dsId = m_pid.toURI() + "/AUDIT";
    String dsvId = dsId + "/" + DateUtility.convertDateToString(m_obj.getCreateDate());

    Entry dsEntry = m_feed.addEntry();
    dsEntry.setId(dsId);
    dsEntry.setTitle("AUDIT");
    dsEntry.setUpdated(m_obj.getCreateDate()); // create date?

    dsEntry.addCategory(MODEL.STATE.uri, "A", null);
    dsEntry.addCategory(MODEL.CONTROL_GROUP.uri, "X", null);
    dsEntry.addCategory(MODEL.VERSIONABLE.uri, "false", null);

    dsEntry.addLink(dsvId, Link.REL_ALTERNATE);

    Entry dsvEntry = m_feed.addEntry();
    dsvEntry.setId(dsvId);
    dsvEntry.setTitle("AUDIT.0");
    dsvEntry.setUpdated(m_obj.getCreateDate());
    ThreadHelper.addInReplyTo(dsvEntry, m_pid.toURI() + "/AUDIT");
    dsvEntry.addCategory(MODEL.FORMAT_URI.uri, AUDIT1_0.uri, null);
    dsvEntry.addCategory(MODEL.LABEL.uri, "Audit Trail for this object", null);
    if (m_format.equals(ATOM_ZIP1_1)) {
        String name = "AUDIT.0.xml";
        try {
            m_zout.putNextEntry(new ZipEntry(name));
            Reader r = new StringReader(DOTranslationUtility.getAuditTrail(m_obj));
            IOUtils.copy(r, m_zout, m_encoding);
            m_zout.closeEntry();
            r.close();
        } catch (IOException e) {
            throw new StreamIOException(e.getMessage(), e);
        }
        IRI iri = new IRI(name);
        dsvEntry.setSummary("AUDIT.0");
        dsvEntry.setContent(iri, "text/xml");
    } else {
        dsvEntry.setContent(DOTranslationUtility.getAuditTrail(m_obj), "text/xml");
    }
}

From source file:gov.nasa.ensemble.resources.ResourceUtil.java

public static void zipContainer(final IContainer container, final OutputStream os,
        final IProgressMonitor monitor) throws CoreException {
    final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(os));
    container.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    // monitor.beginTask("Zipping " + container.getName(), container.get);
    container.accept(new IResourceVisitor() {
        @Override//from  ww w . ja va 2 s.c o m
        public boolean visit(IResource resource) throws CoreException {
            // MSLICE-1258
            for (IProjectPublishFilter filter : publishFilters)
                if (!filter.shouldInclude(resource))
                    return true;

            if (resource instanceof IFile) {
                final IFile file = (IFile) resource;
                final IPath relativePath = ResourceUtil.getRelativePath(container, file).some();
                final ZipEntry entry = new ZipEntry(relativePath.toString());
                try {
                    out.putNextEntry(entry);
                    out.write(ResourceUtil.getContents(file));
                    out.closeEntry();
                } catch (IOException e) {
                    throw new CoreException(new Status(IStatus.ERROR, EnsembleResourcesPlugin.PLUGIN_ID,
                            "Failed to write contents of " + file.getName(), e));
                }
            } else if (resource instanceof IFolder) {
                final IFolder folder = (IFolder) resource;
                if (folder.members().length > 0)
                    return true;
                final IPath relativePath = ResourceUtil.getRelativePath(container, folder).some();
                final ZipEntry entry = new ZipEntry(relativePath.toString() + "/");
                try {
                    out.putNextEntry(entry);
                    out.closeEntry();
                } catch (IOException e) {
                    LogUtil.error(e);
                    throw new CoreException(new Status(IStatus.ERROR, EnsembleResourcesPlugin.PLUGIN_ID,
                            "Failed to compress directory " + folder.getName(), e));
                }
            }
            return true;
        }
    });
    try {
        out.close();
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, EnsembleResourcesPlugin.PLUGIN_ID,
                "Failed to close output stream", e));
    }
}

From source file:edu.lternet.pasta.datapackagemanager.DataPackageArchive.java

/**
 * Generate an "archive" of the data package by parsing and retrieving
 * components of the data package resource map
 * /*from  ww  w  .  ja v  a 2s . c  o m*/
 * @param scope
 *          The scope value of the data package
 * @param identifier
 *          The identifier value of the data package
 * @param revision
 *          The revision value of the data package
 * @param map
 *          The resource map of the data package
 * @param authToken
 *          The authentication token of the user requesting the archive
 * @param transaction
 *          The transaction id of the request
 * @return The file name of the data package archive
 * @throws Exception
 */
public String createDataPackageArchive(String scope, Integer identifier, Integer revision, String userId,
        AuthToken authToken, String transaction) throws Exception {

    String zipName = transaction + ".zip";
    String zipPath = tmpDir + "/";

    EmlPackageId emlPackageId = new EmlPackageId(scope, identifier, revision);

    StringBuffer manifest = new StringBuffer();

    Date now = new Date();
    manifest.append("Manifest file for " + zipName + " created on " + now.toString() + "\n");

    DataPackageManager dpm = null;

    /*
     * It is necessary to create a temporary file while building the ZIP archive
     * to prevent the client from accessing an incomplete product.
     */
    String tmpName = DigestUtils.md5Hex(transaction);
    File zFile = new File(zipPath + tmpName);

    if (zFile.exists()) {
        String gripe = "The resource " + zipName + "already exists!";
        throw new ResourceExistsException(gripe);
    }

    try {
        dpm = new DataPackageManager();
    } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
        throw e;
    }

    FileOutputStream fOut = null;

    try {
        fOut = new FileOutputStream(zFile);
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    if (dpm != null && fOut != null) {

        String map = null;

        try {
            map = dpm.readDataPackage(scope, identifier, revision.toString(), authToken, userId);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            throw e;
        }

        Scanner mapScanner = new Scanner(map);

        ZipOutputStream zOut = new ZipOutputStream(fOut);

        while (mapScanner.hasNextLine()) {

            FileInputStream fIn = null;
            String objectName = null;
            File file = null;

            String line = mapScanner.nextLine();

            if (line.contains(URI_MIDDLE_METADATA)) {

                try {
                    file = dpm.getMetadataFile(scope, identifier, revision.toString(), userId, authToken);
                    objectName = emlPackageId.toString() + ".xml";
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            } else if (line.contains(URI_MIDDLE_REPORT)) {

                try {
                    file = dpm.readDataPackageReport(scope, identifier, revision.toString(), emlPackageId,
                            authToken, userId);
                    objectName = emlPackageId.toString() + ".report.xml";
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            } else if (line.contains(URI_MIDDLE_DATA)) {

                String[] lineParts = line.split("/");
                String entityId = lineParts[lineParts.length - 1];
                String dataPackageResourceId = DataPackageManager.composeResourceId(ResourceType.dataPackage,
                        scope, identifier, revision, null);
                String entityResourceId = DataPackageManager.composeResourceId(ResourceType.data, scope,
                        identifier, revision, entityId);

                String entityName = null;
                String xml = null;

                try {
                    entityName = dpm.readDataEntityName(dataPackageResourceId, entityResourceId, authToken);
                    xml = dpm.readMetadata(scope, identifier, revision.toString(), userId, authToken);
                    objectName = dpm.findObjectName(xml, entityName);
                    file = dpm.getDataEntityFile(scope, identifier, revision.toString(), entityId, authToken,
                            userId);
                } catch (UnauthorizedException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                    manifest.append(objectName + " (access denied)\n");
                } catch (ResourceNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            }

            if (objectName != null && fIn != null) {

                ZipEntry zipEntry = new ZipEntry(objectName);

                try {
                    zOut.putNextEntry(zipEntry);

                    int length;
                    byte[] buffer = new byte[1024];

                    while ((length = fIn.read(buffer)) > 0) {
                        zOut.write(buffer, 0, length);
                    }

                    zOut.closeEntry();
                    fIn.close();

                } catch (IOException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

            }

        }

        // Create ZIP archive manifest
        File mFile = new File(zipPath + transaction + ".txt");
        FileUtils.writeStringToFile(mFile, manifest.toString());
        ZipEntry zipEntry = new ZipEntry("manifest.txt");

        try {

            FileInputStream fIn = new FileInputStream(mFile);
            zOut.putNextEntry(zipEntry);

            int length;
            byte[] buffer = new byte[1024];

            while ((length = fIn.read(buffer)) > 0) {
                zOut.write(buffer, 0, length);
            }

            zOut.closeEntry();
            fIn.close();

        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }

        // Close ZIP archive
        zOut.close();

        FileUtils.forceDelete(mFile);

    }

    File tmpFile = new File(zipPath + tmpName);
    File zipFile = new File(zipPath + zipName);

    // Copy hidden ZIP archive to visible ZIP archive, thus making available
    if (!tmpFile.renameTo(zipFile)) {
        String gripe = "Error renaming " + tmpName + " to " + zipName + "!";
        throw new IOException();
    }

    return zipName;

}

From source file:org.commonjava.aprox.depgraph.rest.RepositoryController.java

public void getZipRepository(final WebOperationConfigDTO dto, final OutputStream zipStream)
        throws AproxWorkflowException {
    ZipOutputStream stream = null;
    try {/*from   w ww.  j a  va  2  s  . c  o m*/
        final Map<ProjectVersionRef, Map<ArtifactRef, ConcreteResource>> contents = resolveContents(dto);

        final Set<ConcreteResource> entries = new HashSet<ConcreteResource>();
        final Set<String> seenPaths = new HashSet<String>();

        logger.info("Iterating contents with {} GAVs.", contents.size());
        for (final Map<ArtifactRef, ConcreteResource> artifactResources : contents.values()) {
            for (final Entry<ArtifactRef, ConcreteResource> entry : artifactResources.entrySet()) {
                final ArtifactRef ref = entry.getKey();
                final ConcreteResource resource = entry.getValue();

                //                        logger.info( "Checking {} ({}) for inclusion...", ref, resource );

                final String path = resource.getPath();
                if (seenPaths.contains(path)) {
                    logger.warn("Conflicting path: {}. Skipping {}.", path, ref);
                    continue;
                }

                seenPaths.add(path);

                //                        logger.info( "Adding to batch: {} via resource: {}", ref, resource );
                entries.add(resource);
            }
        }

        logger.info("Starting batch retrieval of {} artifacts.", entries.size());
        TransferBatch batch = new TransferBatch(entries);
        batch = transferManager.batchRetrieve(batch);

        logger.info("Retrieved {} artifacts. Creating zip.", batch.getTransfers().size());

        // FIXME: Stream to a temp file, then pass that to the Response.ok() handler...
        stream = new ZipOutputStream(zipStream);

        final List<Transfer> items = new ArrayList<Transfer>(batch.getTransfers().values());
        Collections.sort(items, new Comparator<Transfer>() {
            @Override
            public int compare(final Transfer f, final Transfer s) {
                return f.getPath().compareTo(s.getPath());
            }
        });

        for (final Transfer item : items) {
            //                    logger.info( "Adding: {}", item );
            final String path = item.getPath();
            if (item != null) {
                final ZipEntry ze = new ZipEntry(path);
                stream.putNextEntry(ze);

                InputStream itemStream = null;
                try {
                    itemStream = item.openInputStream();
                    copy(itemStream, stream);
                } finally {
                    closeQuietly(itemStream);
                }
            }
        }
    } catch (final IOException e) {
        throw new AproxWorkflowException("Failed to generate runtime repository. Reason: {}", e,
                e.getMessage());
    } catch (final TransferException e) {
        throw new AproxWorkflowException("Failed to generate runtime repository. Reason: {}", e,
                e.getMessage());
    } finally {
        closeQuietly(stream);
    }
}

From source file:ch.rgw.tools.StringTool.java

/**
 * Eine Hashtable in ein komprimiertes Byte-Array umwandeln
 * /*from   ww  w  .  j av  a2  s  .c o m*/
 * @param hash
 *            die Hashtable
 * @param compressMode
 *            GLZ, HUFF, BZIP2
 * @param ExtInfo
 *            Je nach Kompressmode ntige zusatzinfo
 * @return das byte-Array mit der komprimierten Hashtable
 * @deprecated compressmode is always ZIP now.
 */
@SuppressWarnings("unchecked")
@Deprecated
public static byte[] flatten(final Hashtable hash, final int compressMode, final Object ExtInfo) {
    ByteArrayOutputStream baos = null;
    OutputStream os = null;
    ObjectOutputStream oos = null;
    try {
        baos = new ByteArrayOutputStream(hash.size() * 30);
        switch (compressMode) {
        case GUESS:
        case ZIP:
            os = new ZipOutputStream(baos);
            ((ZipOutputStream) os).putNextEntry(new ZipEntry("hash"));
            break;
        case BZIP:
            os = new CBZip2OutputStream(baos);
            break;
        case HUFF:
            os = new HuffmanOutputStream(baos, (HuffmanTree) ExtInfo, 0);
            break;
        case GLZ:
            os = new GLZOutputStream(baos, hash.size() * 30);
            break;
        default:
            os = baos;
        }

        oos = new ObjectOutputStream(os);
        oos.writeObject(hash);
        if (os != null) {
            os.close();
        }
        baos.close();
        return baos.toByteArray();
    } catch (Exception ex) {
        ExHandler.handle(ex);
        return null;
    }
}