Example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream close

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream close

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with the stream.

Usage

From source file:fr.gael.dhus.datastore.processing.impl.ProcessProductPrepareDownload.java

/**
 * Creates a zip file at the specified path with the contents of the 
 * specified directory.//from www .  j  a  v a2s . com
 * @param Input directory path. The directory were is located directory to archive.
 * @param The full path of the zip file.
 * @return the checksum accordig to fr.gael.dhus.datastore.processing.impl.zip.digest variable.
 * @throws IOException If anything goes wrong
 */
protected Map<String, String> processZip(String inpath, File output) throws IOException {
    // Retrieve configuration settings
    String[] algorithms = cfgManager.getDownloadConfiguration().getChecksumAlgorithms().split(",");
    int compressionLevel = cfgManager.getDownloadConfiguration().getCompressionLevel();

    FileOutputStream fOut = null;
    BufferedOutputStream bOut = null;
    ZipArchiveOutputStream tOut = null;
    MultipleDigestOutputStream dOut = null;

    try {
        fOut = new FileOutputStream(output);
        if ((algorithms != null) && (algorithms.length > 0)) {
            try {
                dOut = new MultipleDigestOutputStream(fOut, algorithms);
                bOut = new BufferedOutputStream(dOut);
            } catch (NoSuchAlgorithmException e) {
                logger.error("Problem computing checksum algorithms.", e);
                dOut = null;
                bOut = new BufferedOutputStream(fOut);
            }

        } else
            bOut = new BufferedOutputStream(fOut);
        tOut = new ZipArchiveOutputStream(bOut);
        tOut.setLevel(compressionLevel);

        addFileToZip(tOut, inpath, "");
    } finally {
        try {
            tOut.finish();
            tOut.close();
            bOut.close();
            if (dOut != null)
                dOut.close();
            fOut.close();
        } catch (Exception e) {
            logger.error("Exception raised during ZIP stream close", e);
        }
    }
    if (dOut != null) {
        Map<String, String> checksums = new HashMap<String, String>();
        for (String algorithm : algorithms) {
            String chk = dOut.getMessageDigestAsHexadecimalString(algorithm);
            if (chk != null)
                checksums.put(algorithm, chk);
        }
        return checksums;
    }
    return null;
}

From source file:fr.itldev.koya.alfservice.KoyaContentService.java

/**
 *
 * @param nodeRefs//from   w ww  .j av  a 2  s . c o m
 * @return
 * @throws KoyaServiceException
 */
public File zip(List<String> nodeRefs) throws KoyaServiceException {
    File tmpZipFile = null;
    try {
        tmpZipFile = TempFileProvider.createTempFile("tmpDL", ".zip");
        FileOutputStream fos = new FileOutputStream(tmpZipFile);
        CheckedOutputStream checksum = new CheckedOutputStream(fos, new Adler32());
        BufferedOutputStream buff = new BufferedOutputStream(checksum);
        ZipArchiveOutputStream zipStream = new ZipArchiveOutputStream(buff);
        // NOTE: This encoding allows us to workaround bug...
        // http://bugs.sun.com/bugdatabase/view_bug.do;:WuuT?bug_id=4820807
        zipStream.setEncoding("UTF-8");

        zipStream.setMethod(ZipArchiveOutputStream.DEFLATED);
        zipStream.setLevel(Deflater.BEST_COMPRESSION);

        zipStream.setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.ALWAYS);
        zipStream.setUseLanguageEncodingFlag(true);
        zipStream.setFallbackToUTF8(true);

        try {
            for (String nodeRef : nodeRefs) {
                addToZip(koyaNodeService.getNodeRef(nodeRef), zipStream, "");
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        } finally {
            zipStream.close();
            buff.close();
            checksum.close();
            fos.close();

        }
    } catch (IOException | WebScriptException e) {
        logger.error(e.getMessage(), e);
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    }

    return tmpZipFile;
}

From source file:cz.cuni.mff.ufal.AllBitstreamZipArchiveReader.java

