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.build.gradle.integration.application.ExternalBuildPluginTest.java

@Test
public void testBuild() throws ProcessException, IOException, ParserConfigurationException, SAXException {
    FileUtils.write(mProject.getBuildFile(),
            "" + "apply from: \"../commonHeader.gradle\"\n" + "buildscript {\n "
                    + "  apply from: \"../commonBuildScript.gradle\"\n" + "}\n" + "\n"
                    + "apply plugin: 'base'\n" + "apply plugin: 'com.android.external.build'\n" + "\n"
                    + "externalBuild {\n" + "  executionRoot = $/" + mProject.getTestDir().getAbsolutePath()
                    + "/$\n" + "  buildManifestPath = $/" + manifestFile.getAbsolutePath() + "/$\n" + "}\n");

    mProject.executor().withInstantRun(23, ColdswapMode.AUTO).withPackaging(mPackaging).run("clean", "process");

    InstantRunBuildContext instantRunBuildContext = loadFromBuildInfo();
    assertThat(instantRunBuildContext.getPreviousBuilds()).hasSize(1);
    assertThat(instantRunBuildContext.getLastBuild()).isNotNull();
    assertThat(instantRunBuildContext.getLastBuild().getArtifacts()).hasSize(1);
    InstantRunBuildContext.Build fullBuild = instantRunBuildContext.getLastBuild();
    assertThat(fullBuild.getVerifierStatus().get()).isEqualTo(InstantRunVerifierStatus.INITIAL_BUILD);
    assertThat(fullBuild.getArtifacts()).hasSize(1);
    InstantRunBuildContext.Artifact artifact = fullBuild.getArtifacts().get(0);
    assertThat(artifact.getType()).isEqualTo(InstantRunBuildContext.FileType.MAIN);
    assertThat(artifact.getLocation().exists()).isTrue();

    ApkSubject apkSubject = expect.about(ApkSubject.FACTORY).that(artifact.getLocation());
    apkSubject.contains("instant-run.zip");
    assertThat(apkSubject.hasMainDexFile());

    // now perform a hot swap test.
    File mainClasses = new File(mProject.getTestDir(), "jars/main/classes.jar");
    assertThat(mainClasses.exists()).isTrue();

    File originalFile = new File(mainClasses.getParentFile(), "original_classes.jar");
    assertThat(mainClasses.renameTo(originalFile)).isTrue();

    try (JarFile inputJar = new JarFile(originalFile);
            JarOutputStream jarOutputFile = new JarOutputStream(new BufferedOutputStream(
                    new FileOutputStream(new File(mainClasses.getParentFile(), "classes.jar"))))) {
        Enumeration<JarEntry> entries = inputJar.entries();
        while (entries.hasMoreElements()) {
            JarEntry element = entries.nextElement();
            try (InputStream inputStream = new BufferedInputStream(inputJar.getInputStream(element))) {
                if (!element.isDirectory()) {
                    jarOutputFile.putNextEntry(new ZipEntry(element.getName()));
                    try {
                        if (element.getName().contains("MainActivity.class")) {
                            // perform hot swap change
                            byte[] classBytes = new byte[(int) element.getSize()];
                            ByteStreams.readFully(inputStream, classBytes);
                            classBytes = hotswapChange(classBytes);
                            jarOutputFile.write(classBytes);
                        } else {
                            ByteStreams.copy(inputStream, jarOutputFile);
                        }//from w w  w.  j  a  v a  2  s.  c om
                    } finally {
                        jarOutputFile.closeEntry();
                    }
                }
            }
        }
    }

    mProject.executor().withInstantRun(23, ColdswapMode.AUTO).withPackaging(mPackaging).run("process");

    instantRunBuildContext = loadFromBuildInfo();
    assertThat(instantRunBuildContext.getPreviousBuilds()).hasSize(2);
    InstantRunBuildContext.Build lastBuild = instantRunBuildContext.getLastBuild();
    assertThat(lastBuild).isNotNull();
    assertThat(lastBuild.getVerifierStatus().isPresent());
    assertThat(lastBuild.getVerifierStatus().get()).isEqualTo(InstantRunVerifierStatus.COMPATIBLE);
    assertThat(lastBuild.getArtifacts()).hasSize(1);
    artifact = lastBuild.getArtifacts().get(0);
    assertThat(artifact.getType()).isEqualTo(InstantRunBuildContext.FileType.RELOAD_DEX);
    assertThat(artifact.getLocation()).isNotNull();
    File dexFile = artifact.getLocation();
    assertThat(dexFile.exists()).isTrue();
    DexFileSubject reloadDex = expect.about(DexFileSubject.FACTORY).that(dexFile);
    reloadDex.hasClass("Lcom/android/tools/fd/runtime/AppPatchesLoaderImpl;").that();
    reloadDex.hasClass("Lcom/example/jedo/blazeapp/MainActivity$override;").that();
}

