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.castlemock.web.basis.web.mvc.controller.project.ProjectsOverviewController.java

/**
 * The method provides the functionality to update, delete and export projects. It bases the requested functionality based
 * on the provided action./*w w  w  .  j ava  2s .c o m*/
 * @param action The action is used to determined which action/functionality the perform.
 * @param projectModifierCommand The project overview command contains which ids going to be updated, deleted or exported.
 * @param response The HTTP servlet response
 * @return The model depending in which action was requested.
 */
@PreAuthorize("hasAuthority('READER') or hasAuthority('MODIFIER') or hasAuthority('ADMIN')")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView projectFunctionality(@RequestParam String action,
        @ModelAttribute ProjectModifierCommand projectModifierCommand, HttpServletResponse response) {
    LOGGER.debug("Project action requested: " + action);
    if (EXPORT_PROJECTS.equalsIgnoreCase(action)) {
        if (projectModifierCommand.getProjects().length == 0) {
            return redirect();
        }

        ZipOutputStream zipOutputStream = null;
        InputStream inputStream = null;
        final String outputFilename = tempFilesFolder + SLASH + "exported-projects-" + new Date().getTime()
                + ".zip";
        try {
            zipOutputStream = new ZipOutputStream(new FileOutputStream(outputFilename));
            for (String project : projectModifierCommand.getProjects()) {
                final String[] projectData = project.split(SLASH);
                if (projectData.length != 2) {
                    continue;
                }

                final String projectTypeUrl = projectData[0];
                final String projectId = projectData[1];
                final String exportedProject = projectServiceFacade.exportProject(projectTypeUrl, projectId);
                final byte[] data = exportedProject.getBytes();
                final String filename = "exported-project-" + projectTypeUrl + "-" + projectId + ".xml";
                zipOutputStream.putNextEntry(new ZipEntry(filename));
                zipOutputStream.write(data, 0, data.length);
                zipOutputStream.closeEntry();
            }
            zipOutputStream.close();

            inputStream = new FileInputStream(outputFilename);
            IOUtils.copy(inputStream, response.getOutputStream());

            response.setContentType("application/zip");
            response.flushBuffer();
            return null;
        } catch (IOException exception) {
            LOGGER.error("Unable to export multiple projects and zip them", exception);
        } finally {
            if (zipOutputStream != null) {
                try {
                    zipOutputStream.close();
                } catch (IOException exception) {
                    LOGGER.error("Unable to close the zip output stream", exception);
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException exception) {
                    LOGGER.error("Unable to close the input stream", exception);
                }
            }
            fileManager.deleteUploadedFile(outputFilename);
        }
    } else if (DELETE_PROJECTS.equalsIgnoreCase(action)) {
        List<ProjectDto> projects = new LinkedList<ProjectDto>();
        for (String project : projectModifierCommand.getProjects()) {
            final String[] projectData = project.split(SLASH);

            if (projectData.length != 2) {
                continue;
            }

            final String projectTypeUrl = projectData[0];
            final String projectId = projectData[1];
            final ProjectDto projectDto = projectServiceFacade.findOne(projectTypeUrl, projectId);
            projects.add(projectDto);
        }
        ModelAndView model = createPartialModelAndView(DELETE_PROJECTS_PAGE);
        model.addObject(PROJECTS, projects);
        model.addObject(DELETE_PROJECTS_COMMAND, new DeleteProjectsCommand());
        return model;
    }

    return redirect();
}

