Example usage for java.util.zip ZipOutputStream ZipOutputStream

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

Introduction

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

Prototype

public ZipOutputStream(OutputStream out) 

Source Link

Document

Creates a new ZIP output stream.

Usage

From source file:de.unikassel.puma.openaccess.sword.SwordService.java

/**
 * collects all informations to send Documents with metadata to repository 
 * @throws SwordException //from  www. j  a  v a 2 s .c o  m
 */
public void submitDocument(PumaData<?> pumaData, User user) throws SwordException {
    log.info("starting sword");
    DepositResponse depositResponse = new DepositResponse(999);
    File swordZipFile = null;

    Post<?> post = pumaData.getPost();

    // -------------------------------------------------------------------------------
    /*
     * retrieve ZIP-FILE
     */
    if (post.getResource() instanceof BibTex) {

        // fileprefix
        String fileID = HashUtils.getMD5Hash(user.getName().getBytes()) + "_"
                + post.getResource().getIntraHash();

        // Destination directory 
        File destinationDirectory = new File(repositoryConfig.getDirTemp() + "/" + fileID);

        // zip-filename
        swordZipFile = new File(destinationDirectory.getAbsoluteFile() + "/" + fileID + ".zip");

        byte[] buffer = new byte[18024];

        log.info("getIntraHash = " + post.getResource().getIntraHash());

        /*
         * get documents
         */

        // At the moment, there are no Documents delivered by method parameter post.
        // retrieve list of documents from database - workaround

        // get documents for post and insert documents into post 
        ((BibTex) post.getResource())
                .setDocuments(retrieveDocumentsFromDatabase(user, post.getResource().getIntraHash()));

        if (((BibTex) post.getResource()).getDocuments().isEmpty()) {
            // Wenn kein PDF da, dann Fehlermeldung ausgeben!!
            log.info("throw SwordException: noPDFattached");
            throw new SwordException("error.sword.noPDFattached");
        }

        try {
            // create directory
            boolean mkdir_success = (new File(destinationDirectory.getAbsolutePath())).mkdir();
            if (mkdir_success) {
                log.info("Directory: " + destinationDirectory.getAbsolutePath() + " created");
            }

            // open zip archive to add files to
            log.info("zipFilename: " + swordZipFile);
            ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(swordZipFile));

            ArrayList<String> fileList = new ArrayList<String>();

            for (final Document document : ((BibTex) post.getResource()).getDocuments()) {

                //getpostdetails
                // get file and store it in hard coded folder "/tmp/"
                //final Document document2 = logic.getDocument(user.getName(), post.getResource().getIntraHash(), document.getFileName());

                // move file to user folder with username_resource-hash as folder name

                // File (or directory) to be copied 
                //File fileToZip = new File(document.getFileHash());

                fileList.add(document.getFileName());

                // Move file to new directory 
                //boolean rename_success = fileToCopy.renameTo(new File(destinationDirectory, fileToMove.getName()));
                /*
                if (!rename_success) { 
                   // File was not successfully moved } 
                   log.info("File was not successfully moved: "+fileToMove.getName());
                }
                */
                ZipEntry zipEntry = new ZipEntry(document.getFileName());

                // Set the compression ratio
                zipOutputStream.setLevel(Deflater.DEFAULT_COMPRESSION);

                String inputFilePath = projectDocumentPath + document.getFileHash().substring(0, 2) + "/"
                        + document.getFileHash();
                FileInputStream in = new FileInputStream(inputFilePath);

                // Add ZIP entry to output stream.
                zipOutputStream.putNextEntry(zipEntry);

                // Transfer bytes from the current file to the ZIP file
                //out.write(buffer, 0, in.read(buffer));

                int len;
                while ((len = in.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, len);
                }

                zipOutputStream.closeEntry();

                // Close the current file input stream
                in.close();
            }

            // write meta data into zip archive
            ZipEntry zipEntry = new ZipEntry("mets.xml");
            zipOutputStream.putNextEntry(zipEntry);

            // create XML-Document
            // PrintWriter from a Servlet

            MetsBibTexMLGenerator metsBibTexMLGenerator = new MetsBibTexMLGenerator(urlRenderer);
            metsBibTexMLGenerator.setUser(user);
            metsBibTexMLGenerator.setFilenameList(fileList);
            //metsGenerator.setMetadata(metadataMap);
            metsBibTexMLGenerator.setMetadata((PumaData<BibTex>) pumaData);

            //            PumaPost additionalMetadata = new PumaPost();
            //            additionalMetadata.setExaminstitution(null);
            //            additionalMetadata.setAdditionaltitle(null);
            //            additionalMetadata.setExamreferee(null);
            //            additionalMetadata.setPhdoralexam(null);
            //            additionalMetadata.setSponsors(null);
            //            additionalMetadata.setAdditionaltitle(null);   

            //            metsBibTexMLGenerator.setMetadata((Post<BibTex>) post);

            //StreamResult streamResult = new StreamResult(zipOutputStream);

            zipOutputStream.write(metsBibTexMLGenerator.generateMets().getBytes("UTF-8"));

            zipOutputStream.closeEntry();

            // close zip archive  
            zipOutputStream.close();

            log.debug("saved to " + swordZipFile.getPath());

        } catch (MalformedURLException e) {
            // e.printStackTrace();
            log.info("MalformedURLException! " + e.getMessage());
        } catch (IOException e) {
            //e.printStackTrace();
            log.info("IOException! " + e.getMessage());

        } catch (ResourceNotFoundException e) {
            // e.printStackTrace();
            log.warn("ResourceNotFoundException! SwordService-retrievePost");
        }
    }
    /*
     * end of retrieve ZIP-FILE
     */
    //---------------------------------------------------

    /*
     * do the SWORD stuff
     */

    if (null != swordZipFile) {

        // get an instance of SWORD-Client
        Client swordClient = new Client();

        PostMessage swordMessage = new PostMessage();

        // create sword post message

        // message file
        // create directory in temp-folder
        // store post documents there
        // store meta data there in format http://purl.org/net/sword-types/METSDSpaceSIP
        // delete post document files and meta data file

        // add files to zip archive
        // -- send zip archive
        // -- delete zip archive

        swordClient.setServer(repositoryConfig.getHttpServer(), repositoryConfig.getHttpPort());
        swordClient.setUserAgent(repositoryConfig.getHttpUserAgent());
        swordClient.setCredentials(repositoryConfig.getAuthUsername(), repositoryConfig.getAuthPassword());

        // message meta
        swordMessage.setNoOp(false);
        swordMessage.setUserAgent(repositoryConfig.getHttpUserAgent());
        swordMessage.setFilepath(swordZipFile.getAbsolutePath());
        swordMessage.setFiletype("application/zip");
        swordMessage.setFormatNamespace("http://purl.org/net/sword-types/METSDSpaceSIP"); // sets packaging!
        swordMessage.setVerbose(false);

        try {
            // check depositurl against service document
            if (checkServicedokument(retrieveServicedocument(), repositoryConfig.getHttpServicedocumentUrl(),
                    SWORDFILETYPE, SWORDFORMAT)) {
                // transmit sword message (zip file with document metadata and document files
                swordMessage.setDestination(repositoryConfig.getHttpDepositUrl());

                depositResponse = swordClient.postFile(swordMessage);

                /*
                 * 200 OK Used in response to successful GET operations and
                 * to Media Resource Creation operations where X-No-Op is
                 * set to true and the server supports this header.
                 * 
                 * 201 Created
                 * 
                 * 202 Accepted - One of these MUST be used to indicate that
                 * a deposit was successful. 202 Accepted is used when
                 * processing of the data is not yet complete.
                 * 
                 * 
                 * 400 Bad Request - used to indicate that there is some
                 * problem with the request where there is no more
                 * appropriate 4xx code.
                 * 
                 * 401 Unauthorized - In addition to the usage described in
                 * HTTP, servers that support mediated deposit SHOULD use
                 * this status code when the server does not understand the
                 * value given in the X-Behalf-Of header. In this case a
                 * human-readable explanation MUST be provided.
                 * 
                 * 403 Forbidden - indicates that there was a problem making
                 * the deposit, it may be that the depositor is not
                 * authorised to deposit on behalf of the target owner, or
                 * the target owner does not have permission to deposit into
                 * the specified collection.
                 * 
                 * 412 Precondition failed - MUST be returned by server
                 * implementations if a calculated checksum does not match a
                 * value provided by the client in the Content-MD5 header.
                 * 
                 * 415 Unsupported Media Type - MUST be used to indicate
                 * that the format supplied in either a Content-Type header
                 * or in an X-Packaging header or the combination of the two
                 * is not accepted by the server.
                 */

                log.info("throw SwordException: errcode" + depositResponse.getHttpResponse());
                throw new SwordException("error.sword.errcode" + depositResponse.getHttpResponse());

            }

        } catch (SWORDClientException e) {
            log.warn("SWORDClientException: " + e.getMessage() + "\n" + e.getCause() + " / "
                    + swordMessage.getDestination());
            throw new SwordException("error.sword.urlnotaccessable");
        }

    }

}

