Example usage for java.util.zip ZipInputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

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

Usage

From source file:com.nuvolect.securesuite.util.OmniZip.java

/**
 * Unzip the file into the target directory.
 * The added structure is updated to reflect any new files and directories created.
 * Overwrite files when requested.// w  w  w.j  ava 2s.com
 * @param zipOmni
 * @param targetDir
 * @param added
 * @param httpIpPort
 * @return
 */
public static boolean unzipFile(OmniFile zipOmni, OmniFile targetDir, JsonArray added, String httpIpPort) {

    String volumeId = zipOmni.getVolumeId();
    String rootFolderPath = targetDir.getPath();
    boolean DEBUG = true;

    /**
     * Keep a list of all directories created.
     * Defer creating the directory object files until the zip is extracted.
     * This way the dir=1/0 settings can be set accurately.
     */
    ArrayList<OmniFile> directories = new ArrayList<>();

    ZipInputStream zis = new ZipInputStream(zipOmni.getFileInputStream());

    ZipEntry entry = null;
    try {
        while ((entry = zis.getNextEntry()) != null) {

            if (entry.isDirectory()) {

                OmniFile dir = new OmniFile(volumeId, entry.getName());
                if (dir.mkdir()) {

                    directories.add(dir);
                    if (DEBUG)
                        LogUtil.log(LogUtil.LogType.OMNI_ZIP, "dir created: " + dir.getPath());
                }
            } else {

                String path = rootFolderPath + "/" + entry.getName();
                OmniFile file = new OmniFile(volumeId, path);
                // Create any necessary directories
                file.getParentFile().mkdirs();

                if (file.exists()) {
                    file = OmniUtil.makeUniqueName(file);
                }
                OutputStream out = file.getOutputStream();

                OmniFiles.copyFileLeaveInOpen(zis, out);
                if (DEBUG)
                    LogUtil.log(LogUtil.LogType.OMNI_ZIP, "file created: " + file.getPath());

                if (added != null)
                    added.add(file.getFileObject(httpIpPort));
            }
        }
        zis.close();

        if (added != null) {

            /**
             * Iterate over the list of directories created and
             * create object files for each.
             * The full tree is now expanded such that the dir=1/0
             * can be set accurately.
             */
            for (OmniFile dir : directories)
                added.add(dir.getFileObject(httpIpPort));
        }

    } catch (IOException e) {
        LogUtil.logException(LogUtil.LogType.OMNI_ZIP, e);
        return false;
    }

    return true;
}

From source file:net.ftb.util.FileUtils.java

/**
 * Extracts given zip to given location//  www  .  j a v  a 2 s  .  c o  m
 * @param zipLocation - the location of the zip to be extracted
 * @param outputLocation - location to extract to
 */
public static void extractZipTo(String zipLocation, String outputLocation) {
    ZipInputStream zipinputstream = null;
    try {
        byte[] buf = new byte[1024];
        zipinputstream = new ZipInputStream(new FileInputStream(zipLocation));
        ZipEntry zipentry = zipinputstream.getNextEntry();
        while (zipentry != null) {
            String entryName = zipentry.getName();
            int n;
            if (!zipentry.isDirectory() && !entryName.equalsIgnoreCase("minecraft")
                    && !entryName.equalsIgnoreCase(".minecraft") && !entryName.equalsIgnoreCase("instMods")) {
                new File(outputLocation + File.separator + entryName).getParentFile().mkdirs();
                FileOutputStream fileoutputstream = new FileOutputStream(
                        outputLocation + File.separator + entryName);
                while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
                    fileoutputstream.write(buf, 0, n);
                }
                fileoutputstream.close();
            }
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();
        }
    } catch (Exception e) {
        Logger.logError("Error while extracting zip", e);
        backupExtract(zipLocation, outputLocation);
    } finally {
        try {
            zipinputstream.close();
        } catch (IOException e) {
        }
    }
}

From source file:be.fedict.eid.applet.service.signer.asic.ASiCSignatureOutputStream.java

