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:ZipUtilInPlaceTest.java

public void testByteArrayTransformer() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File file1 = File.createTempFile("temp", null);
    try {/*from   www  .j  a  v a 2 s.  c om*/
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file1));
        try {
            zos.putNextEntry(new ZipEntry(name));
            zos.write(contents);
            zos.closeEntry();
        } finally {
            IOUtils.closeQuietly(zos);
        }

        // Transform the ZIP file
        ZipUtil.transformEntry(file1, name, new ByteArrayZipEntryTransformer() {
            protected byte[] transform(ZipEntry zipEntry, byte[] input) throws IOException {
                String s = new String(input);
                assertEquals(new String(contents), s);
                return s.toUpperCase().getBytes();
            }
        });

        // Test the ZipUtil
        byte[] actual = ZipUtil.unpackEntry(file1, name);
        assertNotNull(actual);
        assertEquals(new String(contents).toUpperCase(), new String(actual));
    } finally {
        FileUtils.deleteQuietly(file1);
    }
}

From source file:edu.umd.cs.marmoset.modelClasses.ZipFileAggregator.java

private void addFileFromInputStream(String dirName, long time, InputStream inputStream) throws IOException {
    // Prepend directory name
    String name = dirName + "/nonzipfile";

    // Create output entry
    ZipEntry outputEntry = new ZipEntry(name);
    if (time > 0L)
        outputEntry.setTime(time); // only add valid times
    zipOutput.putNextEntry(outputEntry);

    // Copy zip input to output
    CopyUtils.copy(inputStream, zipOutput);

    zipOutput.closeEntry();/*from   www .  ja v a2 s  . com*/
}

From source file:com.thruzero.common.core.fs.walker.visitor.ZipCompressingVisitor.java

/**
 * Add the given directory path to the target zip archive (no files are copied, just the relative directory path is
 * added).//from  ww  w . j  a  v  a  2 s. com
 */
@Override
public void visitDirectoryEnter(final File directory) throws IOException {
    String relativePath = getRelativePath(directory);

    if (StringUtils.isNotEmpty(relativePath)) {
        if (!relativePath.endsWith(EnvironmentHelper.FILE_PATH_SEPARATOR)) {
            relativePath += EnvironmentHelper.FILE_PATH_SEPARATOR;
        }

        logHelper.logAddDirectory(relativePath);

        ZipEntry zipEntry = new ZipEntry(relativePath);
        zipOut.putNextEntry(zipEntry);
        zipOut.flush();
        zipOut.closeEntry();

        getStatus().incNumProcessed();
    }
}

From source file:Zip.java

/**
 * Create a Writer on a given file, transparently compressing the data to a
 * Zip file whose name is the provided file path, with a ".zip" extension
 * added.//  w w  w.  ja va 2s .com
 *
 * @param file the file (with no zip extension)
 *
 * @return a writer on the zip entry
 */
public static Writer createWriter(File file) {
    try {
        String path = file.getCanonicalPath();
        FileOutputStream fos = new FileOutputStream(path + ".zip");
        ZipOutputStream zos = new ZipOutputStream(fos);
        ZipEntry ze = new ZipEntry(file.getName());
        zos.putNextEntry(ze);

        return new OutputStreamWriter(zos);
    } catch (FileNotFoundException ex) {
        System.err.println(ex.toString());
        System.err.println(file + " not found");
    } catch (Exception ex) {
        System.err.println(ex.toString());
    }

    return null;
}

From source file:com.samczsun.helios.tasks.DecompileAndSaveTask.java

@Override
public void run() {
    File file = FileChooserUtil.chooseSaveLocation(Settings.LAST_DIRECTORY.get().asString(),
            Arrays.asList("zip"));
    if (file == null)
        return;/*from  www  .j  a  v a2 s . c  om*/
    if (file.exists()) {
        boolean delete = SWTUtil.promptForYesNo(Constants.REPO_NAME + " - Overwrite existing file",
                "The selected file already exists. Overwrite?");
        if (!delete) {
            return;
        }
    }

    AtomicReference<Transformer> transformer = new AtomicReference<>();

    Display display = Display.getDefault();
    display.syncExec(() -> {
        Shell shell = new Shell(Display.getDefault());
        Combo combo = new Combo(shell, SWT.DROP_DOWN | SWT.BORDER);
        List<Transformer> transformers = new ArrayList<>();
        transformers.addAll(Decompiler.getAllDecompilers());
        transformers.addAll(Disassembler.getAllDisassemblers());
        for (Transformer t : transformers) {
            combo.add(t.getName());
        }
        shell.pack();
        shell.open();
        System.out.println(Arrays.toString(combo.getItems()));
    });

    // TODO: Ask for list of decompilers

    FileOutputStream fileOutputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {
        fileOutputStream = new FileOutputStream(file);
        zipOutputStream = new ZipOutputStream(fileOutputStream);
        for (Pair<String, String> pair : data) {
            StringBuilder buffer = new StringBuilder();
            LoadedFile loadedFile = Helios.getLoadedFile(pair.getValue0());
            if (loadedFile != null) {
                String innerName = pair.getValue1();
                byte[] bytes = loadedFile.getData().get(innerName);
                if (bytes != null) {
                    Decompiler.getById("cfr-decompiler").decompile(null, bytes, buffer);
                    zipOutputStream.putNextEntry(
                            new ZipEntry(innerName.substring(0, innerName.length() - 6) + ".java"));
                    zipOutputStream.write(buffer.toString().getBytes(StandardCharsets.UTF_8));
                    zipOutputStream.closeEntry();
                }
            }
        }
    } catch (Exception e) {
        ExceptionHandler.handle(e);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
        IOUtils.closeQuietly(fileOutputStream);
    }
}