From source file:de.hybris.platform.impex.jalo.ImpExMediasImportTest.java

/**
 * Calls the <code>importData</code> method of given handler with an zip-file path in different formats.
 * /*from w ww  .  j  a va 2s. c o m*/
 * @param handler
 *           handler which will be used for test
 * @param media
 *           media where the data will be imported to
 */
private void mediaImportFromZip(final MediaDataHandler handler, final Media media) {
    File testFile = null;
    try {
        testFile = File.createTempFile("mediaImportTest", ".zip");
        final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testFile));
        zos.putNextEntry(new ZipEntry(new File("files", "dummy.txt").getPath()));
        zos.putNextEntry(new ZipEntry(new File("files", "test.txt").getPath()));
        final PrintWriter printer = new PrintWriter(zos);
        printer.print("testest");
        printer.flush();
        zos.flush();
        printer.close();
        zos.close();
    } catch (final IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    final String unixPathRel = ImpExConstants.Syntax.ZIP_BASED_FILE_PATH_PREFIX
            + FilenameUtils.separatorsToUnix(testFile.getPath()) + "&files/test.txt";
    final String unixPathAbs = ImpExConstants.Syntax.ZIP_BASED_FILE_PATH_PREFIX
            + FilenameUtils.separatorsToUnix(testFile.getAbsolutePath()) + "&files/test.txt";
    final String winPathRel = ImpExConstants.Syntax.ZIP_BASED_FILE_PATH_PREFIX
            + FilenameUtils.separatorsToWindows(testFile.getPath()) + "&files\\test.txt";
    final String winPathAbs = ImpExConstants.Syntax.ZIP_BASED_FILE_PATH_PREFIX
            + FilenameUtils.separatorsToWindows(testFile.getAbsolutePath()) + "&files\\test.txt";
    try {
        mediaImport(handler, media, unixPathRel, "testest");
        mediaImport(handler, media, unixPathAbs, "testest");
        mediaImport(handler, media, winPathRel, "testest");
        mediaImport(handler, media, winPathAbs, "testest");
    } catch (final Exception e) {
        fail(e.getMessage());
    }
    if (!testFile.delete()) {
        fail("Can not delete temp file: " + testFile.getPath());
    }
}

