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:com.android.builder.testing.MockableJarGenerator.java

/**
 * Writes a modified *.class file to the output JAR file.
 *///  w ww  . java2  s  .  c om
private void rewriteClass(JarEntry entry, InputStream inputStream, JarOutputStream outputStream)
        throws IOException {
    ClassReader classReader = new ClassReader(inputStream);
    ClassNode classNode = new ClassNode(Opcodes.ASM5);

    classReader.accept(classNode, EMPTY_FLAGS);

    modifyClass(classNode);

    ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
    classNode.accept(classWriter);

    outputStream.putNextEntry(new ZipEntry(entry.getName()));
    outputStream.write(classWriter.toByteArray());
}

From source file:eu.scidipes.toolkits.pawebapp.preservation.PreserveFormManifestTask.java

@SuppressWarnings("boxing")
@Override/*from  w ww. j ava 2s  .c  o  m*/
public PreservationJobItemResult<Preservable, RegistryObject> call() throws PreservationStorageException {

    LOG.trace("New PreserveFormManifestTask started in thread [{}] at [{}]", Thread.currentThread().getId(),
            new Date().toString());
    try {
        final String riLocation;

        final CurationPersistentIdentifier rilCpidToPreserve;
        final FormFieldType dataType = form.getDataHolderType();

        if (dataType == BYTESTREAM) {

            LOG.trace("{} indicates a bytestream", form);

            final Node xml = XMLUtils.formFieldsToMetadata(form.getFormFields());

            final String b64BytesToPreserve;
            final String fileNameToPreserve;
            final String fileTypeToPreserve;

            if (xml != null) {
                LOG.debug("Preparing: {} for preservation - flex fields found", form);

                if (LOG.isTraceEnabled()) {
                    LOG.trace(XMLUtils.nodeToString(xml, true, false));
                }

                final byte[] mainFileBytes = Base64.decodeBase64(form.getDataHolder());
                final byte[] metaFileBytes = XMLUtils.nodeToString(xml, true, false).getBytes();

                final String mainFileName = form.getDataHolderMetadata().get(CoreFieldMetadata.FILE_NAME);
                final String metaFileName = mainFileName + "_meta.xml";

                final ZipEntry zipMain = new ZipEntry(mainFileName);
                final ZipEntry zipMeta = new ZipEntry(metaFileName);

                final Set<ByteArrayZipEntry> entries = new HashSet<>();
                entries.add(new ByteArrayZipEntry(mainFileBytes, zipMain));
                entries.add(new ByteArrayZipEntry(metaFileBytes, zipMeta));

                /* Set the key preservation details from the zip: */
                b64BytesToPreserve = ZipUtils.byteArrayZipEntriesToBase64(entries);
                fileNameToPreserve = mainFileName + "_pa-packaged.zip";
                fileTypeToPreserve = "application/zip";
                rilCpidToPreserve = new CoreCurationPersistentIdentifier(form.getRILCPID().getUID() + "-Z");

            } else {
                /* Just set the key preservation details dreckly from the form: */
                b64BytesToPreserve = form.getDataHolder();
                fileNameToPreserve = form.getDataHolderMetadata().get(FILE_NAME);
                fileTypeToPreserve = form.getDataHolderMetadata().get(FILE_MIMETYPE);
                rilCpidToPreserve = form.getRILCPID();
            }

            final byte[] dataBytes = Base64.decodeBase64(b64BytesToPreserve);
            final String fileName = fileNameToPreserve;
            final String fileType = fileTypeToPreserve;

            final Repository uploadRepo = registry.getUploadRepository();
            riLocation = uploadRepo.storeRIObject(dataBytes, fileName, fileType);

        } else if (dataType == URI) {

            LOG.trace("{} indicates a URI", form);
            rilCpidToPreserve = form.getRILCPID();
            riLocation = form.getDataHolder();

        } else {
            throw new PreservationStorageException("Unhandled storage type [" + dataType + "] for RI", form);
        }

        final UploadManifest uploadManifest;

        /* Manifest CPID may have already been set on Form instance: */
        if (form.getManifestCPID() == null) {
            uploadManifest = new UploadManifest(rilCpidToPreserve);
        } else {
            uploadManifest = new UploadManifest(form.getRILCPID(), form.getManifestCPID());
        }

        final StringBuilder manifestName = new StringBuilder();
        manifestName.append(form.getParentBundle().getDatasetName());
        manifestName.append('-' + form.getName());

        if (!StringUtils.isBlank(form.getItemFileName())) {
            manifestName.append('-' + form.getItemFileName().trim());
        }

        LOG.debug("Creating manifest for '{}' with location '{}'", manifestName, riLocation);

        uploadManifest.setResourceName(manifestName.toString());
        uploadManifest.setLocation(new URL(riLocation));
        uploadManifest.getCategories().addAll(form.getCategories());

        LOG.debug("Storing new manifest '{}' to {}", uploadManifest.getManifestCpid(), registry);

        FrameworkWrapper.storeManifest(uploadManifest, registry);

        /* TODO: Revisit: pause should not be necessary but without it the retrieval fails intermittently */
        Thread.sleep(2000);

        final Manifest stored = FrameworkWrapper.getManifest(uploadManifest.getManifestCpid());

        /* Set the preserved CPID on the form instance and set preserved flag: */
        synchronized (form) {
            if (form.getManifestCPID() == null) {
                ((FormImpl) form).setManifestCPID(stored.getManifestCpid());
            }
            ((FormImpl) form).setPreserved(true);
        }

        return new PreservationJobItemResultImpl(form, stored);

    } catch (final Exception e) {
        throw new PreservationStorageException(e, form);
    } finally {
        LOG.trace("Upload callable finished in thread [{}] at [{}]", Thread.currentThread().getId(),
                new Date().toString());
    }
}