From source file:net.solarnetwork.node.backup.FileSystemBackupService.java

@Override
public Backup performBackup(final Iterable<BackupResource> resources) {
    if (resources == null) {
        return null;
    }//from  ww w  . j av a 2 s.  co m
    final Iterator<BackupResource> itr = resources.iterator();
    if (!itr.hasNext()) {
        log.debug("No resources provided, nothing to backup");
        return null;
    }
    BackupStatus status = setStatusIf(RunningBackup, Configured);
    if (status != RunningBackup) {
        return null;
    }
    final Calendar now = new GregorianCalendar();
    now.set(Calendar.MILLISECOND, 0);
    final String archiveName = String.format(ARCHIVE_NAME_FORMAT, now);
    final File archiveFile = new File(backupDir, archiveName);
    final String archiveKey = getArchiveKey(archiveName);
    log.info("Starting backup to archive {}", archiveName);
    log.trace("Backup archive: {}", archiveFile.getAbsolutePath());
    Backup backup = null;
    ZipOutputStream zos = null;
    try {
        zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(archiveFile)));
        while (itr.hasNext()) {
            BackupResource r = itr.next();
            log.debug("Backup up resource {} to archive {}", r.getBackupPath(), archiveName);
            zos.putNextEntry(new ZipEntry(r.getBackupPath()));
            FileCopyUtils.copy(r.getInputStream(), new FilterOutputStream(zos) {

                @Override
                public void close() throws IOException {
                    // FileCopyUtils closes the stream, which we don't want
                }

            });
        }
        zos.flush();
        zos.finish();
        log.info("Backup complete to archive {}", archiveName);
        backup = new SimpleBackup(now.getTime(), archiveKey, archiveFile.length(), true);

        // clean out older backups
        File[] backupFiles = getAvailableBackupFiles();
        if (backupFiles != null && backupFiles.length > additionalBackupCount + 1) {
            // delete older files
            for (int i = additionalBackupCount + 1; i < backupFiles.length; i++) {
                log.info("Deleting old backup archive {}", backupFiles[i].getName());
                if (!backupFiles[i].delete()) {
                    log.warn("Unable to delete backup archive {}", backupFiles[i].getAbsolutePath());
                }
            }
        }
    } catch (IOException e) {
        log.error("IO error creating backup: {}", e.getMessage());
        setStatus(Error);
    } catch (RuntimeException e) {
        log.error("Error creating backup: {}", e.getMessage());
        setStatus(Error);
    } finally {
        if (zos != null) {
            try {
                zos.close();
            } catch (IOException e) {
                // ignore this
            }
        }
        status = setStatusIf(Configured, RunningBackup);
        if (status != Configured) {
            // clean up if we encountered an error
            if (archiveFile.exists()) {
                archiveFile.delete();
            }
        }
    }
    return backup;
}

From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java

@Test
public void entriesFromTheGivenManifestShouldOverrideThoseInTheJars() throws IOException {
    String expected = "1.4";
    // Write the manifest, setting the implementation version
    Path tmp = folder.newFolder();

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), expected);
    Path manifestFile = tmp.resolve("manifest");
    try (OutputStream fos = Files.newOutputStream(manifestFile)) {
        manifest.write(fos);/* w  w w  .j  av  a 2s.  c o  m*/
    }

    // Write another manifest, setting the implementation version to something else
    manifest = new Manifest();
    manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), "1.0");

    Path input = tmp.resolve("input.jar");
    try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(input)) {
        ZipEntry entry = new ZipEntry("META-INF/MANIFEST.MF");
        out.putNextEntry(entry);
        manifest.write(out);
    }

    Path output = tmp.resolve("output.jar");
    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), output,
            ImmutableSortedSet.of(Paths.get("input.jar")), /* main class */ null, tmp.resolve("manifest"),
            /* merge manifest */ true, /* blacklist */ ImmutableSet.of());
    ExecutionContext context = TestExecutionContext.newInstance();
    assertEquals(0, step.execute(context).getExitCode());

    try (Zip zip = new Zip(output, false)) {
        byte[] rawManifest = zip.readFully("META-INF/MANIFEST.MF");
        manifest = new Manifest(new ByteArrayInputStream(rawManifest));
        String version = manifest.getMainAttributes().getValue(IMPLEMENTATION_VERSION);

        assertEquals(expected, version);
    }
}