From source file:csns.web.controller.DownloadController.java

@RequestMapping(value = "/download", params = "folderId")
public String downloadFolderFiles(@RequestParam Long folderId, HttpServletResponse response, ModelMap models)
        throws IOException {
    File folder = fileDao.getFile(folderId);
    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=" + folder.getName() + ".zip");
    ZipOutputStream zip = new ZipOutputStream(response.getOutputStream());
    addToZip(zip, folder.getName(), fileDao.listFiles(folder));
    zip.close();/*from  w w  w  .j a v  a  2  s  .c  om*/

    String username = SecurityUtils.isAnonymous() ? "guest" : SecurityUtils.getUser().getUsername();
    logger.info(username + " downloaded folder " + folderId);

    return null;
}

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  w  w  w  .ja v a 2  s  .  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:net.morematerials.manager.UpdateManager.java

private void updateSmp(File file) throws Exception {
    ZipFile smpFile = new ZipFile(file);
    Enumeration<? extends ZipEntry> entries = smpFile.entries();
    String smpName = file.getName().substring(0, file.getName().lastIndexOf("."));

    // First we need to know what files are in this .smp file, because the old format uses magic filename matching.
    ArrayList<String> containedFiles = new ArrayList<String>();
    HashMap<String, YamlConfiguration> materials = new HashMap<String, YamlConfiguration>();

    // Now we walk through the file once and store every file.
    ZipEntry entry;//from   w w w. j  ava2s  . co  m
    YamlConfiguration yaml;
    while (entries.hasMoreElements()) {
        entry = entries.nextElement();

        // Only if its a .yml file
        if (entry.getName().endsWith(".yml")) {
            // Load the .yml file
            yaml = new YamlConfiguration();
            yaml.load(smpFile.getInputStream(entry));

            // Texture is required for new package format.
            if (!yaml.contains("Texture")) {
                materials.put(entry.getName().substring(0, entry.getName().lastIndexOf(".")), yaml);
            } else {
                containedFiles.add(entry.getName());
            }
        } else {
            containedFiles.add(entry.getName());
        }
    }

    // If this map contains any entry, we need to convert something.
    if (materials.size() > 0) {
        this.plugin.getUtilsManager().log("Deprecated .smp found: " + file.getName() + ". Updating...");

        // We need a temporary directory to update the .smp in.
        this.tempDir.mkdir();

        // First extract all untouched assets:
        for (String filename : containedFiles) {
            InputStream in = smpFile.getInputStream(smpFile.getEntry(filename));
            OutputStream out = new FileOutputStream(new File(this.tempDir, filename));
            int read;
            byte[] bytes = new byte[1024];
            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            out.flush();
            out.close();
            in.close();
        }

        // Now convert each .yml file in this archive.
        YamlConfiguration oldYaml;
        YamlConfiguration newYaml;
        for (String materialName : materials.keySet()) {
            oldYaml = materials.get(materialName);
            newYaml = new YamlConfiguration();

            // Required "Type" which is Block or Item. Old format didnt support Tools anyway.
            newYaml.set("Type", oldYaml.getString("Type"));
            // Title is now required and falls back to filename.
            newYaml.set("Title", oldYaml.getString("Title", materialName));

            // Now call the converter methods.
            if (newYaml.getString("Type").equals("Block")) {
                this.convertBlock(oldYaml, newYaml, materialName, containedFiles);
                this.convertBlockHandlers(oldYaml, newYaml);
            } else if (newYaml.getString("Type").equals("Item")) {
                this.convertItem(oldYaml, newYaml, materialName, containedFiles);
                this.convertItemHandlers(oldYaml, newYaml);
            }

            // Copy over recipes - nothing changed here!
            if (oldYaml.contains("Recipes")) {
                newYaml.set("Recipes", oldYaml.getList("Recipes"));
            }

            // Finally store the new .yml file.
            String yamlString = newYaml.saveToString();
            BufferedWriter out = new BufferedWriter(
                    new FileWriter(new File(this.tempDir, materialName + ".yml")));
            out.write(this.fixYamlProblems(yamlString));
            out.close();

            // Also update itemmap entry!
            for (Integer i = 0; i < this.itemMap.size(); i++) {
                String oldMaterial = this.itemMap.get(i).replaceAll("^[0-9]+:MoreMaterials.", "");
                if (oldMaterial.equals(newYaml.getString("Title"))) {
                    this.itemMap.set(i, this.itemMap.get(i).replaceAll("^([0-9]+:MoreMaterials.).+$",
                            "$1" + smpName + "." + materialName));
                    break;
                }
            }

            // And we need to tell SpoutPlugin that this material must be renamed!
            SpoutManager.getMaterialManager().renameMaterialKey(this.plugin, newYaml.getString("Title"),
                    smpName + "." + materialName);
        }

        // First remove old .smp file
        smpFile.close();
        file.delete();

        // Then repack the new .smp file
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file));
        for (File entryFile : this.tempDir.listFiles()) {
            FileInputStream in = new FileInputStream(entryFile);
            out.putNextEntry(new ZipEntry(entryFile.getName()));
            Integer len;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.closeEntry();
            in.close();
        }
        out.close();

        // At last remove the temp directory.
        FileUtils.deleteDirectory(this.tempDir);
    } else {
        // At last, close the file handle.
        smpFile.close();
    }
}

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

