Example usage for java.util.zip ZipInputStream read

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

Introduction

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

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

From source file:org.opendatakit.common.android.task.InitializationTask.java

private final void extractFromRawZip(int resourceId, final boolean overwrite, ArrayList<String> result) {

    final ZipEntryCounter countTotal = new ZipEntryCounter();

    if (resourceId == -1) {
        return;/*  w w  w  . j  ava 2 s. co  m*/
    }

    doActionOnRawZip(resourceId, overwrite, result, countTotal);

    if (countTotal.totalFiles == -1) {
        return;
    }

    ZipAction worker = new ZipAction() {

        long bytesProcessed = 0L;
        long lastBytesProcessedThousands = 0L;

        @Override
        public void doWorker(ZipEntry entry, ZipInputStream zipInputStream, int indexIntoZip, long size)
                throws IOException {

            File tempFile = new File(ODKFileUtils.getAppFolder(appName), entry.getName());
            String formattedString = appContext.getString(R.string.expansion_unzipping_without_detail,
                    entry.getName(), indexIntoZip, countTotal.totalFiles);
            String detail;
            if (entry.isDirectory()) {
                detail = appContext.getString(R.string.expansion_create_dir_detail);
                publishProgress(formattedString, detail);
                tempFile.mkdirs();
            } else if (overwrite || !tempFile.exists()) {
                int bufferSize = 8192;
                OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile, false), bufferSize);
                byte buffer[] = new byte[bufferSize];
                int bread;
                while ((bread = zipInputStream.read(buffer)) != -1) {
                    bytesProcessed += bread;
                    long curThousands = (bytesProcessed / 1000L);
                    if (curThousands != lastBytesProcessedThousands) {
                        detail = appContext.getString(R.string.expansion_unzipping_detail, bytesProcessed,
                                indexIntoZip);
                        publishProgress(formattedString, detail);
                        lastBytesProcessedThousands = curThousands;
                    }
                    out.write(buffer, 0, bread);
                }
                out.flush();
                out.close();

                detail = appContext.getString(R.string.expansion_unzipping_detail, bytesProcessed,
                        indexIntoZip);
                publishProgress(formattedString, detail);
            }
            WebLogger.getLogger(appName).i(t, "Extracted ZipEntry: " + entry.getName());
        }

        @Override
        public void done(int totalCount) {
            String completionString = appContext.getString(R.string.expansion_unzipping_complete, totalCount);
            publishProgress(completionString, null);
        }

    };

    doActionOnRawZip(resourceId, overwrite, result, worker);
}

From source file:pl.psnc.synat.wrdz.zmd.object.parser.ObjectCreationParser.java

/**
 * Parses the request provided as ZIP.//w  w  w .j  a v  a2  s . c  om
 * 
 * @param zis
 *            input stream of the zip request
 * @param name
 *            object name (can be <code>null</code>)
 * @return internal representation of the request
 * @throws IncompleteDataException
 *             when some data are missing
 * @throws InvalidDataException
 *             when some data are invalid
 */