@Override
public void close() throws IOException {
    super.close();

    byte[] signatureData = toByteArray();

    /*// ww  w .j av  a 2s .co m
     * Copy the original ZIP content.
     */
    ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream);
    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile));
    ZipEntry zipEntry;
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (!zipEntry.getName().equals(ASiCUtil.SIGNATURE_FILE)) {
            ZipEntry newZipEntry = new ZipEntry(zipEntry.getName());
            zipOutputStream.putNextEntry(newZipEntry);
            LOG.debug("copying " + zipEntry.getName());
            IOUtils.copy(zipInputStream, zipOutputStream);
        }
    }
    zipInputStream.close();

    /*
     * Add the XML signature file to the ASiC package.
     */
    zipEntry = new ZipEntry(ASiCUtil.SIGNATURE_FILE);
    LOG.debug("writing " + zipEntry.getName());
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write(signatureData, zipOutputStream);
    zipOutputStream.close();
}

From source file:com.glaf.jbpm.deploy.MxJbpmProcessDeployer.java

public ProcessDefinition deploy(JbpmContext jbpmContext, byte[] zipBytes) {
    SAXReader xmlReader = new SAXReader();
    JpdlXmlReader jpdlReader = new JpdlXmlReader();
    Document doc = null;/* w w  w .  j  a v  a  2s .  c  o  m*/
    InputStream inputStream = null;
    ZipInputStream zipInputStream = null;
    ProcessDefinition processDefinition = null;
    Map<String, byte[]> zipMap = null;
    try {
        zipInputStream = new ZipInputStream(new ByteArrayInputStream(zipBytes));
        zipMap = ZipUtils.getZipBytesMap(zipInputStream);
        zipInputStream.close();
        zipInputStream = null;
        if (zipMap != null) {
            if (zipMap.get("processdefinition.xml") != null) {
                byte[] bytes = zipMap.get("processdefinition.xml");
                inputStream = new ByteArrayInputStream(bytes);
                doc = xmlReader.read(inputStream);
                jpdlReader.checkTaskNames(doc);
                this.reconfigProcessDefinition(jbpmContext, doc);
                Element root = doc.getRootElement();
                String encoding = doc.getXMLEncoding();
                String processName = root.attributeValue("name");

                try {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
                    String ret = formatter.format(new Date());
                    String filename = SystemProperties.getConfigRootPath() + "/deploy/" + processName + ret
                            + ".zip";
                    // ?
                    FileUtils.save(filename, zipBytes);
                } catch (Exception ex) {
                    if (LogUtils.isDebug()) {
                        logger.debug(ex);
                        ex.printStackTrace();
                    }
                }

                byte[] pdBytes = Dom4jUtils.getBytesFromPrettyDocument(doc, encoding);
                zipMap.put("processdefinition.xml", pdBytes);

                // ??
                byte[] newZipBytes = ZipUtils.toZipBytes(zipMap);
                zipInputStream = new ZipInputStream(new ByteArrayInputStream(newZipBytes));
                processDefinition = ProcessDefinition.parseParZipInputStream(zipInputStream);
                jbpmContext.deployProcessDefinition(processDefinition);
                zipInputStream.close();
                zipInputStream = null;

                String processDefinitionId = String.valueOf(processDefinition.getId());

                logger.debug("processDefinitionId:" + processDefinitionId);
                logger.debug("processName:" + processName);
                Map<String, Task> taskMap = processDefinition.getTaskMgmtDefinition().getTasks();
                if (taskMap != null && taskMap.size() > 0) {
                    Iterator<String> iter = taskMap.keySet().iterator();
                    while (iter.hasNext()) {
                        String taskName = iter.next();
                        logger.debug("taskName:" + taskName);
                    }
                }

                try {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
                    String ret = formatter.format(new Date());
                    String filename = SystemProperties.getConfigRootPath() + "/deploy/" + processName + ret
                            + "_repack.zip";
                    // ??
                    FileUtils.save(filename, newZipBytes);
                } catch (Exception ex) {
                    if (LogUtils.isDebug()) {
                        logger.debug(ex);
                    }
                }
            }

            if (zipMap.get("process.cfg.xml") != null) {
                byte[] x_bytes = zipMap.get("process.cfg.xml");
                if (x_bytes != null) {
                    JbpmExtensionReader reader = new JbpmExtensionReader();
                    List<Extension> extensions = reader.readTasks(new ByteArrayInputStream(x_bytes));
                    if (extensions != null && extensions.size() > 0) {

                        JbpmExtensionManager jbpmExtensionManager = ProcessContainer.getContainer()
                                .getJbpmExtensionManager();
                        jbpmExtensionManager.reconfig(jbpmContext, extensions);
                    }
                }
            }
        }
        return processDefinition;
    } catch (Throwable ex) {
        if (LogUtils.isDebug()) {
            logger.debug(ex);
            ex.printStackTrace();
        }
        throw new JbpmException(ex);
    } finally {
        try {
            if (zipInputStream != null) {
                zipInputStream.close();
                zipInputStream = null;
            }
        } catch (Exception ex) {
            if (LogUtils.isDebug()) {
                logger.debug(ex);
            }
        }
        try {
            if (inputStream != null) {
                inputStream.close();
                inputStream = null;
            }
        } catch (Exception ex) {
            if (LogUtils.isDebug()) {
                logger.debug(ex);
            }
        }
    }
}