From source file:de.mpg.imeji.logic.export.format.ZIPExport.java

/**
 * This method exports all images of the current browse page as a zip file
 * //from www.  j  a  v  a2 s  . c o  m
 * @throws Exception
 * @throws URISyntaxException
 */
public void exportAllImages(SearchResult sr, OutputStream out) throws URISyntaxException, Exception {
    List<String> source = sr.getResults();
    ZipOutputStream zip = new ZipOutputStream(out);
    try {
        // Create the ZIP file
        for (int i = 0; i < source.size(); i++) {
            SessionBean session = (SessionBean) BeanHelper.getSessionBean(SessionBean.class);
            ItemController ic = new ItemController(session.getUser());
            Item item = ic.retrieve(new URI(source.get(i)));
            StorageController sc = new StorageController();
            try {
                zip.putNextEntry(new ZipEntry(item.getFilename()));
                sc.read(item.getFullImageUrl().toString(), zip, false);
                // Complete the entry
                zip.closeEntry();
            } catch (ZipException ze) {
                if (ze.getMessage().contains("duplicate entry")) {
                    String name = i + "_" + item.getFilename();
                    zip.putNextEntry(new ZipEntry(name));
                    sc.read(item.getFullImageUrl().toString(), zip, false);
                    // Complete the entry
                    zip.closeEntry();
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // Complete the ZIP file
        zip.close();
    }
}

From source file:be.neutrinet.ispng.vpn.api.VPNClientConfig.java

@Post
public Representation getConfig(Map<String, String> data) {
    try {/*from  ww w.j  a va 2  s. c  om*/
        if (!getRequestAttributes().containsKey("client"))
            return clientError("MALFORMED_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST);

        Client client = Clients.dao.queryForId(getAttribute("client"));
        if (!Policy.get().canAccess(getSessionToken().get().getUser(), client)) {
            return clientError("FORBIDDEN", Status.CLIENT_ERROR_BAD_REQUEST);
        }

        ArrayList<String> config = new ArrayList<>();
        config.addAll(Arrays.asList(DEFAULTS));

        // create zip
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(baos);

        List<Certificate> userCert = Certificates.dao.queryForEq("client_id", client.id).stream()
                .filter(Certificate::valid).collect(Collectors.toList());

        if (!userCert.isEmpty()) {
            byte[] raw = userCert.get(0).getRaw();
            zip.putNextEntry(new ZipEntry("client.crt"));
            zip.write(raw);
            zip.putNextEntry(new ZipEntry("README"));
            zip.write(("!! You are using your own keypair. Please make sure to adjust the "
                    + "path to your private key in the config file or move the private key"
                    + " here and name it client.key").getBytes());
            config.add("cert client.crt");
            config.add("key client.key");
        } else if (client.user.certId != null && !client.user.certId.isEmpty()) {
            Representation res = addPKCS11config(data.get("platform").toLowerCase(), config, client.user);
            if (res != null)
                return res;
        }

        if (client.user.certId == null || client.user.certId.isEmpty()) {
            zip.putNextEntry(new ZipEntry("NO_KEYPAIR_DEFINED"));
            zip.write("Invalid state, no keypair has been defined.".getBytes());
        }

        return finalizeZip(config, zip, baos);
    } catch (Exception ex) {
        Logger.getLogger(getClass()).error("Failed to generate config file archive", ex);
    }

    return DEFAULT_ERROR;
}

From source file:com.android.build.gradle.internal.transforms.ExtractJarsTransformTest.java

@Test
public void checkNoWarningWhenWillNotHaveIssuesOnCaseSensitiveFileSystems() throws Exception {
    File jar = temporaryFolder.newFile("Jar without case issues.jar");
    try (JarOutputStream jarOutputStream = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(jar)))) {
        jarOutputStream.putNextEntry(new ZipEntry("com/example/a.class"));
        jarOutputStream.closeEntry();//  w  w  w.  j  a v  a 2  s  . c  o m
        jarOutputStream.putNextEntry(new ZipEntry("com/example/B.class"));
        jarOutputStream.closeEntry();
    }
    checkWarningForCaseIssues(jar, false /*expectingWarning*/);
}

From source file:com.asual.summer.onejar.OneJarMojo.java

public void execute() throws MojoExecutionException {

    JarOutputStream out = null;/* w ww  .ja v  a2s  . co m*/
    JarInputStream in = null;

    try {

        File jarFile = new File(buildDirectory, jarName);
        File warFile = new File(buildDirectory, warName);

        Manifest manifest = new Manifest(new ByteArrayInputStream("Manifest-Version: 1.0\n".getBytes("UTF-8")));
        manifest.getMainAttributes().putValue("Main-Class", JAR_MAIN_CLASS);
        manifest.getMainAttributes().putValue("One-Jar-Main-Class", ONE_JAR_MAIN_CLASS);

        out = new JarOutputStream(new FileOutputStream(jarFile, false), manifest);
        in = new JarInputStream(getClass().getClassLoader().getResourceAsStream(ONE_JAR_DIST));

        putEntry(out, new FileInputStream(warFile), new ZipEntry(JAR_CLASSPATH + warFile.getName()));

        for (Artifact artifact : pluginArtifacts) {
            if (artifact.getArtifactId().equalsIgnoreCase("summer-onejar")) {
                artifact.updateVersion(artifact.getVersion(), localRepository);
                putEntry(out, new FileInputStream(artifact.getFile()),
                        new ZipEntry(JAR_CLASSPATH + artifact.getFile().getName()));
                MavenProject project = mavenProjectBuilder.buildFromRepository(artifact,
                        remoteArtifactRepositories, localRepository);
                List<Dependency> dependencies = project.getDependencies();
                for (Dependency dependency : dependencies) {
                    if (!"provided".equals(dependency.getScope())) {
                        Artifact dependencyArtifact = artifactFactory.createArtifact(dependency.getGroupId(),
                                dependency.getArtifactId(), dependency.getVersion(), dependency.getScope(),
                                dependency.getType());
                        dependencyArtifact.updateVersion(dependencyArtifact.getVersion(), localRepository);
                        putEntry(out, new FileInputStream(dependencyArtifact.getFile()),
                                new ZipEntry(JAR_CLASSPATH + dependencyArtifact.getFile().getName()));
                    }
                }
            }
        }

        while (true) {
            ZipEntry entry = in.getNextEntry();
            if (entry != null) {
                putEntry(out, in, entry);
            } else {
                break;
            }
        }

        projectHelper.attachArtifact(project, "jar", jarFile);

    } catch (Exception e) {
        getLog().error(e.getMessage(), e);
        throw new MojoExecutionException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
    }
}

From source file:com.amalto.core.storage.hibernate.TypeMapping.java

private static Object _serializeValue(Object value, FieldMetadata sourceField, FieldMetadata targetField,
        Session session) {//www. j a  va2 s  . c o  m
    if (targetField == null) {
        return value;
    }
    if (!targetField.isMany()) {
        Boolean targetZipped = targetField.<Boolean>getData(MetadataRepository.DATA_ZIPPED);
        Boolean sourceZipped = sourceField.<Boolean>getData(MetadataRepository.DATA_ZIPPED);
        if (sourceZipped == null && Boolean.TRUE.equals(targetZipped)) {
            try {
                ByteArrayOutputStream characters = new ByteArrayOutputStream();
                OutputStream bos = new Base64OutputStream(characters);
                ZipOutputStream zos = new ZipOutputStream(bos);
                ZipEntry zipEntry = new ZipEntry("content"); //$NON-NLS-1$
                zos.putNextEntry(zipEntry);
                zos.write(String.valueOf(value).getBytes("UTF-8")); //$NON-NLS-1$
                zos.closeEntry();
                zos.flush();
                zos.close();
                return new String(characters.toByteArray());
            } catch (IOException e) {
                throw new RuntimeException("Unexpected compression exception", e); //$NON-NLS-1$
            }
        }
        String targetSQLType = targetField.getType().getData(TypeMapping.SQL_TYPE);
        if (targetSQLType != null && SQL_TYPE_CLOB.equals(targetSQLType)) {
            if (value != null) {
                return Hibernate.getLobCreator(session).createClob(String.valueOf(value));
            } else {
                return null;
            }
        }
    }
    return value;
}