From source file:mergedoc.core.MergeManager.java

/**
 * ????Java ???//w  w  w .j  av a 2s .  c om
 * API ???????????? ZIP
 * ??????
 *
 * @param  in  
 * @param  out ZIP 
 * @throws MergeDocException ??????
 * @throws SAXException SAX ????
 * @throws IOException ????
 */
private void merge(ArchiveInputStream in, ZipOutputStream out)
        throws MergeDocException, SAXException, IOException {
    Merger merger = new Merger(pref.getDocDirectory());
    merger.setDocEncoding(pref.getDocEncoding());

    ArchiveInputStream.Entry inEntry = null;
    while ((inEntry = in.getNextEntry()) != null) {

        if (workingState.isCanceled()) {
            return;
        }
        String entryName = inEntry.getName();
        out.putNextEntry(new ZipEntry(entryName));
        workingState.changeWorkingText(entryName);

        //debug ?
        //if (!entryName.equals("java/lang/String.java")) continue;
        //if (!entryName.endsWith("/SuppressWarnings.java")) continue;
        //if (!entryName.endsWith("/System.java")) continue;

        if (entryName.endsWith(".java") && !entryName.endsWith("/package-info.java")) {

            // Java ??
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            copyStream(in, baos);
            String source = baos.toString(pref.getInputEncoding());
            source = FastStringUtils.optimizeLineSeparator(source);
            source = FastStringUtils.untabify(source);

            // Java  API ?
            Pattern classPat = PatternCache.getPattern(".*/(.*)\\.java");
            Matcher classMat = classPat.matcher(entryName);
            if (classMat.find()) {
                String result = merger.merge(source, classMat.group(1));
                String className = merger.getMergedClassName();
                if (className != null) {
                    result = doFilter(className, result);
                }
                byte[] resultBuf = result.getBytes(pref.getOutputEncoding());
                out.write(resultBuf);
            } else {
                copyStream(in, out);
            }
        } else {
            // Java ??
            copyStream(in, out);
        }
    }
}

From source file:com.adobe.communities.ugc.migration.legacyProfileExport.MessagesExportServlet.java

private void exportMessagesBatch(final Iterable<Message> messages) throws JSONException, IOException {

    final JSONWriter writer = new JSONWriter(responseWriter);
    writer.setTidy(true);//from  w  w w  .  j  av  a2s.c  o m
    Boolean hasInitialized = false;
    for (final Message message : messages) {
        final Resource messageResource = message.adaptTo(Resource.class);
        if (exportedIds.containsKey(message.getId())) {
            if (!messagesForExport.containsKey(message.getId())) {
                continue; // already exported (for example, a message with two recipients, both checked, now looking
                // at the copy in the sender's outbox)
            }
            // we will always look at every message twice, since every message appears in an inbox and a sentitems
            // so, when we get here, we're looking at a message for the second time (or more, if the message has
            // multiple recipients). Our goal here is to fill in any missing recipient details, and, if this should
            // be the last time we look at a message, then write it to the output together with any attachments it
            // may have.
            final JSONObject messageObject = messagesForExport.get(message.getId());
            // check for an additional recipient
            boolean hasAllRecipients = true;
            final JSONObject recipientDetails = messageObject.getJSONObject("recipients");
            final Iterator<String> recipients = message.getRecipientIdList().listIterator();
            final String mailboxPath = messageResource.getPath();
            while (recipients.hasNext()) {
                final String recipient = recipients.next();
                if (!recipientDetails.has(recipient)) {
                    if (mailboxPath.contains(recipient)) {
                        final JSONObject recipientDetail = new JSONObject();
                        recipientDetail.put("read", message.isRead());
                        recipientDetail.put("deleted", message.isDeleted());
                        recipientDetails.put(recipient, recipientDetail);
                    } else {
                        hasAllRecipients = false;
                    }
                }
            }
            if (hasAllRecipients) {
                if (!hasInitialized) {
                    // we don't run this step unless at least one message is being written to a file
                    zip.putNextEntry(new ZipEntry("batch-" + counter + ".json"));
                    counter++;
                    writer.array();
                    hasInitialized = true;
                }
                // last time looking at a message, so write it to output together with any attachments
                writer.object();
                writeObject(writer, messageObject);
                final Resource attachments = messageResource.getChild("attachments");
                if (null != attachments) {
                    writer.key(ContentTypeDefinitions.LABEL_ATTACHMENTS);
                    final JSONWriter attachmentsWriter = writer.array();
                    for (final Resource attachment : attachments.getChildren()) {
                        UGCExportHelper.extractAttachment(responseWriter, attachmentsWriter.object(),
                                attachment);
                        attachmentsWriter.endObject();
                    }
                    attachmentsWriter.endArray();
                }
                writer.endObject();
                messagesForExport.remove(message.getId());
            }

            continue;
        }
        exportedIds.put(message.getId(), true);
        final JSONObject messageObject = new JSONObject();
        messageObject.put("content", URLEncoder.encode(message.getContent(), "UTF-8"));
        messageObject.put("subject", URLEncoder.encode(message.getSubject(), "UTF-8"));
        final Iterator<String> recipients = message.getRecipientIdList().listIterator();
        if (recipients.hasNext()) { //get each recipient and populate their "read" and "deleted" values
            final JSONObject recipientDetails = new JSONObject();
            final String mailboxPath = messageResource.getPath();
            while (recipients.hasNext()) {
                final String recipient = recipients.next();
                if (mailboxPath.contains(recipient)) {
                    final JSONObject recipientDetail = new JSONObject();
                    recipientDetail.put("read", message.isRead());
                    recipientDetail.put("deleted", message.isDeleted());
                    recipientDetails.put(recipient, recipientDetail);
                }
            }
            messageObject.put("recipients", recipientDetails);
        }
        final Calendar timestamp = message.getTimestamp();
        messageObject.put("added", timestamp.getTime().getTime());
        messageObject.put("senderId", URLEncoder.encode(message.getSenderId(), "UTF-8"));
        messagesForExport.put(message.getId(), messageObject);
    }
    if (hasInitialized) {
        writer.endArray();
        responseWriter.flush();
        zip.closeEntry();
    }
}