From source file:net.sourceforge.jweb.maven.mojo.PropertiesOverideMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (disabled) {
        this.getLog().info("plugin was disabled");
        return;// w w w . ja  va2s. com
    }
    processConfiguration();
    if (replacements.isEmpty()) {
        this.getLog().info("Nothing to replace with");
        return;
    }

    String name = this.builddir.getAbsolutePath() + File.separator + this.finalName + "." + this.packing;//the final package
    this.getLog().debug("final artifact: " + name);// the final package

    try {
        File finalWarFile = new File(name);
        File tempFile = File.createTempFile(finalWarFile.getName(), null);
        tempFile.delete();//check deletion
        boolean renameOk = finalWarFile.renameTo(tempFile);
        if (!renameOk) {
            getLog().error("Can not rename file, please check.");
            return;
        }

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile));
        ZipFile zipFile = new ZipFile(tempFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (acceptMime(entry)) {
                getLog().info("applying replacements for " + entry.getName());
                InputStream inputStream = zipFile.getInputStream(entry);
                String src = IOUtils.toString(inputStream, encoding);
                //do replacement
                for (Entry<String, String> e : replacements.entrySet()) {
                    src = src.replaceAll("#\\{" + e.getKey() + "}", e.getValue());
                }
                out.putNextEntry(new ZipEntry(entry.getName()));
                IOUtils.write(src, out, encoding);
                inputStream.close();
            } else {
                //not repalce, just put entry back to out zip
                out.putNextEntry(entry);
                InputStream inputStream = zipFile.getInputStream(entry);
                byte[] buf = new byte[512];
                int len = -1;
                while ((len = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                inputStream.close();
                continue;
            }
        }
        zipFile.close();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.h3xstream.findbugs.test.service.FindBugsLauncher.java

private void addFilesToStream(final ClassLoader cl, final JarOutputStream jar, final File dir,
        final String path) throws IOException {
    for (final File nextFile : dir.listFiles()) {
        if (nextFile.isFile()) {
            final String resource = path + nextFile.getName();
            jar.putNextEntry(new ZipEntry(resource));
            jar.write(IOUtils.toByteArray(cl.getResourceAsStream("metadata/" + resource)));
        } else {/* w  ww. java 2 s . com*/
            addFilesToStream(cl, jar, nextFile, path + nextFile.getName() + "/");
        }
    }
}

From source file:ServerJniTest.java

@Test
public void testDocumentRoot() throws Exception {
    File dir = null;// www  .  ja v a2s.com
    long handle = 0;
    try {
        dir = Files.createTempDir();
        // prepare data
        FileUtils.writeStringToFile(new File(dir, "test.txt"), STATIC_FILE_DATA);
        FileUtils.writeStringToFile(new File(dir, "foo.boo"), STATIC_FILE_DATA);
        File zipFile = new File(dir, "test.zip");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zipper = new ZipOutputStream(baos);
        zipper.putNextEntry(new ZipEntry("test/zipped.txt"));
        zipper.write(STATIC_ZIP_DATA.getBytes("UTF-8"));
        zipper.close();
        FileUtils.writeByteArrayToFile(zipFile, baos.toByteArray());
        String sout = wiltoncall("server_create", GSON.toJson(ImmutableMap.builder()
                .put("views", TestGateway.views()).put("tcpPort", TCP_PORT)
                .put("documentRoots",
                        ImmutableList.builder().add(ImmutableMap.builder().put("resource", "/static/files")
                                .put("dirPath", dir.getAbsolutePath())
                                .put("mimeTypes",
                                        ImmutableList.builder()
                                                .add(ImmutableMap.builder().put("extension", "boo")
                                                        .put("mime", "text/x-boo").build())
                                                .build())
                                .build())
                                .add(ImmutableMap.builder().put("resource", "/static")
                                        .put("zipPath", zipFile.getAbsolutePath())
                                        .put("zipInnerPrefix", "test/").build())
                                .build())
                .build()));
        Map<String, Long> shamap = GSON.fromJson(sout, LONG_MAP_TYPE);
        handle = shamap.get("serverHandle");
        assertEquals(HELLO_RESP, httpGet(ROOT_URL + "hello"));
        // deliberated repeated requests
        assertEquals(STATIC_FILE_DATA, httpGet(ROOT_URL + "static/files/test.txt"));
        assertEquals(STATIC_FILE_DATA, httpGet(ROOT_URL + "static/files/test.txt"));
        assertEquals(STATIC_FILE_DATA, httpGet(ROOT_URL + "static/files/test.txt"));
        assertEquals("text/plain", httpGetHeader(ROOT_URL + "static/files/test.txt", "Content-Type"));
        assertEquals(STATIC_FILE_DATA, httpGet(ROOT_URL + "static/files/foo.boo"));
        assertEquals("text/x-boo", httpGetHeader(ROOT_URL + "static/files/foo.boo", "Content-Type"));
        assertEquals(STATIC_ZIP_DATA, httpGet(ROOT_URL + "static/zipped.txt"));
        assertEquals(STATIC_ZIP_DATA, httpGet(ROOT_URL + "static/zipped.txt"));
        assertEquals(STATIC_ZIP_DATA, httpGet(ROOT_URL + "static/zipped.txt"));
    } finally {
        stopServerQuietly(handle);
        deleteDirQuietly(dir);
    }
}

From source file:ZipTransformTest.java

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

    File file1 = File.createTempFile("temp", null);
    File file2 = File.createTempFile("temp", null);
    try {/*from   w w w. java  2s  . c  o m*/
        // 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
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(file1);
            out = new FileOutputStream(file2);

            ZipUtil.transformEntry(in, 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();
                }
            }, out);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }

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