From source file:fr.gael.dhus.service.job.SendLogsJob.java

@Override
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    if (!configurationManager.getSendLogsCronConfiguration().isActive())
        return;/*from   w  w  w . j a v a  2s . co  m*/
    long start = System.currentTimeMillis();
    logger.info("SCHEDULER : Send Administrative logs.");
    if (!DHuS.isStarted()) {
        logger.warn("SCHEDULER : Not run while system not fully initialized.");
        return;
    }

    String[] addresses = configurationManager.getSendLogsCronConfiguration().getAddresses().split(",");
    // Case of no addresses available: use system support
    if ((addresses == null) || (addresses.length == 0) || "".equals(addresses[0].trim())) {
        String email = configurationManager.getSupportConfiguration().getMail();
        if ((email == null) || "".equals(email)) {
            throw new MailException("Support e-mail not configured, " + "system logs will not be send");
        }
        addresses = new String[] { email };
    }

    RollingFileAppender rollingFileAppender = (RollingFileAppender) ((org.apache.logging.log4j.core.Logger) LogManager
            .getRootLogger()).getAppenders().get("RollingFile");
    if (rollingFileAppender == null) {
        throw new MailException("No rolling log file defined");
    }

    String logPath = rollingFileAppender.getFileName();

    if ((logPath == null) || logPath.trim().equals("")) {
        throw new MailException("Log file not defined");
    }

    File logs = new File(logPath);
    if (!logs.exists()) {
        throw new MailException("Log file not present : " + logs.getPath());
    }

    Date now = new Date();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'@'HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    String docFilename = configurationManager.getNameConfiguration().getShortName().toLowerCase() + "-"
            + df.format(now);

    File zipLogs;
    try {
        zipLogs = File.createTempFile(docFilename, ".zip");
    } catch (IOException e) {
        throw new MailException("Cannot create temporary zip log file.", e);
    }

    // compress logs file to zip format
    FileOutputStream fos;
    ZipOutputStream zos = null;
    FileInputStream fis = null;
    try {
        int length;
        byte[] buffer = new byte[1024];
        ZipEntry entry = new ZipEntry(docFilename + ".txt");

        fos = new FileOutputStream(zipLogs);
        zos = new ZipOutputStream(fos);
        fis = new FileInputStream(logs);

        zos.setLevel(Deflater.BEST_COMPRESSION);
        zos.putNextEntry(entry);
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
    } catch (IOException e) {
        throw new MailException("An error occurred during compression " + "logs file, cannot send logs !", e);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (zos != null) {
                zos.closeEntry();
                zos.close();
            }
        } catch (IOException e) {
            throw new MailException("An error occurred during compression " + "logs file, cannot send logs !",
                    e);
        }
    }

    EmailAttachment attachment = new EmailAttachment();
    attachment.setDescription(
            configurationManager.getNameConfiguration().getShortName() + " Logs " + now.toString());
    attachment.setPath(zipLogs.getPath());
    attachment.setName(zipLogs.getName());

    // Prepare the addresses
    List<String> ads = new ArrayList<String>();
    for (String email : addresses) {
        StringTokenizer tk = new StringTokenizer(email, ", ");
        while (tk.hasMoreTokens()) {
            String token = tk.nextToken().trim();
            if (!token.isEmpty())
                ads.add(token);
        }
    }
    for (String email : ads) {
        try {
            String server = configurationManager.getServerConfiguration().getExternalHostname();
            String url = configurationManager.getServerConfiguration().getExternalUrl();

            mailServer.send(email, null, null,
                    "[" + configurationManager.getNameConfiguration().getShortName().toLowerCase() + "@"
                            + server + "] logs of " + df.format(now),
                    "Here is attached " + configurationManager.getNameConfiguration().getShortName()
                            + " logs of \"" + url + "\" host.\n\n" + "Kind Regards.\nThe "
                            + configurationManager.getNameConfiguration().getShortName() + " Team.",
                    attachment);
            logger.info("Logs Sent to " + email);
        } catch (EmailException e) {
            throw new MailException("Cannot send logs to " + email, e);
        }
    }

    if (!zipLogs.delete()) {
        logger.warn("Cannot remove mail attachment: " + zipLogs.getAbsolutePath());
    }

    logger.info("SCHEDULER : Send Administrative logs done - " + (System.currentTimeMillis() - start) + "ms");
}