@Override
public void generate() throws IOException, SAXException, ProcessingException {

    if (redirect != NO_REDIRECTION) {
        return;/*  w ww  . ja  v a2s. c om*/
    }

    String name = item.getName() + ".zip";

    try {

        // first write everything to a temp file
        String tempDir = ConfigurationManager.getProperty("upload.temp.dir");
        String fn = tempDir + File.separator + "SWORD." + item.getID() + "." + UUID.randomUUID().toString()
                + ".zip";
        OutputStream outStream = new FileOutputStream(new File(fn));
        ZipArchiveOutputStream zip = new ZipArchiveOutputStream(outStream);
        zip.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        zip.setLevel(Deflater.NO_COMPRESSION);
        ConcurrentMap<String, AtomicInteger> usedFilenames = new ConcurrentHashMap<String, AtomicInteger>();

        Bundle[] originals = item.getBundles("ORIGINAL");
        if (needsZip64) {
            zip.setUseZip64(Zip64Mode.Always);
        }
        for (Bundle original : originals) {
            Bitstream[] bss = original.getBitstreams();
            for (Bitstream bitstream : bss) {
                String filename = bitstream.getName();
                String uniqueName = createUniqueFilename(filename, usedFilenames);
                ZipArchiveEntry ze = new ZipArchiveEntry(uniqueName);
                zip.putArchiveEntry(ze);
                InputStream is = bitstream.retrieve();
                Utils.copy(is, zip);
                zip.closeArchiveEntry();
                is.close();
            }
        }
        zip.close();

        File file = new File(fn);
        zipFileSize = file.length();

        zipInputStream = new TempFileInputStream(file);
    } catch (AuthorizeException e) {
        log.error(e.getMessage(), e);
        throw new ProcessingException("You do not have permissions to access one or more files.");
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new ProcessingException("Could not create ZIP, please download the files one by one. "
                + "The error has been stored and will be solved by our technical team.");
    }

    // Log download statistics
    for (int bitstreamID : bitstreamIDs) {
        DSpaceApi.updateFileDownloadStatistics(userID, bitstreamID);
    }

    response.setDateHeader("Last-Modified", item.getLastModified().getTime());

    // Try and make the download file name formated for each browser.
    try {
        String agent = request.getHeader("USER-AGENT");
        if (agent != null && agent.contains("MSIE")) {
            name = URLEncoder.encode(name, "UTF8");
        } else if (agent != null && agent.contains("Mozilla")) {
            name = MimeUtility.encodeText(name, "UTF8", "B");
        }
    } catch (UnsupportedEncodingException see) {
        name = "item_" + item.getID() + ".zip";
    }
    response.setHeader("Content-Disposition", "attachment;filename=" + name);

    byte[] buffer = new byte[BUFFER_SIZE];
    int length = -1;

    try {
        response.setHeader("Content-Length", String.valueOf(this.zipFileSize));

        while ((length = this.zipInputStream.read(buffer)) > -1) {
            out.write(buffer, 0, length);
        }
        out.flush();
    } finally {
        try {
            if (this.zipInputStream != null) {
                this.zipInputStream.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException ioe) {
            // Closing the stream threw an IOException but do we want this to propagate up to Cocoon?
            // No point since the user has already got the file contents.
            log.warn("Caught IO exception when closing a stream: " + ioe.getMessage());
        }
    }

}

From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java

/**
 * Writes a modified version of zip_Source into target.
 *
 * @author S3460//from  ww w . j  a v a  2s  .  c om
 * @param zipSource the zip source
 * @param target the target
 * @return the zip file
 * @throws Exception the exception
 */
private ZipFile makeTargetZipFile(ZipFile zipSource, File target) throws Exception {
    ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(target));
    for (Enumeration<ZipArchiveEntry> enumer = zipSource.getEntries(); enumer.hasMoreElements();) {
        ZipArchiveEntry sourceEntry = enumer.nextElement();
        out.putArchiveEntry(new ZipArchiveEntry(sourceEntry.getName()));
        byte[] oldBytes = toBytes(zipSource, sourceEntry);
        byte[] newBytes = getRandomBytes();
        byte[] mixedBytes = mixBytes(oldBytes, newBytes);
        out.write(mixedBytes, 0, mixedBytes.length);
        out.flush();
        out.closeArchiveEntry();
    }
    out.putArchiveEntry(new ZipArchiveEntry("zipentry" + entryMaxSize + 1));
    byte[] bytes = getRandomBytes();
    out.write(bytes, 0, bytes.length);
    out.flush();
    out.closeArchiveEntry();
    out.putArchiveEntry(new ZipArchiveEntry("zipentry" + (entryMaxSize + 2)));
    out.closeArchiveEntry();
    out.flush();
    out.finish();
    out.close();
    return new ZipFile(targetFile);
}

