Example usage for java.util.zip ZipOutputStream setLevel

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

Introduction

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

Prototype

public void setLevel(int level) 

Source Link

Document

Sets the compression level for subsequent entries which are DEFLATED.

Usage

From source file:org.gluu.oxtrust.action.UpdateTrustRelationshipAction.java

@Restrict("#{s:hasPermission('trust', 'access')}")
public String downloadConfiguration() {
    Shibboleth2ConfService shibboleth2ConfService = Shibboleth2ConfService.instance();

    ByteArrayOutputStream bos = new ByteArrayOutputStream(16384);
    ZipOutputStream zos = ResponseHelper.createZipStream(bos, "Shibboleth2 configuration files");
    try {/* w  w  w .  j  a  v a2 s.  c om*/
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setLevel(Deflater.DEFAULT_COMPRESSION);

        // Add files
        String idpMetadataFilePath = shibboleth2ConfService.getIdpMetadataFilePath();
        if (!ResponseHelper.addFileToZip(idpMetadataFilePath, zos,
                Shibboleth2ConfService.SHIB2_IDP_IDP_METADATA_FILE)) {
            log.error("Failed to add " + idpMetadataFilePath + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }

        if (this.trustRelationship.getSpMetaDataFN() == null) {
            log.error("SpMetaDataFN is not set.");
            return OxTrustConstants.RESULT_FAILURE;
        }
        String spMetadataFilePath = shibboleth2ConfService
                .getSpMetadataFilePath(this.trustRelationship.getSpMetaDataFN());
        if (!ResponseHelper.addFileToZip(spMetadataFilePath, zos,
                Shibboleth2ConfService.SHIB2_IDP_SP_METADATA_FILE)) {
            log.error("Failed to add " + spMetadataFilePath + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }
        String sslDirFN = applicationConfiguration.getShibboleth2IdpRootDir() + File.separator
                + TrustService.GENERATED_SSL_ARTIFACTS_DIR + File.separator;
        String spKeyFilePath = sslDirFN + shibboleth2ConfService
                .getSpNewMetadataFileName(this.trustRelationship).replaceFirst("\\.xml$", ".key");
        if (!ResponseHelper.addFileToZip(spKeyFilePath, zos, Shibboleth2ConfService.SHIB2_IDP_SP_KEY_FILE)) {
            log.error("Failed to add " + spKeyFilePath + " to zip");
            //            return OxTrustConstants.RESULT_FAILURE;
        }
        String spCertFilePath = sslDirFN + shibboleth2ConfService
                .getSpNewMetadataFileName(this.trustRelationship).replaceFirst("\\.xml$", ".crt");
        if (!ResponseHelper.addFileToZip(spCertFilePath, zos, Shibboleth2ConfService.SHIB2_IDP_SP_CERT_FILE)) {
            log.error("Failed to add " + spCertFilePath + " to zip");
            //            return OxTrustConstants.RESULT_FAILURE;
        }

        String spAttributeMap = shibboleth2ConfService.generateSpAttributeMapFile(this.trustRelationship);
        if (spAttributeMap == null) {
            log.error("spAttributeMap is not set.");
            return OxTrustConstants.RESULT_FAILURE;
        }
        if (!ResponseHelper.addFileContentToZip(spAttributeMap, zos,
                Shibboleth2ConfService.SHIB2_SP_ATTRIBUTE_MAP)) {
            log.error("Failed to add " + spAttributeMap + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }

        String spShibboleth2FilePath = shibboleth2ConfService.getSpShibboleth2FilePath();
        VelocityContext context = new VelocityContext();
        context.put("spUrl", trustRelationship.getUrl());
        String gluuSPEntityId = trustRelationship.getEntityId();
        context.put("gluuSPEntityId", gluuSPEntityId);
        String spHost = trustRelationship.getUrl().replaceAll(":[0-9]*$", "").replaceAll("^.*?//", "");
        context.put("spHost", spHost);
        String idpUrl = applicationConfiguration.getIdpUrl();
        context.put("idpUrl", idpUrl);
        String idpHost = idpUrl.replaceAll(":[0-9]*$", "").replaceAll("^.*?//", "");
        context.put("idpHost", idpHost);
        context.put("orgInum",
                StringHelper.removePunctuation(OrganizationService.instance().getOrganizationInum()));
        context.put("orgSupportEmail", applicationConfiguration.getOrgSupportEmail());
        String shibConfig = templateService.generateConfFile(Shibboleth2ConfService.SHIB2_SP_SHIBBOLETH2,
                context);
        if (!ResponseHelper.addFileContentToZip(shibConfig, zos, Shibboleth2ConfService.SHIB2_SP_SHIBBOLETH2)) {
            log.error("Failed to add " + spShibboleth2FilePath + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }

        String spReadMeResourceName = shibboleth2ConfService.getSpReadMeResourceName();
        String fileName = (new File(spReadMeResourceName)).getName();
        InputStream is = resourceLoader.getResourceAsStream(spReadMeResourceName);
        //InputStream is = this.getClass().getClassLoader().getResourceAsStream(spReadMeResourceName);
        if (!ResponseHelper.addResourceToZip(is, fileName, zos)) {
            log.error("Failed to add " + spReadMeResourceName + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }
        String spReadMeWindowsResourceName = shibboleth2ConfService.getSpReadMeWindowsResourceName();
        fileName = (new File(spReadMeWindowsResourceName)).getName();
        is = resourceLoader.getResourceAsStream(spReadMeWindowsResourceName);
        if (!ResponseHelper.addResourceToZip(is, fileName, zos)) {
            log.error("Failed to add " + spReadMeWindowsResourceName + " to zip");
            return OxTrustConstants.RESULT_FAILURE;
        }
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(bos);
    }

    boolean result = ResponseHelper.downloadFile("shibboleth2-configuration.zip",
            OxTrustConstants.CONTENT_TYPE_APPLICATION_ZIP, bos.toByteArray(), facesContext);

    return result ? OxTrustConstants.RESULT_SUCCESS : OxTrustConstants.RESULT_FAILURE;
}

From source file:org.dspace.app.itemexport.ItemExportServiceImpl.java

@Override
public void zip(String strSource, String target) throws Exception {
    ZipOutputStream cpZipOutputStream = null;
    String tempFileName = target + "_tmp";
    try {/*  w w  w.  j a v a  2s . co  m*/
        File cpFile = new File(strSource);
        if (!cpFile.isFile() && !cpFile.isDirectory()) {
            return;
        }
        File targetFile = new File(tempFileName);
        if (!targetFile.createNewFile()) {
            log.warn("Target file already exists: " + targetFile.getName());
        }

        FileOutputStream fos = new FileOutputStream(tempFileName);
        cpZipOutputStream = new ZipOutputStream(fos);
        cpZipOutputStream.setLevel(9);
        zipFiles(cpFile, strSource, tempFileName, cpZipOutputStream);
        cpZipOutputStream.finish();
        cpZipOutputStream.close();
        cpZipOutputStream = null;

        // Fix issue on Windows with stale file handles open before trying to delete them
        System.gc();

        deleteDirectory(cpFile);
        if (!targetFile.renameTo(new File(target))) {
            log.error("Unable to rename file");
        }
    } finally {
        if (cpZipOutputStream != null) {
            cpZipOutputStream.close();
        }
    }
}

From source file:org.olat.ims.qti.export.QTIWordExport.java

private void exportTest(String header, OutputStream out, boolean withResponses) {
    ZipOutputStream zout = null;
    try {//from ww  w.j  a  v a 2 s  . c  o  m
        OpenXMLDocument document = new OpenXMLDocument();
        document.setMediaContainer(mediaContainer);
        document.setDocumentHeader(header);

        Translator translator = Util.createPackageTranslator(QTIWordExport.class, locale,
                Util.createPackageTranslator(QTIEditorMainController.class, locale));

        Assessment assessment = rootNode.getAssessment();
        renderAssessment(assessment, document, translator);

        for (Section section : assessment.getSections()) {
            renderSection(section, document);
            List<Item> items = section.getItems();
            for (Iterator<Item> itemIt = items.iterator(); itemIt.hasNext();) {
                Item item = itemIt.next();
                if (item.isAlient()) {
                    renderAlienItem(item, document, translator);
                } else {
                    renderItem(item, document, withResponses, translator);
                }
                if (itemIt.hasNext()) {
                    document.appendPageBreak();
                }
            }
        }

        zout = new ZipOutputStream(out);
        zout.setLevel(9);

        OpenXMLDocumentWriter writer = new OpenXMLDocumentWriter();
        writer.createDocument(zout, document);
    } catch (Exception e) {
        log.error("", e);
    } finally {
        if (zout != null) {
            try {
                zout.finish();
            } catch (IOException e) {
                log.error("", e);
            }
        }
    }
}

From source file:org.zeroturnaround.zip.ZipUtil.java

/**
 * Compresses the given directory and all its sub-directories into a ZIP file.
 * <p>//from   w  ww.  ja va 2  s. co m
 * The ZIP file must not be a directory and its parent directory must exist.
 *
 * @param sourceDir
 *          root directory.
 * @param targetZip
 *          ZIP file that will be created or overwritten.
 * @param compressionLevel
 *          compression level
 */
public static void pack(File sourceDir, File targetZip, NameMapper mapper, int compressionLevel) {
    log.debug("Compressing '{}' into '{}'.", sourceDir, targetZip);
    if (!sourceDir.exists()) {
        throw new ZipException("Given file '" + sourceDir + "' doesn't exist!");
    }
    ZipOutputStream out = null;
    try {
        out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(targetZip)));
        out.setLevel(compressionLevel);
        pack(sourceDir, out, mapper, "", true);
    } catch (IOException e) {
        throw ZipExceptionUtil.rethrow(e);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

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

/**
 * collects all informations to send Documents with metadata to repository 
 * @throws SwordException /*w ww .  ja  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.innovationgate.wga.model.WGADesignConfigurationModel.java

private ZipOutputStream createZIP(File zipFile, boolean obfuscate, String javaSourceFolder)
        throws FileNotFoundException, PersistentKeyException, GeneralSecurityException, IOException {
    if (!zipFile.exists()) {
        zipFile.createNewFile();// ww w .  j  ava  2s.  c o m
    }

    ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));
    zipOutputStream.setLevel(0);

    DirZipper zipper = new DirZipper();
    zipper.setInputStreamProvider(new PluginISProvider(_designDirectory, obfuscate));
    zipper.addFilePatternToIgnore("^\\..*$");

    // Zip all folders and files that belong into an exported plugin
    List<File> filesToZip = new ArrayList<File>();
    filesToZip.add(new File(_designDirectory, DesignDirectory.FOLDERNAME_TML));
    filesToZip.add(new File(_designDirectory, DesignDirectory.FOLDERNAME_SCRIPT));
    filesToZip.add(new File(_designDirectory, DesignDirectory.FOLDERNAME_FILES));
    filesToZip.add(new File(_designDirectory, DesignDirectory.SYNCINFO_FILE));
    filesToZip.add(new File(_designDirectory, DesignDirectory.DESIGN_DEFINITION_FILE));
    Iterator<File> files = filesToZip.iterator();
    while (files.hasNext()) {
        File file = (File) files.next();
        if (file.exists()) {
            if (file.isDirectory()) {
                zipper.zipDirectory(file, zipOutputStream, file.getName() + "/");
            } else {
                zipper.zipFile(file, zipOutputStream);
            }

        }
    }

    // If the design directory has a java classes folder we put those into a jar and zip them to "files/system"
    File javaClassesDir = new File(_designDirectory, DesignDirectory.FOLDERNAME_JAVA);
    if (javaClassesDir.exists() && javaClassesDir.isDirectory()) {
        TemporaryFile jar = new TemporaryFile("plugin-classes.jar", null, null);
        ZipOutputStream jarStream = new ZipOutputStream(new FileOutputStream(jar.getFile()));
        jarStream.setLevel(0);
        DirZipper jarZipper = new DirZipper();
        jarZipper.addFilePatternToIgnore("^\\..*$");
        jarZipper.zipDirectory(javaClassesDir, jarStream);

        jarStream.close();

        zipper.zipNormalFile(jar.getFile(), zipOutputStream, "files/system/");

        jar.delete();
    }

    // If we were given a java source folder we put its contents into plugin-sources.zip and put that into "files/system" (for OSS plugins)
    if (javaSourceFolder != null) {
        File javaSourceDir = new File(javaSourceFolder);
        TemporaryFile zip = new TemporaryFile("plugin-sources.zip", null, null);
        ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(zip.getFile()));
        zipStream.setLevel(0);
        DirZipper jarZipper = new DirZipper();
        jarZipper.addFilePatternToIgnore("^\\..*$");
        jarZipper.zipDirectory(javaSourceDir, zipStream);

        zipStream.close();

        zipper.zipNormalFile(zip.getFile(), zipOutputStream, "files/system/");

        zip.delete();
    }

    if (obfuscate) {
        ZipEntry anEntry = new ZipEntry(DesignDirectory.OBFUSCATE_FLAGFILE);
        zipOutputStream.putNextEntry(anEntry);
        zipOutputStream.write("Obfuscation flagfile".getBytes());
    }

    return zipOutputStream;
}

From source file:se.unlogic.hierarchy.foregroundmodules.imagegallery.GalleryModule.java

@WebPublic(alias = "download")
public SimpleForegroundModuleResponse downloadGallery(HttpServletRequest req, HttpServletResponse res,
        User user, URIParser uriParser) throws SQLException, URINotFoundException {

    Gallery gallery = null;//from w w w  . jav a2s .  c  om

    if (uriParser.size() < 3 || (gallery = this.galleryDao.get(uriParser.get(2))) == null) {

        throw new URINotFoundException(uriParser);

    }

    // check if path is valid
    File dir = new File(gallery.getUrl());

    if (!dir.canRead()) {
        throw new URINotFoundException(uriParser);
    }

    log.info("User " + user + " downloading gallery " + gallery + "...");

    long startTime = System.currentTimeMillis();

    File[] files = dir.listFiles(fileFilter);

    ZipOutputStream zipOutputStream = null;

    try {
        res.setContentType("application/zip");
        res.setHeader("Content-Disposition",
                "inline; filename=\"" + FileUtils.toValidHttpFilename(gallery.getName()) + ".zip\"");
        res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate");

        zipOutputStream = new ZipOutputStream(res.getOutputStream());
        zipOutputStream.setLevel(ZipOutputStream.STORED);

        ZipUtils.addFiles(files, zipOutputStream);

        zipOutputStream.flush();

        log.info("Sent gallery " + gallery + " containing " + files.length + " files to user " + user + " in "
                + TimeUtils.millisecondsToString(System.currentTimeMillis() - startTime));

    } catch (IOException e) {

        log.info("Error sending gallery " + gallery + " to user " + user);

    } finally {

        StreamUtils.closeStream(zipOutputStream);
    }

    return null;
}

From source file:org.pentaho.di.trans.steps.zipfile.ZipFile.java

private void zipFile() throws KettleException {

    String localrealZipfilename = KettleVFS.getFilename(data.zipFile);
    boolean updateZip = false;

    byte[] buffer = null;
    OutputStream dest = null;/*w w  w . ja  va  2s  . c om*/
    BufferedOutputStream buff = null;
    ZipOutputStream out = null;
    InputStream in = null;
    ZipInputStream zin = null;
    ZipEntry entry = null;
    File tempFile = null;
    HashSet<String> fileSet = new HashSet<String>();

    try {

        updateZip = (data.zipFile.exists() && meta.isOverwriteZipEntry());

        if (updateZip) {
            // the Zipfile exists
            // and we weed to update entries
            // Let's create a temp file
            File fileZip = getFile(localrealZipfilename);
            tempFile = File.createTempFile(fileZip.getName(), null);
            // delete it, otherwise we cannot rename existing zip to it.
            tempFile.delete();

            updateZip = fileZip.renameTo(tempFile);
        }

        // Prepare Zip File
        buffer = new byte[18024];
        dest = KettleVFS.getOutputStream(localrealZipfilename, false);
        buff = new BufferedOutputStream(dest);
        out = new ZipOutputStream(buff);

        if (updateZip) {
            // User want to append files to existing Zip file
            // The idea is to rename the existing zip file to a temporary file
            // and then adds all entries in the existing zip along with the new files,
            // excluding the zip entries that have the same name as one of the new files.

            zin = new ZipInputStream(new FileInputStream(tempFile));
            entry = zin.getNextEntry();

            while (entry != null) {
                String name = entry.getName();

                if (!fileSet.contains(name)) {

                    // Add ZIP entry to output stream.
                    out.putNextEntry(new ZipEntry(name));
                    // Transfer bytes from the ZIP file to the output file
                    int len;
                    while ((len = zin.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }

                    fileSet.add(name);
                }
                entry = zin.getNextEntry();
            }
            // Close the streams
            zin.close();
        }

        // Set the method
        out.setMethod(ZipOutputStream.DEFLATED);
        out.setLevel(Deflater.BEST_COMPRESSION);

        // Associate a file input stream for the current file
        in = KettleVFS.getInputStream(data.sourceFile);

        // Add ZIP entry to output stream.
        //
        String relativeName = data.sourceFile.getName().getBaseName();

        if (meta.isKeepSouceFolder()) {
            // Get full filename
            relativeName = KettleVFS.getFilename(data.sourceFile);

            if (data.baseFolder != null) {
                // Remove base folder
                data.baseFolder += Const.FILE_SEPARATOR;
                relativeName = relativeName.replace(data.baseFolder, "");
            }
        }
        if (!fileSet.contains(relativeName)) {
            out.putNextEntry(new ZipEntry(relativeName));

            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        }
    } catch (Exception e) {
        throw new KettleException(BaseMessages.getString(PKG, "ZipFile.ErrorCreatingZip"), e);
    } finally {
        try {
            if (in != null) {
                // Close the current file input stream
                in.close();
            }
            if (out != null) {
                // Close the ZipOutPutStream
                out.flush();
                out.closeEntry();
                out.close();
            }
            if (buff != null) {
                buff.close();
            }
            if (dest != null) {
                dest.close();
            }
            // Delete Temp File
            if (tempFile != null) {
                tempFile.delete();
            }
            fileSet = null;

        } catch (Exception e) { /* Ignore */
        }
    }

}

From source file:de.innovationgate.wgpublisher.WGACore.java

public InputStream dumpContentStore(WGDatabase dbSource, String filterExpression, boolean autoCorrect,
        Logger log, boolean includeACL, boolean includeSystemAreas, boolean includeArchived)
        throws WGAPIException, IOException {

    log.info("Creating dump database");

    // Create working folder for dump database
    File dir = File.createTempFile("csd", ".tmp", WGFactory.getTempDir());
    dir.delete();//from www .j  av a  2s  . co  m
    dir.mkdir();

    // Create dump database
    Map<String, String> options = new HashMap<String, String>();
    options.put(WGDatabase.COPTION_MONITORLASTCHANGE, "false");
    options.put(WGDatabaseImpl.COPTION_DISTINCTFILECONTENTS, "false");
    WGDatabase dbTarget = WGFactory.getInstance().openDatabase(null,
            de.innovationgate.webgate.api.hsql.WGDatabaseImpl.class.getName(), dir.getAbsolutePath() + "/wgacs",
            "sa", null, options);
    dbTarget.setDbReference("Temporary WGACS dump target");

    // Replicate
    log.info("Synchronizing data to dump database");
    dbSource.lock();
    try {
        ContentStoreDumpManager importer = new ContentStoreDumpManager(dbSource, dbTarget, log);
        importer.exportDump(includeACL, includeSystemAreas, includeArchived);
    } finally {
        dbSource.unlock();
    }

    // Close database and zip up its contents
    log.info("Creating dump file");
    dbTarget.close();
    File zipFile = File.createTempFile("csz", ".tmp", WGFactory.getTempDir());
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
    out.setLevel(9);
    File[] files = dir.listFiles();
    for (int i = 0; i < files.length; i++) {
        File file = files[i];
        out.putNextEntry(new ZipEntry(file.getName()));
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        WGUtils.inToOut(in, out, 2048);
        in.close();
        out.closeEntry();
    }
    out.close();

    // Delete temp dir
    WGUtils.delTree(dir);

    // Return input stream for zip file
    return new TempFileInputStream(zipFile);

}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public Object getPortfolio(MimeType outMimeType, String portfolioUuid, int userId, int groupId, String label,
        String resource, String files) throws Exception {
    String rootNodeUuid = getPortfolioRootNode(portfolioUuid);
    String header = "";
    String footer = "";
    NodeRight nodeRight = credential.getPortfolioRight(userId, groupId, portfolioUuid, Credential.READ);
    if (!nodeRight.read)
        return "faux";

    if (outMimeType.getSubType().equals("xml")) {
        //         header = "<portfolio xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' schemaVersion='1.0'>";
        //         footer = "</portfolio>";

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder;
        Document document = null;
        try {//from w  w  w.  java  2  s. c  o  m
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.newDocument();
            document.setXmlStandalone(true);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Element root = document.createElement("portfolio");
        root.setAttribute("id", portfolioUuid);
        root.setAttribute("code", "0");

        //// Noeuds supplmentaire pour WAD
        // Version
        Element verNode = document.createElement("version");
        Text version = document.createTextNode("3");
        verNode.appendChild(version);
        root.appendChild(verNode);
        // metadata-wad
        Element metawad = document.createElement("metadata-wad");
        metawad.setAttribute("prog", "main.jsp");
        metawad.setAttribute("owner", "N");
        root.appendChild(metawad);

        //          root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        //          root.setAttribute("schemaVersion", "1.0");
        document.appendChild(root);

        getLinearXml(portfolioUuid, rootNodeUuid, root, true, null, userId, groupId);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));

        if (resource != null && files != null) {

            if (resource.equals("true") && files.equals("true")) {
                String adressedufichier = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".xml";
                String adresseduzip = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".zip";

                File file = null;
                PrintWriter ecrire;
                PrintWriter ecri;
                try {
                    file = new File(adressedufichier);
                    ecrire = new PrintWriter(new FileOutputStream(adressedufichier));
                    ecrire.println(stw.toString());
                    ecrire.flush();
                    ecrire.close();
                    System.out.print("fichier cree ");
                } catch (IOException ioe) {
                    System.out.print("Erreur : ");
                    ioe.printStackTrace();
                }

                try {
                    String fileName = portfolioUuid + ".zip";

                    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(adresseduzip));
                    zip.setMethod(ZipOutputStream.DEFLATED);
                    zip.setLevel(Deflater.BEST_COMPRESSION);
                    File dataDirectories = new File(file.getName());
                    FileInputStream fis = new FileInputStream(dataDirectories);
                    byte[] bytes = new byte[fis.available()];
                    fis.read(bytes);

                    ZipEntry entry = new ZipEntry(file.getName());
                    entry.setTime(dataDirectories.lastModified());
                    zip.putNextEntry(entry);
                    zip.write(bytes);
                    zip.closeEntry();
                    fis.close();
                    //zipDirectory(dataDirectories, zip);
                    zip.close();

                    file.delete();

                    return adresseduzip;

                } catch (FileNotFoundException fileNotFound) {
                    fileNotFound.printStackTrace();

                } catch (IOException io) {

                    io.printStackTrace();
                }
            }
        }

        return stw.toString();

    } else if (outMimeType.getSubType().equals("json")) {
        header = "{\"portfolio\": { \"-xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\"-schemaVersion\": \"1.0\",";
        footer = "}}";
    }

    return header + getNode(outMimeType, rootNodeUuid, true, userId, groupId, label).toString() + footer;
}