@Override
public Backup performBackup(final Iterable<BackupResource> resources) {
    if (resources == null) {
        return null;
    }//from  w ww.j  a  v a  2s  . 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:de.uniwue.info6.database.jaxb.ScenarioExporter.java

/**
 *
 *
 * @param files/*from   ww w.  j  a v a 2  s  . c  o m*/
 * @param zipfile
 * @return
 */
private File zip(List<File> files, File zipfile) {
    byte[] buf = new byte[1024];
    try {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
        for (int i = 0; i < files.size(); i++) {
            FileInputStream in = new FileInputStream(files.get(i));
            out.putNextEntry(new ZipEntry(files.get(i).getName()));
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.closeEntry();
            in.close();
        }
        out.close();
        for (File file : files) {
            if (file.isFile() && file.exists() && file.canWrite()) {
                file.delete();
            }
        }
        return zipfile;
    } catch (Exception e) {
        LOGGER.error("FAILED TO ZIP FILES", e);
    }
    return null;
}

From source file:com.ephesoft.gxt.systemconfig.server.ExportRegexPoolServlet.java

/**
 * Overridden doGet method./*w  w w.j av  a2 s  . c  o  m*/
 */
@Override
public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    final BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
    final RegexGroupService regexGroupService = this.getSingleBeanOfType(RegexGroupService.class);
    final List<RegexGroup> regexGroupList = regexGroupService.getRegexGroups();

    if (regexGroupList == null) {
        LOGGER.error("Regex group list is null.");
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Regex group list is null.");
    } else {
        try {
            final Calendar cal = Calendar.getInstance();
            final String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation();

            final SimpleDateFormat formatter = new SimpleDateFormat(CoreCommonConstant.DATE_FORMAT);
            final String formattedDate = formatter.format(new Date());
            final String zipFileName = StringUtil.concatenate(SystemConfigConstants.REGEX_POOL,
                    CoreCommonConstant.UNDERSCORE, formattedDate, CoreCommonConstant.UNDERSCORE,
                    cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.SECOND));
            final String tempFolderLocation = StringUtil.concatenate(exportSerailizationFolderPath,
                    File.separator, zipFileName);
            final File copiedFolder = new File(tempFolderLocation);

            if (copiedFolder.exists()) {
                copiedFolder.delete();
            }

            // Setting the parent of regex pattern list to null for exporting
            RegexUtil.exportRegexPatterns(regexGroupList);

            // Setting the id of regex group list to "0" for exporting
            for (final RegexGroup regexGroup : regexGroupList) {
                regexGroup.setId(0);
            }
            copiedFolder.mkdirs();

            final File serializedExportFile = new File(tempFolderLocation + File.separator
                    + SystemConfigConstants.REGEX_POOL + SystemConfigConstants.SERIALIZATION_EXT);

            try {
                SerializationUtils.serialize((Serializable) regexGroupList,
                        new FileOutputStream(serializedExportFile));
                final File originalFolder = new File(
                        StringUtil.concatenate(batchSchemaService.getBaseSampleFDLock(), File.separator,
                                SystemConfigConstants.REGEX_POOL));

                if (originalFolder.isDirectory()) {
                    final String[] folderList = originalFolder.list();
                    Arrays.sort(folderList);
                }
            } catch (final FileNotFoundException fileNotFoundException) {
                // Unable to read serializable file
                LOGGER.error("Error occurred while creating the serializable file." + fileNotFoundException,
                        fileNotFoundException);
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Error occurred while creating the serializable file.");
            }

            resp.setContentType(SystemConfigConstants.APPLICATION_X_ZIP);
            resp.setHeader(SystemConfigConstants.CONTENT_DISPOSITION,
                    StringUtil.concatenate(SystemConfigConstants.ATTACHMENT_FILENAME, zipFileName,
                            SystemConfigConstants.ZIP_EXT, SystemConfigConstants.HEADER_MODE));
            ServletOutputStream out = null;
            ZipOutputStream zipOutput = null;
            try {
                out = resp.getOutputStream();
                zipOutput = new ZipOutputStream(out);
                FileUtils.zipDirectory(tempFolderLocation, zipOutput, zipFileName);
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (final IOException ioException) {
                // Unable to create the temporary export file(s)/folder(s)
                LOGGER.error("Error occurred while creating the zip file." + ioException, ioException);
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Unable to export.Please try again.");
            } finally {
                // clean up code
                if (zipOutput != null) {
                    zipOutput.close();
                }
                if (out != null) {
                    out.flush();
                }
                FileUtils.deleteDirectoryAndContentsRecursive(copiedFolder);
            }
        } catch (final Exception exception) {
            LOGGER.error("ERROR IN EXPORT:  " + exception, exception);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again.");
        }
    }
}