public ObjectCreationRequest parse(ZipInputStream zis, String name)
        throws IncompleteDataException, InvalidDataException {
    ObjectCreationRequestBuilder requestBuilder = new ObjectCreationRequestBuilder();
    if (!new File(root).mkdir()) {
        logger.error("Root folder " + root + " creation failed.");
        throw new WrdzRuntimeException("Root folder " + root + " creation failed.");
    }
    byte[] buffer = new byte[1024];
    ZipEntry entry = null;
    try {
        while ((entry = zis.getNextEntry()) != null) {
            logger.debug("root: " + root + " unzipping: " + entry.getName() + " - is directory: "
                    + entry.isDirectory());
            if (entry.isDirectory()) {
                if (!new File(root + "/" + entry.getName()).mkdir()) {
                    logger.error("folder " + entry.getName() + " creation failed.");
                    throw new WrdzRuntimeException("Folder " + entry.getName() + " creation failed.");
                }
            } else {
                BufferedOutputStream bos = new BufferedOutputStream(
                        new FileOutputStream(root + "/" + entry.getName()), 1024);
                int len;
                while ((len = zis.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                bos.flush();
                bos.close();
                if (entry.getName().toLowerCase().startsWith("metadata/")) {
                    String metadataName = entry.getName().substring(new String("metadata/").length());
                    if (metadataName.contains("/")) {
                        requestBuilder.addInputFileMetadataFile(
                                metadataName.substring(0, metadataName.lastIndexOf('/')),
                                ObjectManagerRequestHelper.makeUri(root, entry.getName()));
                    } else {
                        requestBuilder
                                .addObjectMetadata(ObjectManagerRequestHelper.makeUri(root, entry.getName()));
                    }
                } else {
                    String contentName = entry.getName();
                    if (contentName.toLowerCase().startsWith("content/")) {
                        contentName = contentName.substring(new String("content/").length());
                    }
                    requestBuilder.setInputFileSource(contentName,
                            ObjectManagerRequestHelper.makeUri(root, entry.getName()));
                    requestBuilder.setInputFileDestination(contentName, contentName);
                }
            }
            zis.closeEntry();
        }
        zis.close();
    } catch (FileNotFoundException e) {
        logger.error("Saving the file " + entry.getName() + " failed!");
        throw new WrdzRuntimeException(e.getMessage());
    } catch (IOException e) {
        logger.error("Uncorrect zip file.", e);
        FileUtils.deleteQuietly(new File(root));
        throw new InvalidDataException(e.getMessage());
    }
    requestBuilder.setName(name);
    return requestBuilder.build();
}

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

private void unZipDHIS2APIBackupToTemp(String zipFile) {
    byte[] buffer = new byte[1024];
    String outputFolder = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_TEMP_FOLDER;

    try {/* w  ww .  ja v a2 s.  c  o  m*/
        File destDir = new File(outputFolder);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry = zipIn.getNextEntry();

        while (entry != null) {
            String filePath = outputFolder + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                if (!(new File(filePath)).getParentFile().exists()) {
                    (new File(filePath)).getParentFile().mkdirs();
                }
                (new File(filePath)).createNewFile();
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
                byte[] bytesIn = buffer;
                int read = 0;
                while ((read = zipIn.read(bytesIn)) != -1) {
                    bos.write(bytesIn, 0, read);
                }
                bos.close();
            } else {
                // if the entry is a directory, make the directory
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.eclipse.kura.web.server.servlet.FileServlet.java

private void doPostCommand(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    UploadRequest upload = new UploadRequest(this.m_diskFileItemFactory);

    try {//from   w w w  .  j  ava  2 s .co m
        upload.parse(req);
    } catch (FileUploadException e) {
        s_logger.error("Error parsing the file upload request");
        throw new ServletException("Error parsing the file upload request", e);
    }

    // BEGIN XSRF - Servlet dependent code
    Map<String, String> formFields = upload.getFormFields();

    try {
        GwtXSRFToken token = new GwtXSRFToken(formFields.get("xsrfToken"));
        KuraRemoteServiceServlet.checkXSRFToken(req, token);
    } catch (Exception e) {
        throw new ServletException("Security error: please retry this operation correctly.", e);
    }
    // END XSRF security check

    List<FileItem> fileItems = null;
    InputStream is = null;
    File localFolder = new File(System.getProperty("java.io.tmpdir"));
    OutputStream os = null;

    try {
        fileItems = upload.getFileItems();

        if (fileItems.size() > 0) {
            FileItem item = fileItems.get(0);
            is = item.getInputStream();

            byte[] bytes = IOUtils.toByteArray(is);
            ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bytes));

            int entries = 0;
            long total = 0;
            ZipEntry ze = zis.getNextEntry();
            while (ze != null) {
                byte[] buffer = new byte[BUFFER];

                String expectedFilePath = new StringBuilder(localFolder.getPath()).append(File.separator)
                        .append(ze.getName()).toString();
                String fileName = validateFileName(expectedFilePath, localFolder.getPath());
                File newFile = new File(fileName);
                if (newFile.isDirectory()) {
                    newFile.mkdirs();
                    ze = zis.getNextEntry();
                    continue;
                }
                if (newFile.getParent() != null) {
                    File parent = new File(newFile.getParent());
                    parent.mkdirs();
                }

                FileOutputStream fos = new FileOutputStream(newFile);
                int len;
                while (total + BUFFER <= tooBig && (len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                    total += len;
                }
                fos.flush();
                fos.close();

                entries++;
                if (entries > tooMany) {
                    throw new IllegalStateException("Too many files to unzip.");
                }
                if (total > tooBig) {
                    throw new IllegalStateException("File being unzipped is too big.");
                }

                ze = zis.getNextEntry();
            }

            zis.closeEntry();
            zis.close();
        }
    } catch (IOException e) {
        throw e;
    } catch (GwtKuraException e) {
        throw new ServletException("File is outside extraction target directory.");
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                s_logger.warn("Cannot close output stream", e);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                s_logger.warn("Cannot close input stream", e);
            }
        }
        if (fileItems != null) {
            for (FileItem fileItem : fileItems) {
                fileItem.delete();
            }
        }
    }
}

From source file:de.xirp.plugin.PluginManager.java

/**
 * Extracts files from the plugins jar./*ww  w . j av  a2s.c  o  m*/
 * 
 * @param info
 *            the information about the plugin
 * @param destination
 *            destination for extraction
 * @param comparer
 *            comparer which returns <code>0</code> if an
 *            element from the jar should be extracted
 * @param replace
 *            string of the elements path which should be deleted
 * @param deleteOnExit
 *            <code>true</code> if the extracted files should be
 *            deleted on exit of the application.
 * @return <code>false</code> if an error occurred while
 *         extraction
 */
private static boolean extractFromJar(PluginInfo info, String destination, Comparable<String> comparer,
        String replace, boolean deleteOnExit) {
    if (logClass.isTraceEnabled()) {
        logClass.trace(Constants.LINE_SEPARATOR + "Extracting for Plugin: " + info.getDefaultName() //$NON-NLS-1$
                + " to path " + destination + Constants.LINE_SEPARATOR); //$NON-NLS-1$
    }
    ZipInputStream zip = null;
    FileInputStream in = null;
    try {
        in = new FileInputStream(info.getAbsoluteJarPath());
        zip = new ZipInputStream(in);

        ZipEntry entry = null;
        while ((entry = zip.getNextEntry()) != null) {
            // relative name with slashes to separate dirnames.
            String elementName = entry.getName();
            // Check if it's an entry within Plugin Dir.
            // Only need to extract these

            if (comparer.compareTo(elementName) == 0) {
                // Remove Help Dir Name, because we don't like
                // to extract this parent dir
                elementName = elementName.replaceFirst(replace + JAR_SEPARATOR, "").trim(); //$NON-NLS-1$ 

                if (!elementName.equalsIgnoreCase("")) { //$NON-NLS-1$
                    // if parent dir for File does not exist,
                    // create
                    // it
                    File elementFile = new File(destination, elementName);
                    if (!elementFile.exists()) {
                        elementFile.getParentFile().mkdirs();
                        if (deleteOnExit) {
                            DeleteManager.deleteOnShutdown(elementFile);
                        }
                    }

                    // Only extract files, directorys are created
                    // above with mkdirs
                    if (!entry.isDirectory()) {
                        FileOutputStream fos = new FileOutputStream(elementFile);
                        byte[] buf = new byte[1024];
                        int len;
                        while ((len = zip.read(buf)) > 0) {
                            fos.write(buf, 0, len);
                        }
                        fos.close();
                        elementFile.setLastModified(entry.getTime());
                    }
                    logClass.trace("Extracted: " + elementName + Constants.LINE_SEPARATOR); //$NON-NLS-1$
                }
            }
            zip.closeEntry();
        }

    } catch (IOException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
        return false;
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException e) {
                logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
            }
        }
    }

    return true;
}

