Example usage for java.util.zip ZipOutputStream close

List of usage examples for java.util.zip ZipOutputStream close

Introduction

In this page you can find the example usage for java.util.zip ZipOutputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP output stream as well as the stream being filtered.

Usage

From source file:com.clustercontrol.collect.util.ZipCompresser.java

/**
 * ?????1????//from  w  w w  . j  a v a  2 s  .c  o  m
 * 
 * @param inputFileNameList ??
 * @param outputFileName ?
 * 
 * @return ???
 */
protected static synchronized void archive(ArrayList<String> inputFileNameList, String outputFileName)
        throws HinemosUnknown {
    m_log.debug("archive() output file = " + outputFileName);

    byte[] buf = new byte[128];
    BufferedInputStream in = null;
    ZipEntry entry = null;
    ZipOutputStream out = null;

    // ?
    if (outputFileName == null || "".equals(outputFileName)) {
        HinemosUnknown e = new HinemosUnknown("archive output fileName is null ");
        m_log.info("archive() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;
    }
    File zipFile = new File(outputFileName);
    if (zipFile.exists()) {
        if (zipFile.isFile() && zipFile.canWrite()) {
            m_log.debug("archive() output file = " + outputFileName
                    + " is exists & file & writable. initialize file(delete)");
            if (!zipFile.delete())
                m_log.debug("Fail to delete " + zipFile.getAbsolutePath());
        } else {
            HinemosUnknown e = new HinemosUnknown("archive output fileName is directory or not writable ");
            m_log.info("archive() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
            throw e;
        }
    }

    // ?
    try {
        // ????
        out = new ZipOutputStream(new FileOutputStream(outputFileName));

        for (String inputFileName : inputFileNameList) {
            m_log.debug("archive() input file name = " + inputFileName);

            // ????
            in = new BufferedInputStream(new FileInputStream(inputFileName));

            // ??
            String fileName = (new File(inputFileName)).getName();
            m_log.debug("archive() entry file name = " + fileName);
            entry = new ZipEntry(fileName);

            out.putNextEntry(entry);
            // ????
            int size;
            while ((size = in.read(buf, 0, buf.length)) != -1) {
                out.write(buf, 0, size);
            }
            // ??
            out.closeEntry();
            in.close();
        }
        // ? out.flush();
        out.close();

    } catch (IOException e) {
        m_log.warn("archive() archive error : " + outputFileName + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
        throw new HinemosUnknown("archive error " + outputFileName, e);

    } finally {

        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:de.unisaarland.swan.export.ExportUtil.java

/**
 * Returns a zip file containing all annotation and link data by annotator
 * and document belonging to the given project: creates one XML file per
 * annotator./*from  ww w  .  j  a  va 2s  . c  o  m*/
 *
 * @param proj Project
 * @return zip file
 */
public File getExportDataInXML(Project proj) {
    try {
        File zipFile = new File("swan_" + proj.getName() + ".zip");
        ZipOutputStream zos = createZipOutputStream(zipFile);

        for (de.unisaarland.swan.entities.Document d : proj.getDocuments()) {
            for (Users u : proj.getUsers()) {

                String fileName = proj.getName() + "_" + d.getName() + "_" + u.getEmail() + ".xml";
                File docUserfile = new File(fileName);

                List<de.unisaarland.swan.entities.Annotation> annotations = annotationDAO
                        .getAllAnnotationsByUserIdDocId(u.getId(), d.getId());
                List<de.unisaarland.swan.entities.Link> links = linkDAO.getAllLinksByUserIdDocId(u.getId(),
                        d.getId());
                Document exportDoc = convertToExportDocument(d, annotations, links);

                marshalXMLToSingleFile(exportDoc, docUserfile);
                createZipEntry(docUserfile, zos);
            }
        }

        // Insert scheme
        marshalScheme(proj, zos);

        zos.close();

        return zipFile;
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ExportUtil.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ExportUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    throw new RuntimeException("ExportUtil: Error while zipping data to XML");
}

From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java

@Override
public String getDHIS2APIBackupPath() {
    String zipFile = null;// www  . j  a v  a 2 s.  com
    String sourceDirectory = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_DHIS2BACKUP_FOLDER
            + File.separator;
    String tempFolderName = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_TEMP_FOLDER
            + File.separator;
    File temp = new File(tempFolderName);

    if (!temp.exists()) {
        temp.mkdirs();
    }
    zipFile = tempFolderName + "exported-dhis2APIBackup_" + (new Date()).getTime() + ".zip";

    File dirObj = new File(sourceDirectory);
    ZipOutputStream out;
    try {
        out = new ZipOutputStream(new FileOutputStream(zipFile));

        System.out.println("Creating : " + zipFile);
        addDHIS2APIDirectories(dirObj, out, sourceDirectory);
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return zipFile;
}

From source file:fr.fastconnect.factory.tibco.bw.fcunit.PrepareTestMojo.java

private void removeFileInZipContaining(List<String> contentFilter, File zipFile)
        throws ZipException, IOException {
    ZipScanner zs = new ZipScanner();
    zs.setSrc(zipFile);/*from ww  w. ja  va2s  .  c o  m*/
    String[] includes = { "**/*.process" };
    zs.setIncludes(includes);
    //zs.setCaseSensitive(true);
    zs.init();
    zs.scan();

    File originalProjlib = zipFile; // to be overwritten
    File tmpProjlib = new File(zipFile.getAbsolutePath() + ".tmp"); // to read
    FileUtils.copyFile(originalProjlib, tmpProjlib);

    ZipFile listZipFile = new ZipFile(tmpProjlib);
    ZipInputStream readZipFile = new ZipInputStream(new FileInputStream(tmpProjlib));
    ZipOutputStream writeZipFile = new ZipOutputStream(new FileOutputStream(originalProjlib));

    ZipEntry zipEntry;
    boolean keep;
    while ((zipEntry = readZipFile.getNextEntry()) != null) {
        keep = true;
        for (String filter : contentFilter) {
            keep = keep && !containsString(filter, listZipFile.getInputStream(zipEntry));
        }
        //         if (!containsString("<pd:type>com.tibco.pe.core.OnStartupEventSource</pd:type>", listZipFile.getInputStream(zipEntry))
        //          && !containsString("<pd:type>com.tibco.plugin.jms.JMSTopicEventSource</pd:type>", listZipFile.getInputStream(zipEntry))) {
        if (keep) {
            writeZipFile.putNextEntry(zipEntry);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = readZipFile.read(buf)) >= 0) {
                writeZipFile.write(buf, 0, len);
            }
            writeZipFile.closeEntry();
            //getLog().info("written");
        } else {
            getLog().info("removed " + zipEntry.getName());
        }

    }

    writeZipFile.close();
    readZipFile.close();
    listZipFile.close();

    originalProjlib.setLastModified(originalProjlib.lastModified() - 100000);
}

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. ja  v  a  2s . c om*/
 * @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:com.pari.nm.utils.backup.BackupRestore.java

public boolean zipFolder(File backupDir, File backupZipFile) {
    FileOutputStream fileWriter = null;
    ZipOutputStream zip = null;
    try {//from w  w  w  .  ja v a  2 s .co m
        fileWriter = new FileOutputStream(backupZipFile);
        zip = new ZipOutputStream(fileWriter);
        addFolderToZip("", backupDir, zip);
        zip.flush();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (zip != null) {
                zip.close();
            }
        } catch (IOException ignore) {
        }
        try {
            if (fileWriter != null) {
                fileWriter.close();
            }
        } catch (IOException ignore) {
        }
    }
    return true;
}

From source file:fr.univrouen.poste.services.ZipService.java

public void writeZip(List<PosteCandidature> posteCandidatures, OutputStream destStream)
        throws IOException, SQLException {

    ZipOutputStream out = new ZipOutputStream(destStream);

    for (PosteCandidature posteCandidature : posteCandidatures) {
        String folderName = posteCandidature.getPoste().getNumEmploi().concat("/");
        folderName = folderName.concat(posteCandidature.getCandidat().getNom().concat("-"));
        folderName = folderName.concat(posteCandidature.getCandidat().getPrenom().concat("-"));
        folderName = folderName.concat(posteCandidature.getCandidat().getNumCandidat().concat("/"));
        for (PosteCandidatureFile posteCandidatureFile : posteCandidature.getCandidatureFiles()) {
            String fileName = posteCandidatureFile.getId().toString().concat("-")
                    .concat(posteCandidatureFile.getFilename());
            String folderFileName = folderName.concat(fileName);
            out.putNextEntry(new ZipEntry(folderFileName));
            InputStream inputStream = posteCandidatureFile.getBigFile().getBinaryFile().getBinaryStream();
            BufferedInputStream bufInputStream = new BufferedInputStream(inputStream, BUFFER);
            byte[] bytes = new byte[BUFFER];
            int length;
            while ((length = bufInputStream.read(bytes)) >= 0) {
                out.write(bytes, 0, length);
            }//  w  w w .  j  a v a 2s.c o  m
            out.closeEntry();
        }
    }
    out.close();
}

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./*from  w w w .java2 s  . 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:it.geosolutions.mariss.wps.ppio.OutputResourcesPPIO.java

@Override
public void encode(Object value, OutputStream os) throws Exception {

    ZipOutputStream zos = null;
    try {/*from ww w .  j a  va2  s.c om*/
        OutputResource or = (OutputResource) value;

        zos = new ZipOutputStream(os);
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setLevel(Deflater.DEFAULT_COMPRESSION);

        Iterator<File> iter = or.getDeletableResourcesIterator();
        while (iter.hasNext()) {

            File tmp = iter.next();
            if (!tmp.exists() || !tmp.canRead() || !tmp.canWrite()) {
                LOGGER.warning("Skip Deletable file '" + tmp.getName() + "' some problems occurred...");
                continue;
            }

            addToZip(tmp, zos);

            if (!tmp.delete()) {
                LOGGER.warning("File '" + tmp.getName() + "' cannot be deleted...");
            }
        }
        iter = null;

        Iterator<File> iter2 = or.getUndeletableResourcesIterator();
        while (iter2.hasNext()) {

            File tmp = iter2.next();
            if (!tmp.exists() || !tmp.canRead()) {
                LOGGER.warning("Skip Undeletable file '" + tmp.getName() + "' some problems occurred...");
                continue;
            }

            addToZip(tmp, zos);

        }
    } finally {
        try {
            zos.close();
        } catch (IOException e) {
            LOGGER.severe(e.getMessage());
        }
    }
}

From source file:br.org.indt.ndg.client.Service.java

private void zipSurvey(String surveyId, byte[] fileContent, String fileType) {
    final String SURVEY = "survey";
    FileOutputStream arqExport;/*from w  ww  .j  ava 2s  .  c o  m*/
    try {
        if (fileType.equals(XLS)) {
            arqExport = new FileOutputStream(surveyId + File.separator + SURVEY + surveyId + XLS);
            arqExport.write(fileContent);
            arqExport.close();
        } else if (fileType.equals(CSV)) {
            arqExport = new FileOutputStream(surveyId + File.separator + SURVEY + surveyId + CSV);
            arqExport.write(fileContent);
            arqExport.close();
        }

        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(SURVEY + surveyId + ZIP));

        zipDir(surveyId, zos);

        zos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}