From source file:it.geosolutions.tools.compress.file.Compressor.java

/**
 * @param outputDir/*from   www . j  a  v a  2s. c o  m*/
 *            The directory where the zipfile will be created
 * @param zipFileBaseName
 *            The basename of hte zip file (i.e.: a .zip will be appended)
 * @param folder
 *            The folder that will be compressed
 * @return The created zipfile, or null if an error occurred.
 * @deprecated TODO UNTESTED
 */
public static File deflate(final File outputDir, final String zipFileBaseName, final File folder) {
    // Create a buffer for reading the files
    byte[] buf = new byte[4096];

    // Create the ZIP file
    final File outZipFile = new File(outputDir, zipFileBaseName + ".zip");
    if (outZipFile.exists()) {
        if (LOGGER.isInfoEnabled())
            LOGGER.info("The output file already exists: " + outZipFile);
        return outZipFile;
    }
    ZipOutputStream out = null;
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(outZipFile);
        bos = new BufferedOutputStream(fos);
        out = new ZipOutputStream(bos);
        Collector c = new Collector(null);
        List<File> files = c.collect(folder);
        // Compress the files
        for (File file : files) {
            FileInputStream in = null;
            try {
                in = new FileInputStream(file);
                if (file.isDirectory()) {
                    out.putNextEntry(new ZipEntry(Path.toRelativeFile(folder, file).getPath()));
                } else {
                    // Add ZIP entry to output stream.
                    out.putNextEntry(new ZipEntry(FilenameUtils.getBaseName(file.getName())));
                    // Transfer bytes from the file to the ZIP file
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                }

            } finally {
                try {
                    // Complete the entry
                    out.closeEntry();
                } catch (IOException e) {
                }
                IOUtils.closeQuietly(in);
            }

        }

    } catch (IOException e) {
        LOGGER.error(e.getLocalizedMessage(), e);
        return null;
    } finally {

        // Complete the ZIP file
        IOUtils.closeQuietly(bos);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(out);
    }

    return outZipFile;
}

From source file:ch.silviowangler.dox.export.DoxExporterImpl.java

private void writeToZipOutputStream(ZipOutputStream out, byte[] dataBytes, String path) throws IOException {
    logger.trace("Writing to ZIP output stream using path '{}' and data length '{}'", path, dataBytes.length);
    out.putNextEntry(new ZipEntry(path));
    out.write(dataBytes, 0, dataBytes.length);
    out.closeEntry(); // end of entry
}

From source file:com.joliciel.talismane.machineLearning.linearsvm.LinearSVMModel.java

@Override
public void writeDataToStream(ZipOutputStream zos) {
    try {/*from  ww  w  . j  ava  2 s . c  om*/
        zos.putNextEntry(new ZipEntry("featureIndexMap.obj"));
        ObjectOutputStream out = new ObjectOutputStream(zos);

        try {
            out.writeObject(featureIndexMap);
        } finally {
            out.flush();
        }

        zos.flush();

        zos.putNextEntry(new ZipEntry("outcomes.obj"));
        out = new ObjectOutputStream(zos);
        try {
            out.writeObject(outcomes);
        } finally {
            out.flush();
        }

        zos.flush();
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }

}

From source file:edu.harvard.med.screensaver.service.cherrypicks.CherryPickRequestPlateMapFilesBuilder.java