From source file:net.firejack.platform.core.utils.ArchiveUtils.java

private static void zipEntry(File file, ZipOutputStream out, String delPath) throws IOException {
    if (file.isFile()) {
        FileInputStream in = new FileInputStream(file);
        out.putNextEntry(new ZipEntry(file.getPath().replace(delPath + File.separator, "")));
        IOUtils.copy(in, out);//from www  .  j  a v a2s  . c  o m

        out.closeEntry();
        IOUtils.closeQuietly(in);
    } else {
        for (File f : file.listFiles())
            zipEntry(f, out, delPath);
    }
}

From source file:com.googlecode.clearnlp.component.AbstractStatisticalComponent.java

protected void saveDefaultConfiguration(ZipOutputStream zout, String entryName) throws Exception {
    zout.putNextEntry(new ZipEntry(entryName));
    PrintStream fout = UTOutput.createPrintBufferedStream(zout);
    LOG.info("Saving configuration.\n");

    fout.println(s_models.length);//from  w  ww.j  av  a  2  s .c o m

    fout.flush();
    zout.closeEntry();
}

From source file:com.edgenius.core.util.ZipFileUtil.java

private static void addEntry(ZipOutputStream zop, File entry, String entryName) throws IOException {
    if (StringUtils.isBlank(entryName))
        return;//from   www .j a v  a2 s  .c  o m

    BufferedInputStream source = null;
    if (entry != null) {
        source = new BufferedInputStream(new FileInputStream(entry));
    } else {
        //to make this as directory
        if (!entryName.endsWith("/"))
            entryName += "/";
    }
    ZipEntry zipEntry = new ZipEntry(entryName);
    zop.putNextEntry(zipEntry);

    if (entry != null) {
        //transfer bytes from file to ZIP file
        byte[] data = new byte[BUFFER_SIZE];
        int length;
        while ((length = source.read(data)) > 0) {
            zop.write(data, 0, length);
        }
        IOUtils.closeQuietly(source);
    }
    zop.closeEntry();

}

From source file:com.adobe.communities.ugc.migration.export.MessagesExportServlet.java