From source file:com.iisigroup.cap.log.TimeFolderSizeRollingFileAppender.java

public void zipFiles(List<String> fileList, String destUrl) throws IOException {

    FileUtils.forceMkdir(new File(FilenameUtils.getFullPathNoEndSeparator(destUrl)));
    BufferedInputStream origin = null;
    FileOutputStream fos = null;//from   www  .  ja  v  a2s . c o  m
    BufferedOutputStream bos = null;
    ZipArchiveOutputStream out = null;
    byte data[] = new byte[BUFFER];
    try {
        fos = new FileOutputStream(destUrl);
        bos = new BufferedOutputStream(fos);
        out = new ZipArchiveOutputStream(bos);

        for (String fName : fileList) {
            File file = new File(fName);
            FileInputStream fi = new FileInputStream(file);
            origin = new BufferedInputStream(fi, BUFFER);
            ZipArchiveEntry entry = new ZipArchiveEntry(file.getName());
            out.putArchiveEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            out.closeArchiveEntry();
            fi.close();
            origin.close();
        }

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

From source file:com.gitblit.servlet.PtServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//  w  w w.j av  a 2s.  co m
        response.setContentType("application/octet-stream");
        response.setDateHeader("Last-Modified", lastModified);
        response.setHeader("Cache-Control", "none");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        boolean windows = false;
        try {
            String useragent = request.getHeader("user-agent").toString();
            windows = useragent.toLowerCase().contains("windows");
        } catch (Exception e) {
        }

        byte[] pyBytes;
        File file = runtimeManager.getFileOrFolder("tickets.pt", "${baseFolder}/pt.py");
        if (file.exists()) {
            // custom script
            pyBytes = readAll(new FileInputStream(file));
        } else {
            // default script
            pyBytes = readAll(getClass().getResourceAsStream("/pt.py"));
        }

        if (windows) {
            // windows: download zip file with pt.py and pt.cmd
            response.setHeader("Content-Disposition", "attachment; filename=\"pt.zip\"");

            OutputStream os = response.getOutputStream();
            ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os);

            // add the Python script
            ZipArchiveEntry pyEntry = new ZipArchiveEntry("pt.py");
            pyEntry.setSize(pyBytes.length);
            pyEntry.setUnixMode(FileMode.EXECUTABLE_FILE.getBits());
            pyEntry.setTime(lastModified);
            zos.putArchiveEntry(pyEntry);
            zos.write(pyBytes);
            zos.closeArchiveEntry();

            // add a Python launch cmd file
            byte[] cmdBytes = readAll(getClass().getResourceAsStream("/pt.cmd"));
            ZipArchiveEntry cmdEntry = new ZipArchiveEntry("pt.cmd");
            cmdEntry.setSize(cmdBytes.length);
            cmdEntry.setUnixMode(FileMode.REGULAR_FILE.getBits());
            cmdEntry.setTime(lastModified);
            zos.putArchiveEntry(cmdEntry);
            zos.write(cmdBytes);
            zos.closeArchiveEntry();

            // add a brief readme
            byte[] txtBytes = readAll(getClass().getResourceAsStream("/pt.txt"));
            ZipArchiveEntry txtEntry = new ZipArchiveEntry("readme.txt");
            txtEntry.setSize(txtBytes.length);
            txtEntry.setUnixMode(FileMode.REGULAR_FILE.getBits());
            txtEntry.setTime(lastModified);
            zos.putArchiveEntry(txtEntry);
            zos.write(txtBytes);
            zos.closeArchiveEntry();

            // cleanup
            zos.finish();
            zos.close();
            os.flush();
        } else {
            // unix: download a tar.gz file with pt.py set with execute permissions
            response.setHeader("Content-Disposition", "attachment; filename=\"pt.tar.gz\"");

            OutputStream os = response.getOutputStream();
            CompressorOutputStream cos = new CompressorStreamFactory()
                    .createCompressorOutputStream(CompressorStreamFactory.GZIP, os);
            TarArchiveOutputStream tos = new TarArchiveOutputStream(cos);
            tos.setAddPaxHeadersForNonAsciiNames(true);
            tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);

            // add the Python script
            TarArchiveEntry pyEntry = new TarArchiveEntry("pt");
            pyEntry.setMode(FileMode.EXECUTABLE_FILE.getBits());
            pyEntry.setModTime(lastModified);
            pyEntry.setSize(pyBytes.length);
            tos.putArchiveEntry(pyEntry);
            tos.write(pyBytes);
            tos.closeArchiveEntry();

            // add a brief readme
            byte[] txtBytes = readAll(getClass().getResourceAsStream("/pt.txt"));
            TarArchiveEntry txtEntry = new TarArchiveEntry("README");
            txtEntry.setMode(FileMode.REGULAR_FILE.getBits());
            txtEntry.setModTime(lastModified);
            txtEntry.setSize(txtBytes.length);
            tos.putArchiveEntry(txtEntry);
            tos.write(txtBytes);
            tos.closeArchiveEntry();

            // cleanup
            tos.finish();
            tos.close();
            cos.close();
            os.flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.citytechinc.cq.component.maven.util.ComponentMojoUtil.java

/**
 * Add files to the already constructed Archive file by creating a new
 * Archive file, appending the contents of the existing Archive file to it,
 * and then adding additional entries for the newly constructed artifacts.
 * /*from w  w w  .  ja v  a2  s  . co m*/
 * @param classList
 * @param classLoader
 * @param classPool
 * @param buildDirectory
 * @param componentPathBase
 * @param defaultComponentPathSuffix
 * @param defaultComponentGroup
 * @param existingArchiveFile
 * @param tempArchiveFile
 * @throws OutputFailureException
 * @throws IOException
 * @throws InvalidComponentClassException
 * @throws InvalidComponentFieldException
 * @throws ParserConfigurationException
 * @throws TransformerException
 * @throws ClassNotFoundException
 * @throws CannotCompileException
 * @throws NotFoundException
 * @throws SecurityException
 * @throws NoSuchFieldException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws InstantiationException
 */
public static void buildArchiveFileForProjectAndClassList(List<CtClass> classList,
        WidgetRegistry widgetRegistry, TouchUIWidgetRegistry touchUIWidgetRegistry, ClassLoader classLoader,
        ClassPool classPool, File buildDirectory, String componentPathBase, String defaultComponentPathSuffix,
        String defaultComponentGroup, File existingArchiveFile, File tempArchiveFile,
        ComponentNameTransformer transformer, boolean generateTouchUiDialogs) throws OutputFailureException,
        IOException, InvalidComponentClassException, InvalidComponentFieldException,
        ParserConfigurationException, TransformerException, ClassNotFoundException, CannotCompileException,
        NotFoundException, SecurityException, NoSuchFieldException, IllegalArgumentException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException,
        TouchUIDialogWriteException, TouchUIDialogGenerationException {

    if (!existingArchiveFile.exists()) {
        throw new OutputFailureException("Archive file does not exist");
    }

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

    tempArchiveFile.createNewFile();

    deleteTemporaryComponentOutputDirectory(buildDirectory);

    /*
     * Create archive input stream
     */
    ZipArchiveInputStream existingInputStream = new ZipArchiveInputStream(
            new FileInputStream(existingArchiveFile));

    /*
     * Create a zip archive output stream for the temp file
     */
    ZipArchiveOutputStream tempOutputStream = new ZipArchiveOutputStream(tempArchiveFile);

    /*
     * Iterate through all existing entries adding them to the new archive
     */
    ZipArchiveEntry curArchiveEntry;

    Set<String> existingArchiveEntryNames = new HashSet<String>();

    while ((curArchiveEntry = existingInputStream.getNextZipEntry()) != null) {
        existingArchiveEntryNames.add(curArchiveEntry.getName().toLowerCase());
        getLog().debug("Current File Name: " + curArchiveEntry.getName());
        tempOutputStream.putArchiveEntry(curArchiveEntry);
        IOUtils.copy(existingInputStream, tempOutputStream);
        tempOutputStream.closeArchiveEntry();
    }

    /*
     * Create content.xml within temp archive
     */
    ContentUtil.buildContentFromClassList(classList, tempOutputStream, existingArchiveEntryNames,
            buildDirectory, componentPathBase, defaultComponentPathSuffix, defaultComponentGroup, transformer);

    /*
     * Create Dialogs within temp archive
     */
    DialogUtil.buildDialogsFromClassList(transformer, classList, tempOutputStream, existingArchiveEntryNames,
            widgetRegistry, classLoader, classPool, buildDirectory, componentPathBase,
            defaultComponentPathSuffix);

    if (generateTouchUiDialogs) {
        TouchUIDialogUtil.buildDialogsFromClassList(classList, classLoader, classPool, touchUIWidgetRegistry,
                transformer, buildDirectory, componentPathBase, defaultComponentPathSuffix, tempOutputStream,
                existingArchiveEntryNames);
    }

    /*
     * Create edit config within temp archive
     */
    EditConfigUtil.buildEditConfigFromClassList(classList, tempOutputStream, existingArchiveEntryNames,
            buildDirectory, componentPathBase, defaultComponentPathSuffix, transformer);

    /*
     * Copy temp archive to the original archive position
     */
    tempOutputStream.finish();
    existingInputStream.close();
    tempOutputStream.close();

    existingArchiveFile.delete();
    tempArchiveFile.renameTo(existingArchiveFile);

}

From source file:es.ucm.fdi.util.archive.ZipFormat.java

public void create(ArrayList<File> sources, File destFile, File baseDir) throws IOException {

    // to avoid modifying input argument
    ArrayList<File> toAdd = new ArrayList<>(sources);
    ZipArchiveOutputStream zos = null;

    try {/*from  w w w.  ja va  2  s . com*/
        zos = new ZipArchiveOutputStream(new FileOutputStream(destFile));
        zos.setMethod(ZipArchiveOutputStream.DEFLATED);
        byte[] b = new byte[1024];

        //log.debug("Creating zip file: "+ficheroZip.getName());
        for (int i = 0; i < toAdd.size(); i++) {
            // note: cannot use foreach because sources gets modified
            File file = toAdd.get(i);

            // zip standard uses fw slashes instead of backslashes, always
            String baseName = baseDir.getAbsolutePath() + '/';
            String fileName = file.getAbsolutePath().substring(baseName.length());
            if (file.isDirectory()) {
                fileName += '/';
            }
            ZipArchiveEntry entry = new ZipArchiveEntry(fileName);

            // skip directories - after assuring that their children *will* be included.
            if (file.isDirectory()) {
                //log.debug("\tAdding dir "+fileName);
                for (File child : file.listFiles()) {
                    toAdd.add(child);
                }
                zos.putArchiveEntry(entry);
                continue;
            }

            //log.debug("\tAdding file "+fileName);

            // Add the zip entry and associated data.
            zos.putArchiveEntry(entry);

            int n;
            try (FileInputStream fis = new FileInputStream(file)) {
                while ((n = fis.read(b)) > -1) {
                    zos.write(b, 0, n);
                }
                zos.closeArchiveEntry();
            }
        }
    } finally {
        if (zos != null) {
            zos.finish();
            zos.close();
        }
    }
}

From source file:com.jaeksoft.searchlib.crawler.web.database.UrlManager.java

public File exportCrawlCache(AbstractSearchRequest searchRequest) throws IOException, SearchLibException {
    File tempFile = null;/* w  w w . ja  va  2  s.  c  om*/
    ZipArchiveOutputStream zipOutput = null;
    CrawlCacheManager crawlCacheManager = ClientCatalog.getCrawlCacheManager();
    if (crawlCacheManager.isDisabled())
        throw new SearchLibException("The crawlCache is disabled.");
    try {
        tempFile = File.createTempFile("OSS_web_crawler_crawlcache", ".zip");
        zipOutput = new ZipArchiveOutputStream(tempFile);
        int currentPos = 0;
        List<UrlItem> uList = new ArrayList<UrlItem>();
        for (;;) {
            int totalSize = (int) getUrlList(searchRequest, currentPos, 1000, uList);
            if (uList.size() == 0)
                break;
            for (UrlItem u : uList) {
                URL url = u.getURL();
                if (url == null)
                    continue;
                DownloadItem downloadItem = crawlCacheManager.loadCache(url.toURI());
                if (downloadItem == null)
                    continue;
                downloadItem.writeToZip(zipOutput);
            }
            uList.clear();
            currentPos += 1000;
            if (currentPos >= totalSize)
                break;
        }
        zipOutput.close();
        zipOutput = null;
        return tempFile;
    } catch (JSONException e) {
        throw new IOException(e);
    } catch (URISyntaxException e) {
        throw new IOException(e);
    } finally {
        if (zipOutput != null)
            IOUtils.closeQuietly(zipOutput);
    }
}

From source file:fr.gael.dhus.datastore.processing.ProcessingManager.java

/**
 * Creates a zip file at the specified path with the contents of the
 * specified directory.//from  ww w. ja  va2  s  .  com
 *
 * @param Input directory path. The directory were is located directory to
 *           archive.
 * @param The full path of the zip file.
 * @return the checksum accordig to
 *         fr.gael.dhus.datastore.processing.impl.zip.digest variable.
 * @throws IOException If anything goes wrong
 */
private Map<String, String> processZip(String inpath, File output) throws IOException {
    // Retrieve configuration settings
    String[] algorithms = cfgManager.getDownloadConfiguration().getChecksumAlgorithms().split(",");
    int compressionLevel = cfgManager.getDownloadConfiguration().getCompressionLevel();

    FileOutputStream fOut = null;
    BufferedOutputStream bOut = null;
    ZipArchiveOutputStream tOut = null;
    MultipleDigestOutputStream dOut = null;

    try {
        fOut = new FileOutputStream(output);
        if ((algorithms != null) && (algorithms.length > 0)) {
            try {
                dOut = new MultipleDigestOutputStream(fOut, algorithms);
                bOut = new BufferedOutputStream(dOut);
            } catch (NoSuchAlgorithmException e) {
                LOGGER.error("Problem computing checksum algorithms.", e);
                dOut = null;
                bOut = new BufferedOutputStream(fOut);
            }

        } else
            bOut = new BufferedOutputStream(fOut);
        tOut = new ZipArchiveOutputStream(bOut);
        tOut.setLevel(compressionLevel);

        addFileToZip(tOut, inpath, "");
    } finally {
        try {
            tOut.finish();
            tOut.close();
            bOut.close();
            if (dOut != null)
                dOut.close();
            fOut.close();
        } catch (Exception e) {
            LOGGER.error("Exception raised during ZIP stream close", e);
        }
    }
    if (dOut != null) {
        Map<String, String> checksums = new HashMap<String, String>();
        for (String algorithm : algorithms) {
            String chk = dOut.getMessageDigestAsHexadecimalString(algorithm);
            if (chk != null)
                checksums.put(algorithm, chk);
        }
        return checksums;
    }
    return null;
}