@SuppressWarnings("unchecked")
private void buildReadme(CherryPickRequest cherryPickRequest, ZipOutputStream zipOut) throws IOException {

    ZipEntry zipEntry = new ZipEntry(README_FILE_NAME);
    zipOut.putNextEntry(zipEntry);/*from  ww  w.ja  v  a 2s. c  o  m*/
    PrintWriter writer = new CustomNewlinePrintWriter(zipOut, NEWLINE);

    writer.println("This zip file contains plate mappings for Cherry Pick Request "
            + cherryPickRequest.getCherryPickRequestNumber());
    writer.println();

    {
        StringBuilder buf = new StringBuilder();
        for (CherryPickAssayPlate assayPlate : cherryPickRequest.getActiveCherryPickAssayPlates()) {
            buf.append(assayPlate.getName()).append("\t").append(assayPlate.getStatusLabel());
            if (assayPlate.isPlatedAndScreened()) {
                buf.append("\t(").append(assayPlate.getCherryPickScreenings().last().getDateOfActivity())
                        .append(" by ").append(assayPlate.getCherryPickScreenings().last().getPerformedBy()
                                .getFullNameFirstLast())
                        .append(')');
            } else if (assayPlate.isPlated()) {
                buf.append("\t(").append(assayPlate.getCherryPickLiquidTransfer().getDateOfActivity())
                        .append(" by ").append(assayPlate.getCherryPickLiquidTransfer().getPerformedBy()
                                .getFullNameFirstLast())
                        .append(')');
            }
            buf.append(NEWLINE);
        }
        if (buf.length() > 0) {
            writer.println("Cherry pick plates:");
            writer.print(buf.toString());
            writer.println();
        }
    }

    Map<CherryPickAssayPlate, Integer> platesRequiringReload = cherryPickRequestPlateMapper
            .getAssayPlatesRequiringSourcePlateReload(cherryPickRequest);
    if (platesRequiringReload.size() > 0) {
        writer.println("WARNING: Some cherry pick plates will be created from the same source plate!");
        writer.println(
                "You will need to reload one or more source plates for each of the following cherry pick plates:");
        for (CherryPickAssayPlate assayPlate : platesRequiringReload.keySet()) {
            writer.println("\tCherry pick plate '" + assayPlate.getName() + "' requires reload of source plate "
                    + platesRequiringReload.get(assayPlate));
        }
        writer.println();
    }

    {
        StringBuilder buf = new StringBuilder();
        MultiMap sourcePlateTypesForEachAssayPlate = getSourcePlateTypesForEachAssayPlate(cherryPickRequest);
        for (CherryPickAssayPlate assayPlate : cherryPickRequest.getActiveCherryPickAssayPlates()) {
            Set<PlateType> sourcePlateTypes = (Set<PlateType>) sourcePlateTypesForEachAssayPlate
                    .get(assayPlate.getName());
            if (sourcePlateTypes != null && sourcePlateTypes.size() > 1) {
                buf.append(assayPlate.getName()).append(NEWLINE);
            }
        }
        if (buf.length() > 0) {
            writer.println(
                    "WARNING: Some cherry pick plates will be created from multiple source plates of non-uniform plate types!");
            writer.println("The following cherry pick plates are specified across multiple files:");
            writer.print(buf.toString());
            writer.println();
        }
    }

    writer.flush();
}

From source file:com.asual.summer.bundle.BundleDescriptorMojo.java

private void zip(File directory, File base, ZipOutputStream zos) throws IOException {
    File[] files = directory.listFiles();
    byte[] buffer = new byte[8192];
    int read = 0;
    for (int i = 0, n = files.length; i < n; i++) {
        String name = files[i].getPath().replace(File.separatorChar, '/')
                .substring(base.getPath().length() + 1);
        if (files[i].isDirectory()) {
            if (!name.endsWith("/")) {
                name = name + "/";
            }//from  w ww  . j a  va  2  s . c  o  m
            ZipEntry entry = new ZipEntry(name);
            zos.putNextEntry(entry);
            zip(files[i], base, zos);
        } else {
            FileInputStream in = new FileInputStream(files[i]);
            ZipEntry entry = new ZipEntry(name);
            zos.putNextEntry(entry);
            while (-1 != (read = in.read(buffer))) {
                zos.write(buffer, 0, read);
            }
            in.close();
        }
    }
}