From source file:ninja.command.PackageCommand.java

public void unzip(File zipFile, File outputFolder) {

    byte[] buffer = new byte[1024];

    try {/*from  ww  w .ja v  a  2 s.c o  m*/

        // create output directory is not exists
        File folder = outputFolder;
        if (!folder.exists()) {
            folder.mkdir();
        }

        // get the zip file content
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        // get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();
        String zipFilename = zipFile.getName();
        while (ze != null) {
            if (ze.isDirectory()) {
                ze = zis.getNextEntry();
                continue;
            }
            String fileName = ze.getName();
            File newFile = new File(outputFolder, fileName);

            String parentFolder = newFile.getParentFile().getName();
            // (!"META-INF".equals(parentFolder))
            if (newFile.exists() && !"about.html".equals(fileName) && !"META-INF/DEPENDENCIES".equals(fileName)
                    && !"META-INF/LICENSE".equals(fileName) && !"META-INF/NOTICE".equals(fileName)
                    && !"META-INF/NOTICE.txt".equals(fileName) && !"META-INF/MANIFEST.MF".equals(fileName)
                    && !"META-INF/LICENSE.txt".equals(fileName) && !"META-INF/INDEX.LIST".equals(fileName)) {
                String conflicted = zipManifest.get(newFile.getAbsolutePath());
                if (conflicted == null)
                    conflicted = "unknown";
                info(String.format("Conflicts for '%s' with '%s'. File alreay exists '%s", zipFilename,
                        conflicted, newFile));
                conflicts++;
            } else
                zipManifest.put(newFile.getAbsolutePath(), zipFile.getName());
            // create all non exists folders
            // else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

            FileOutputStream fos = new FileOutputStream(newFile);

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

            fos.close();
            ze = zis.getNextEntry();
            count++;
        }

        zis.closeEntry();
        zis.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:nl.coinsweb.sdk.FileManager.java

/**
 * Extracts all the content of the .ccr-file specified in the constructor to [TEMP_ZIP_PATH] / [internalRef].
 *
 *///from   w w  w.  j a  v a  2  s. c o  m
public static void unzipTo(File sourceFile, Path destinationPath) {

    byte[] buffer = new byte[1024];
    String startFolder = null;

    try {

        // Get the zip file content
        ZipInputStream zis = new ZipInputStream(new FileInputStream(sourceFile));
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {

            if (ze.isDirectory()) {
                ze = zis.getNextEntry();
                continue;
            }

            String fileName = ze.getName();

            log.info("Dealing with file " + fileName);

            // If the first folder is a somename/bim/file.ref skip it
            Path filePath = Paths.get(fileName);
            Path pathPath = filePath.getParent();

            if (pathPath.endsWith("bim") || pathPath.endsWith("bim/repository") || pathPath.endsWith("doc")
                    || pathPath.endsWith("woa")) {

                Path pathRoot = pathPath.endsWith("repository") ? pathPath.getParent().getParent()
                        : pathPath.getParent();

                String prefix = "";
                if (pathRoot != null) {
                    prefix = pathRoot.toString();
                }

                if (startFolder == null) {
                    startFolder = prefix;
                    log.debug("File root set to: " + startFolder);

                } else if (startFolder != null && !prefix.equals(startFolder)) {
                    throw new InvalidContainerFileException(
                            "The container file has an inconsistent file root, was " + startFolder
                                    + ", now dealing with " + prefix + ".");
                }
            } else {
                log.debug("Skipping file: " + filePath.toString());
                continue;
            }

            String insideStartFolder = filePath.toString().substring(startFolder.length());
            File newFile = new File(destinationPath + "/" + insideStartFolder);
            log.info("Extract " + newFile);

            // Create all non exists folders
            // else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

            FileOutputStream fos = new FileOutputStream(newFile);

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

            fos.close();
            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:org.wso2.carbon.utils.ArchiveManipulator.java

public void extractFromStream(InputStream inputStream, String extractDir) throws IOException {
    ZipInputStream zin = null;
    OutputStream out = null;/*w  ww  .  j  av  a  2s .  c o  m*/

    try {
        File unzipped = new File(extractDir);
        if (!unzipped.exists() && !unzipped.mkdirs()) {
            throw new IOException("Fail to create the directory: " + unzipped.getAbsolutePath());
        }

        // Open the ZIP file
        zin = new ZipInputStream(inputStream);
        ZipEntry entry;
        while ((entry = zin.getNextEntry()) != null) {
            String entryName = entry.getName();
            File f = new File(extractDir + File.separator + entryName);

            if (entryName.endsWith("/") && !f.exists()) { // this is a
                // directory
                if (!f.mkdirs()) {
                    throw new IOException("Fail to create the directory: " + f.getAbsolutePath());
                }
                continue;
            }

            // This is a file. Carry out File processing
            int lastIndexOfSlash = entryName.lastIndexOf('/');
            String dirPath = "";
            if (lastIndexOfSlash != -1) {
                dirPath = entryName.substring(0, lastIndexOfSlash);
                File dir = new File(extractDir + File.separator + dirPath);
                if (!dir.exists() && !dir.mkdirs()) {
                    throw new IOException("Fail to create the directory: " + dir.getAbsolutePath());
                }
            }

            if (!f.isDirectory()) {
                out = new FileOutputStream(f);
                byte[] buf = new byte[BUFFER_SIZE];

                // Transfer bytes from the ZIP file to the output file
                int len;
                while ((len = zin.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            }
        }
    } catch (IOException e) {
        String msg = "Cannot unzip archive. It is probably corrupted";
        log.error(msg, e);
        throw e;

    } finally {
        try {
            if (zin != null) {
                zin.close();
            }
        } catch (IOException e) {
            log.warn("Unable to close the InputStream " + e.getMessage(), e);
        }

        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            log.warn("Unable to close the OutputStream " + e.getMessage(), e);
        }
    }
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

private void unzipToTemp(File dst) {
    try {//ww  w.j  a v a 2  s  .  c o  m
        ZipInputStream zin = new ZipInputStream(new FileInputStream(dst));
        String workingDir = "./downloads/tmp" + File.separator + "unzipped_tmp";
        byte buffer[] = new byte[4096];
        int bytesRead;

        ZipEntry entry = null;
        while ((entry = zin.getNextEntry()) != null) {
            String dirName = workingDir;

            int endIndex = entry.getName().lastIndexOf(File.separatorChar);
            if (endIndex != -1) {
                dirName += entry.getName().substring(0, endIndex);
            }

            File newDir = new File(dirName);
            // If the directory that this entry should be inflated under does not exist, create it
            if (!newDir.exists() && !newDir.mkdir()) {
                throw new ZipException("Could not create directory " + dirName + "\n");
            }

            // Copy data from ZipEntry to file
            FileOutputStream fos = new FileOutputStream(workingDir + File.separator + entry.getName());
            while ((bytesRead = zin.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            fos.close();
        }
        zin.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.carbon.automation.engine.frameworkutils.ArchiveManipulator.java

/**
 * Extract InputStream to a directory// w  w  w  .j  a v  a 2  s  .  c  om
 *
 * @param inputStream archive inputStream
 * @param extractDir  location to be extract
 * @throws IOException if extracting InputStream failed
 */
public void extractFromStream(InputStream inputStream, String extractDir) throws IOException {
    ZipInputStream zin = null;
    OutputStream out = null;

    try {
        File unzipped = new File(extractDir);
        if (!unzipped.exists() && !unzipped.mkdirs()) {
            throw new IOException("Fail to create the directory: " + unzipped.getAbsolutePath());
        }

        // Open the ZIP file
        zin = new ZipInputStream(inputStream);
        ZipEntry entry;
        while ((entry = zin.getNextEntry()) != null) {
            String entryName = entry.getName();
            File f = new File(extractDir + File.separator + entryName);

            if (entryName.endsWith("/") && !f.exists()) { // this is a
                // directory
                if (!f.mkdirs()) {
                    throw new IOException("Fail to create the directory: " + f.getAbsolutePath());
                }
                continue;
            }

            // This is a file. Carry out File processing
            int lastIndexOfSlash = entryName.lastIndexOf('/');
            String dirPath = "";
            if (lastIndexOfSlash != -1) {
                dirPath = entryName.substring(0, lastIndexOfSlash);
                File dir = new File(extractDir + File.separator + dirPath);
                if (!dir.exists() && !dir.mkdirs()) {
                    throw new IOException("Fail to create the directory: " + dir.getAbsolutePath());
                }
            }

            if (!f.isDirectory()) {
                out = new FileOutputStream(f);
                byte[] buf = new byte[BUFFER_SIZE];

                // Transfer bytes from the ZIP file to the output file
                int len;
                while ((len = zin.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            }
        }
    } finally {
        try {
            if (zin != null) {
                zin.close();
            }
        } catch (IOException e) {
            log.warn("Unable to close the InputStream ", e);
        }

        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            log.warn("Unable to close the OutputStream ", e);
        }
    }
}