From source file:de.micromata.genome.gdbfs.FileSystemUtils.java

/**
 * Copy to zip./*from   ww  w .j  a va 2s  .  c om*/
 *
 * @param source the source
 * @param zout the zout
 */
public static void copyToZip(FsObject source, ZipOutputStream zout) {
    String name = source.getName();
    if (source.isDirectory() == true) {
        name += "/";
    }
    ZipEntry ze = new ZipEntry(name);
    try {
        if (source.isFile() == true) {
            zout.putNextEntry(ze);
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            source.getFileSystem().readBinaryFile(source.getName(), bout);
            zout.write(bout.toByteArray());
            zout.closeEntry();
        } else if (source.isDirectory() == true) {
            zout.putNextEntry(ze);
            zout.closeEntry();
        }
    } catch (IOException ex) {
        throw new RuntimeIOException(ex);
    }
}

From source file:io.lavagna.service.LavagnaExporter.java

private void exportFiles(ZipOutputStream zf, OutputStreamWriter osw) throws IOException {
    osw.flush();/*w w w . j  a va 2 s  .co m*/
    for (CardDataUploadContentInfo fileData : cardDataRepository.findAllDataUploadContentInfo()) {
        zf.putNextEntry(new ZipEntry("files/" + fileData.getDigest()));
        cardDataRepository.outputFileContent(fileData.getDigest(), zf);
        writeEntry("files/" + fileData.getDigest() + ".json", fileData, zf, osw);
    }
}