From source file:com.jcalvopinam.core.Unzipping.java

private static void joinAndUnzipFile(File inputFile, CustomFile customFile) throws IOException {

    ZipInputStream is = null;
    File path = inputFile.getParentFile();

    List<InputStream> fileInputStream = new ArrayList<>();
    for (String fileName : path.list()) {
        if (fileName.startsWith(customFile.getFileName()) && fileName.endsWith(Extensions.ZIP.getExtension())) {
            fileInputStream.add(new FileInputStream(String.format("%s%s", customFile.getPath(), fileName)));
            System.out.println(String.format("File found: %s", fileName));
        }//from   ww  w  .j  av a 2 s.  c o m
    }

    if (fileInputStream.size() > 0) {
        String fileNameOutput = String.format("%s%s", customFile.getPath(), customFile.getFileName());
        OutputStream os = new BufferedOutputStream(new FileOutputStream(fileNameOutput));
        try {
            System.out.println("Please wait while the files are joined: ");

            ZipEntry ze;
            for (InputStream inputStream : fileInputStream) {
                is = new ZipInputStream(inputStream);
                ze = is.getNextEntry();
                customFile.setFileName(String.format("%s_%s", REBUILT, ze.getName()));

                byte[] buffer = new byte[CustomFile.BYTE_SIZE];

                for (int readBytes; (readBytes = is.read(buffer, 0, CustomFile.BYTE_SIZE)) > -1;) {
                    os.write(buffer, 0, readBytes);
                    System.out.print(".");
                }
            }
        } finally {
            os.flush();
            os.close();
            is.close();
            renameFinalFile(customFile, fileNameOutput);
        }
    } else {
        throw new FileNotFoundException("Error: The file not exist!");
    }
    System.out.println("\nEnded process!");
}

From source file:de.tudarmstadt.ukp.clarin.webanno.crowdflower.CrowdClient.java

/**
 * Unzips all elements in the file represented by byte[] data.
 * Needed by retrieveRawJudgments which will retrieve a zip-file with a single JSON
 * @param data//from w  ww .  j a  v a  2 s .c  om
 * @return unzipped data
 * @throws IOException
 */

byte[] unzip(final byte[] data) throws IOException {
    final InputStream input = new ByteArrayInputStream(data);
    final byte[] buffer = new byte[1024];

    final ZipInputStream zip = new ZipInputStream(input);
    final ByteArrayOutputStream out = new ByteArrayOutputStream(data.length);
    int count = 0;

    if (zip.getNextEntry() != null) {
        while ((count = zip.read(buffer)) != -1) {
            out.write(buffer, 0, count);
        }
    }

    out.flush();
    zip.close();
    out.close();

    return out.toByteArray();
}

From source file:com.ibm.liberty.starter.ProjectZipConstructor.java

public void initializeMap() throws IOException {
    System.out.println("Entering method ProjectZipConstructor.initializeMap()");
    InputStream skeletonIS = this.getClass().getClassLoader().getResourceAsStream(SKELETON_JAR_FILENAME);
    ZipInputStream zis = new ZipInputStream(skeletonIS);
    ZipEntry ze;//  w ww  .j  a v a2s  .  co m
    while ((ze = zis.getNextEntry()) != null) {
        String path = ze.getName();
        int length = 0;
        byte[] bytes = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while ((length = zis.read(bytes)) != -1) {
            baos.write(bytes, 0, length);
        }
        putFileInMap(path, baos.toByteArray());
    }
    zis.close();
}