From source file:com.thinkbiganalytics.feedmgr.service.ExportImportTemplateService.java

private byte[] zip(RegisteredTemplate template, String nifiTemplateXml, List<String> reusableTemplateXmls) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (ZipOutputStream zos = new ZipOutputStream(baos)) {

        ZipEntry entry = new ZipEntry(NIFI_TEMPLATE_XML_FILE);
        zos.putNextEntry(entry);/* w  ww.j  a va 2  s .c  o m*/
        zos.write(nifiTemplateXml.getBytes());
        zos.closeEntry();
        int reusableTemplateNumber = 0;
        for (String reusableTemplateXml : reusableTemplateXmls) {
            entry = new ZipEntry(String.format("%s_%s.xml", NIFI_CONNECTING_REUSABLE_TEMPLATE_XML_FILE,
                    reusableTemplateNumber++));
            zos.putNextEntry(entry);
            zos.write(reusableTemplateXml.getBytes());
            zos.closeEntry();
        }
        entry = new ZipEntry(TEMPLATE_JSON_FILE);
        zos.putNextEntry(entry);
        String json = ObjectMapperSerializer.serialize(template);
        zos.write(json.getBytes());
        zos.closeEntry();

    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
    return baos.toByteArray();
}

From source file:org.cloudfoundry.tools.io.zip.ZipArchiveTest.java

@Test
public void shouldReloadIfChanged() throws Exception {
    File file = this.zip.getFile("a/b/c.txt");
    assertThat(file.getContent().asString(), is("c"));
    ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(this.zipFile));
    try {//from   w ww . jav a2  s. com
        zipOutputStream.putNextEntry(new ZipEntry("/a/b/c.txt"));
        zipOutputStream.write("c2".getBytes());
    } finally {
        zipOutputStream.close();
    }
    assertThat(file.getContent().asString(), is("c2"));
}