From source file:com.netflix.nicobar.core.module.ScriptModuleUtils.java

/**
 * Convert a ScriptModule to its compiled equivalent ScriptArchive.
 * <p>/*from  ww w .j  av  a  2  s .co m*/
 * A jar script archive is created containing compiled bytecode
 * from a script module, as well as resources and other metadata from
 * the source script archive.
 * <p>
 * This involves serializing the class bytes of all the loaded classes in
 * the script module, as well as copying over all entries in the original
 * script archive, minus any that have excluded extensions. The module spec
 * of the source script archive is transferred as is to the target bytecode
 * archive.
 *
 * @param module the input script module containing loaded classes
 * @param jarPath the path to a destination JarScriptArchive.
 * @param excludeExtensions a set of extensions with which
 *        source script archive entries can be excluded.
 *
 * @throws Exception
 */
public static void toCompiledScriptArchive(ScriptModule module, Path jarPath, Set<String> excludeExtensions)
        throws Exception {
    ScriptArchive sourceArchive = module.getSourceArchive();
    JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jarPath.toFile()));
    try {
        // First copy all resources (excluding those with excluded extensions)
        // from the source script archive, into the target script archive
        for (String archiveEntry : sourceArchive.getArchiveEntryNames()) {
            URL entryUrl = sourceArchive.getEntry(archiveEntry);
            boolean skip = false;
            for (String extension : excludeExtensions) {
                if (entryUrl.toString().endsWith(extension)) {
                    skip = true;
                    break;
                }
            }

            if (skip)
                continue;

            InputStream entryStream = entryUrl.openStream();
            byte[] entryBytes = IOUtils.toByteArray(entryStream);
            entryStream.close();

            jarStream.putNextEntry(new ZipEntry(archiveEntry));
            jarStream.write(entryBytes);
            jarStream.closeEntry();
        }

        // Now copy all compiled / loaded classes from the script module.
        Set<Class<?>> loadedClasses = module.getModuleClassLoader().getLoadedClasses();
        Iterator<Class<?>> iterator = loadedClasses.iterator();
        while (iterator.hasNext()) {
            Class<?> clazz = iterator.next();
            String classPath = clazz.getName().replace(".", "/") + ".class";
            URL resourceURL = module.getModuleClassLoader().getResource(classPath);
            if (resourceURL == null) {
                throw new Exception("Unable to find class resource for: " + clazz.getName());
            }

            InputStream resourceStream = resourceURL.openStream();
            jarStream.putNextEntry(new ZipEntry(classPath));
            byte[] classBytes = IOUtils.toByteArray(resourceStream);
            resourceStream.close();
            jarStream.write(classBytes);
            jarStream.closeEntry();
        }

        // Copy the source moduleSpec, but tweak it to specify the bytecode compiler in the
        // compiler plugin IDs list.
        ScriptModuleSpec moduleSpec = sourceArchive.getModuleSpec();
        ScriptModuleSpec.Builder newModuleSpecBuilder = new ScriptModuleSpec.Builder(moduleSpec.getModuleId());
        newModuleSpecBuilder.addCompilerPluginIds(moduleSpec.getCompilerPluginIds());
        newModuleSpecBuilder.addCompilerPluginId(BytecodeLoadingPlugin.PLUGIN_ID);
        newModuleSpecBuilder.addMetadata(moduleSpec.getMetadata());
        newModuleSpecBuilder.addModuleDependencies(moduleSpec.getModuleDependencies());

        // Serialize the modulespec with GSON and its default spec file name
        ScriptModuleSpecSerializer specSerializer = new GsonScriptModuleSpecSerializer();
        String json = specSerializer.serialize(newModuleSpecBuilder.build());
        jarStream.putNextEntry(new ZipEntry(specSerializer.getModuleSpecFileName()));
        jarStream.write(json.getBytes(Charsets.UTF_8));
        jarStream.closeEntry();
    } finally {
        if (jarStream != null) {
            jarStream.close();
        }
    }
}