From source file:gov.va.chir.tagline.dao.FileDao.java

public static TagLineModel loadTagLineModel(final File file) throws Exception {
    final TagLineModel model = new TagLineModel();

    // Unzip each file to temp
    final File temp = new File(System.getProperty("java.io.tmpdir"));

    byte[] buffer = new byte[BUFFER_SIZE];

    final ZipInputStream zis = new ZipInputStream(new FileInputStream(file));

    ZipEntry entry = zis.getNextEntry();

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

        File tempFile = new File(temp, name);

        // Write out file
        final FileOutputStream fos = new FileOutputStream(tempFile);
        int len;/*from w  w w . jav  a 2s. c o  m*/
        while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }

        fos.close();

        // Determine which file was written
        if (name.equalsIgnoreCase(FILENAME_FEATURES)) {
            model.setFeatures(loadFeatures(tempFile));
        } else if (name.equalsIgnoreCase(FILENAME_HEADER)) {
            model.setHeader(loadHeader(tempFile));
        } else if (name.equalsIgnoreCase(FILENAME_MODEL)) {
            model.setModel(loadModel(tempFile));
        } else {
            throw new IllegalStateException(String.format("Unknown file in TagLine model file (%s)", name));
        }

        // Delete temp file
        tempFile.delete();

        // Get next entry
        zis.closeEntry();
        entry = zis.getNextEntry();
    }

    zis.close();

    return model;
}

From source file:com.relicum.ipsum.io.PropertyIO.java

/**
 * Gets all files in jar./*from  w  w  w.ja v a2s .  com*/
 *
 * @param clazz the clazz
 * @return the list of files and paths in jar
 */
default List<String> getAllFilesInJar(Class<?> clazz) {

    List<String> list = new ArrayList<>();
    CodeSource src = clazz.getProtectionDomain().getCodeSource();
    if (src != null) {
        try {
            URL jar = src.getLocation();
            ZipInputStream zip = new ZipInputStream(jar.openStream());
            while (true) {
                ZipEntry e = zip.getNextEntry();
                if (e == null)
                    break;
                String name = e.getName();
                if (name.contains(".properties")) {
                    list.add(name);
                    System.out.println(name);
                }

            }
            zip.close();
            jar = null;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    return list;
}

From source file:org.activiti.designer.kickstart.eclipse.sync.SyncUtil.java

protected static IFile downloadZipFile(IProject project, Document document, final Shell shell,
        IProgressMonitor monitor) throws Exception {
    IFolder tempzipFolder = project.getFolder("tempzip");
    if (tempzipFolder.exists()) {
        tempzipFolder.delete(true, monitor);
    }/*from  w ww.  j  a  va 2  s .c om*/

    tempzipFolder.create(true, true, monitor);

    IFile file = tempzipFolder.getFile(new Path(document.getName()));
    file.create(CmisUtil.downloadDocument(document), true, null);

    IFile openFile = null;
    byte[] buffer = new byte[1024];
    if ("zip".equalsIgnoreCase(file.getFileExtension())) {
        final ZipInputStream zis = new ZipInputStream(new FileInputStream(file.getLocation().toFile()));
        boolean hasMoreEntries = true;
        IFile processFile = null;
        while (hasMoreEntries) {
            ZipEntry entry = zis.getNextEntry();
            if (entry != null) {
                IFile unzippedFile = tempzipFolder.getFile(entry.getName());
                if ("kickproc".equalsIgnoreCase(unzippedFile.getFileExtension())) {
                    processFile = unzippedFile;
                }
                String filePath = unzippedFile.getLocationURI().getPath();
                File extractFile = new File(filePath);
                FileOutputStream fos = new FileOutputStream(extractFile);
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }

                fos.close();
            } else {
                hasMoreEntries = false;
            }
        }
        zis.close();

        tempzipFolder.getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
        if (processFile != null) {
            openFile = processWorkflowDefinition(processFile, tempzipFolder, document, shell, monitor);
        }
    }

    tempzipFolder.delete(true, monitor);
    project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    return openFile;
}