private void exportMessagesBatch(final Iterable<Message> messages) throws JSONException, IOException {

    final JSONWriter writer = new JSONWriter(responseWriter);
    writer.setTidy(true);//w  w w  . ja  v  a2  s.  c  o m
    Boolean hasInitialized = false;
    for (final Message message : messages) {
        final Resource messageResource = message.adaptTo(Resource.class);
        if (exportedIds.containsKey(message.getId())) {
            if (!messagesForExport.containsKey(message.getId())) {
                continue; // already exported (for example, a message with two recipients, both checked, now looking
                // at the copy in the sender's outbox)
            }
            // we will always look at every message twice, since every message appears in an inbox and a sentitems
            // so, when we get here, we're looking at a message for the second time (or more, if the message has
            // multiple recipients). Our goal here is to fill in any missing recipient details, and, if this should
            // be the last time we look at a message, then write it to the output together with any attachments it
            // may have.
            final JSONObject messageObject = messagesForExport.get(message.getId());
            // check for an additional recipient
            boolean hasAllRecipients = true;
            final JSONObject recipientDetails = messageObject.getJSONObject("recipients");
            final Iterator<String> recipients = message.getRecipientIdList().listIterator();
            final String mailboxPath = messageResource.getPath();
            while (recipients.hasNext()) {
                final String recipient = recipients.next();
                if (!recipientDetails.has(recipient)) {
                    if (mailboxPath.contains(recipient)) {
                        final JSONObject recipientDetail = new JSONObject();
                        recipientDetail.put("read", message.isRead());
                        recipientDetail.put("deleted", message.isDeleted());
                        recipientDetails.put(recipient, recipientDetail);
                    } else {
                        hasAllRecipients = false;
                    }
                }
            }
            if (hasAllRecipients) {
                if (!hasInitialized) {
                    // we don't run this step unless at least one message is being written to a file
                    zip.putNextEntry(new ZipEntry("batch-" + counter + ".json"));
                    counter++;
                    writer.array();
                    hasInitialized = true;
                }
                // last time looking at a message, so write it to output together with any attachments
                writer.object();
                writeObject(writer, messageObject);
                final ValueMap vm = messageResource.getValueMap();
                if (vm.containsKey(SocialUtils.PN_ATTACHMENT_LIST)) {
                    final Object attachments = vm.get(SocialUtils.PN_ATTACHMENT_LIST);
                    if (attachments instanceof String[] && ((String[]) attachments).length > 0) {
                        writer.key(ContentTypeDefinitions.LABEL_ATTACHMENTS);
                        final JSONWriter attachmentsWriter = writer.array();
                        for (final String attachment : (String[]) attachments) {
                            UGCExportHelper.extractAttachment(responseWriter, attachmentsWriter.object(),
                                    messageResource.getResourceResolver().getResource(attachment));
                            attachmentsWriter.endObject();
                        }
                        attachmentsWriter.endArray();
                    }
                }
                writer.endObject();
                messagesForExport.remove(message.getId());
            }

            continue;
        }
        exportedIds.put(message.getId(), true);
        final JSONObject messageObject = new JSONObject();
        messageObject.put("content", URLEncoder.encode(message.getContent(), "UTF-8"));
        messageObject.put("subject", URLEncoder.encode(message.getSubject(), "UTF-8"));
        final Iterator<String> recipients = message.getRecipientIdList().listIterator();
        if (recipients.hasNext()) { //get each recipient and populate their "read" and "deleted" values
            final JSONObject recipientDetails = new JSONObject();
            final String mailboxPath = messageResource.getPath();
            while (recipients.hasNext()) {
                final String recipient = recipients.next();
                if (mailboxPath.contains(recipient)) {
                    final JSONObject recipientDetail = new JSONObject();
                    recipientDetail.put("read", message.isRead());
                    recipientDetail.put("deleted", message.isDeleted());
                    recipientDetails.put(recipient, recipientDetail);
                }
            }
            messageObject.put("recipients", recipientDetails);
        }
        final Calendar timestamp = message.getTimestamp();
        messageObject.put("added", timestamp.getTime().getTime());
        messageObject.put("senderId", URLEncoder.encode(message.getSenderId(), "UTF-8"));
        messagesForExport.put(message.getId(), messageObject);
    }
    if (hasInitialized) {
        writer.endArray();
        responseWriter.flush();
        zip.closeEntry();
    }
}

From source file:com.replaymod.replaystudio.io.ReplayOutputStream.java

@Override
public void close() throws IOException {
    if (zipOut != null) {
        zipOut.closeEntry();/*w  w w  .j ava 2s .c  o  m*/

        metaData.setDuration(duration);
        zipOut.putNextEntry(new ZipEntry("metaData.json"));
        zipOut.write(GSON.toJson(metaData).getBytes());
        zipOut.closeEntry();
    }
    out.close();
}