From source file:gov.nih.nci.caarray.services.external.v1_0.data.AbstractDataApiUtils.java

/**
 * {@inheritDoc}/*  ww w  .  java 2  s. co m*/
 */
public void copyMageTabZipToOutputStream(CaArrayEntityReference experimentRef, OutputStream ostream)
        throws InvalidReferenceException, DataTransferException, IOException {
    MageTabFileSet mtset = exportMageTab(experimentRef);
    ZipOutputStream zos = new ZipOutputStream(ostream);
    zos.putNextEntry(new ZipEntry(mtset.getIdf().getMetadata().getName()));
    IOUtils.write(mtset.getIdf().getContents(), zos);
    zos.putNextEntry(new ZipEntry(mtset.getSdrf().getMetadata().getName()));
    IOUtils.write(mtset.getSdrf().getContents(), zos);
    for (gov.nih.nci.caarray.external.v1_0.data.File dataFile : mtset.getDataFiles()) {
        zos.putNextEntry(new ZipEntry(dataFile.getMetadata().getName()));
        copyFileContentsToOutputStream(dataFile.getReference(), false, zos);
    }
    zos.finish();
}

From source file:de.bps.onyx.plugin.OnyxExportManager.java

public void exportResults(List<QTIResultSet> resultSets, ZipOutputStream exportStream,
        CourseNode currentCourseNode) {//w w w  . ja  va  2  s  .co  m
    final String path = createTargetFilename(currentCourseNode.getShortTitle(), "TEST");
    for (final QTIResultSet rs : resultSets) {
        String resultXml = getResultXml(rs.getIdentity().getName(),
                currentCourseNode.getModuleConfiguration().get(IQEditController.CONFIG_KEY_TYPE).toString(),
                currentCourseNode.getIdent(), rs.getAssessmentID());

        String filename = path + "/" + rs.getIdentity().getName() + "_" + rs.getCreationDate() + ".xml";
        try {
            exportStream.putNextEntry(new ZipEntry(filename));
            IOUtils.write(resultXml, exportStream);
            exportStream.closeEntry();
        } catch (IOException e) {
            log.error("", e);
        }
    }
}

From source file:com.liferay.portal.deploy.hot.ExtHotDeployListener.java

private void zipWebInfJar(String zipName, File[] files) throws Exception {
    byte[] buffer = new byte[4096]; // Create a buffer for copying
    int bytesRead;

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipName));
    try {//from   w w w  .ja  v a  2 s.  c om
        for (int i = 0; i < files.length; i++) {
            File f = files[i];
            if (f.isDirectory()) {
                continue;
            }

            String fileName = "WEB-INF/" + f.getName();
            FileInputStream in = new FileInputStream(f); // Stream to read file
            try {
                ZipEntry entry = new ZipEntry(fileName); // Make a ZipEntry
                out.putNextEntry(entry); // Store entry
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            } finally {
                in.close();
            }
        }
    } finally {
        out.close();
    }
}

From source file:be.fedict.eid.applet.service.signer.odf.AbstractODFSignatureService.java

private void outputSignedOpenDocument(byte[] signatureData) throws IOException {
    LOG.debug("output signed open document");
    OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream();
    if (null == signedOdfOutputStream) {
        throw new NullPointerException("signedOpenDocumentOutputStream is null");
    }/*w w  w.j ava  2 s  .c o m*/
    /*
     * Copy the original ODF content to the signed ODF package.
     */
    ZipOutputStream zipOutputStream = new ZipOutputStream(signedOdfOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(this.getOpenDocumentURL().openStream());
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) {
            zipOutputStream.putNextEntry(zipEntry);
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }
    zipInputStream.close();
    /*
     * Add the ODF XML signature file to the signed ODF package.
     */
    zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE);
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();
}