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, int off, int len) throws IOException 

Source Link

Document

Reads from the current ZIP entry into an array of bytes.

Usage

From source file:nl.nn.adapterframework.webcontrol.pipes.TestPipeLine.java

private String processZipFile(IPipeLineSession session, InputStream inputStream, String fileEncoding,
        IAdapter adapter, boolean writeSecLogMessage) throws IOException {
    String result = "";
    String lastState = null;/*from  w  ww  .j  av  a2 s.  c  o  m*/
    ZipInputStream archive = new ZipInputStream(inputStream);
    for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) {
        String name = entry.getName();
        int size = (int) entry.getSize();
        if (size > 0) {
            byte[] b = new byte[size];
            int rb = 0;
            int chunk = 0;
            while (((int) size - rb) > 0) {
                chunk = archive.read(b, rb, (int) size - rb);
                if (chunk == -1) {
                    break;
                }
                rb += chunk;
            }
            String message = XmlUtils.readXml(b, 0, rb, fileEncoding, false);
            if (StringUtils.isNotEmpty(result)) {
                result += "\n";
            }
            lastState = processMessage(adapter, message, writeSecLogMessage).getState();
            result += name + ":" + lastState;
        }
        archive.closeEntry();
    }
    archive.close();
    session.put("state", lastState);
    session.put("result", result);
    return "";
}

From source file:mitm.common.security.JCEPolicyManager.java

private void installJCEPolicy(ZipInputStream zis, String filename) throws IOException {
    byte data[] = new byte[ZIP_BUFFER_SIZE];

    File jarFile = File.createTempFile("jce", ".jar");

    try {//from w w w. java2 s  .c  o  m
        FileOutputStream fos = new FileOutputStream(jarFile);

        OutputStream output = new BufferedOutputStream(fos, ZIP_BUFFER_SIZE);

        File destination = new File(getJCEPolicyLibPath(), filename);

        try {
            int count;

            while ((count = zis.read(data, 0, ZIP_BUFFER_SIZE)) != -1) {
                output.write(data, 0, count);
            }
        } finally {
            output.flush();
            output.close();
        }

        copyPolicyFile(jarFile, destination);
    } finally {
        jarFile.delete();
    }
}

From source file:com.celements.photo.utilities.Unzip.java

private ByteArrayOutputStream findAndExtractFile(String filename, ZipInputStream zipIn) throws IOException {
    ByteArrayOutputStream out = null;

    for (ZipEntry entry = zipIn.getNextEntry(); zipIn.available() > 0; entry = zipIn.getNextEntry()) {
        if (!entry.isDirectory() && entry.getName().equals(filename)) {
            // read the data and write it to the OutputStream
            int count;
            byte[] data = new byte[BUFFER];
            out = new ByteArrayOutputStream();
            BufferedOutputStream byteOut = new BufferedOutputStream(out, BUFFER);
            while ((count = zipIn.read(data, 0, BUFFER)) != -1) {
                byteOut.write(data, 0, count);
            }/* ww  w . j  a  v  a2  s .  co m*/
            byteOut.flush();
            break;
        }
    }

    zipIn.close();
    return out;
}

From source file:nl.nn.adapterframework.webcontrol.api.TestPipeline.java

private void processZipFile(Map<String, Object> returnResult, InputStream inputStream, String fileEncoding,
        IAdapter adapter, boolean writeSecLogMessage) throws IOException {
    String result = "";
    String lastState = null;/*from w w  w.  j a  v a2 s. co  m*/
    ZipInputStream archive = new ZipInputStream(inputStream);
    for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) {
        String name = entry.getName();
        int size = (int) entry.getSize();
        if (size > 0) {
            byte[] b = new byte[size];
            int rb = 0;
            int chunk = 0;
            while (((int) size - rb) > 0) {
                chunk = archive.read(b, rb, (int) size - rb);
                if (chunk == -1) {
                    break;
                }
                rb += chunk;
            }
            String message = XmlUtils.readXml(b, 0, rb, fileEncoding, false);
            if (StringUtils.isNotEmpty(result)) {
                result += "\n";
            }
            lastState = processMessage(adapter, message, writeSecLogMessage).getState();
            result += name + ":" + lastState;
        }
        archive.closeEntry();
    }
    archive.close();
    returnResult.put("state", lastState);
    returnResult.put("result", result);
}

From source file:com.googlecode.jsfFlex.shared.tasks.sdk.UnzipTask.java

protected void performTask() {

    BufferedOutputStream bufferOutputStream = null;
    ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(_file));
    ZipEntry entry;/*from   w w  w. j  a v a2  s  .  co  m*/

    try {

        while ((entry = zipInputStream.getNextEntry()) != null) {

            ensureDirectoryExists(entry.getName(), entry.isDirectory());

            bufferOutputStream = new BufferedOutputStream(new FileOutputStream(_dest + entry.getName()),
                    BUFFER_SIZE);
            int currRead = 0;
            byte[] dataRead = new byte[BUFFER_SIZE];

            while ((currRead = zipInputStream.read(dataRead, 0, BUFFER_SIZE)) != -1) {
                bufferOutputStream.write(dataRead, 0, currRead);
            }
            bufferOutputStream.flush();
            bufferOutputStream.close();
        }

        _log.debug("UnzipTask performTask has been completed with " + toString());
    } catch (IOException ioExcept) {
        StringBuilder errorMessage = new StringBuilder();
        errorMessage.append("Error in Unzip's performTask with following fields \n");
        errorMessage.append(toString());
        throw new ComponentBuildException(errorMessage.toString(), ioExcept);
    } finally {
        try {
            zipInputStream.close();
            if (bufferOutputStream != null) {
                bufferOutputStream.close();
            }
        } catch (IOException innerIOExcept) {
            _log.info("Error while closing the streams within UnzipTask's finally block");
        }
    }

}

From source file:org.apache.atlas.repository.impexp.ZipSource.java

private void updateGuidZipEntryMap() throws IOException {

    ZipInputStream zipInputStream = new ZipInputStream(inputStream);
    ZipEntry zipEntry = zipInputStream.getNextEntry();
    while (zipEntry != null) {
        String entryName = zipEntry.getName().replace(".json", "");

        if (guidEntityJsonMap.containsKey(entryName))
            continue;

        byte[] buf = new byte[1024];

        int n = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((n = zipInputStream.read(buf, 0, 1024)) > -1) {
            bos.write(buf, 0, n);/*w  w  w .j a v  a2s  . c om*/
        }

        guidEntityJsonMap.put(entryName, bos.toString());
        zipEntry = zipInputStream.getNextEntry();

    }

    zipInputStream.close();
}

From source file:edu.ucla.loni.server.Upload.java

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {//from  w w  w.  ja  v  a2s.  co  m
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(req);

            // Go through the items and get the root and package
            String rootPath = "";
            String packageName = "";

            for (FileItem item : items) {
                if (item.isFormField()) {
                    if (item.getFieldName().equals("root")) {
                        rootPath = item.getString();
                    } else if (item.getFieldName().equals("packageName")) {
                        packageName = item.getString();
                    }
                }
            }

            if (rootPath.equals("")) {
                res.getWriter().println("error :: Root directory has not been found.");
                return;
            }

            Directory root = Database.selectDirectory(rootPath);

            // Go through items and process urls and files
            for (FileItem item : items) {
                // Uploaded File
                if (item.isFormField() == false) {
                    String filename = item.getName();
                    ;
                    if (filename.equals("") == true)
                        continue;
                    try {
                        InputStream in = item.getInputStream();
                        //determine if it is pipefile or zipfile
                        //if it is pipefile => feed directly to writeFile function
                        //otherwise, uncompresse it first and then one-by-one feed to writeFile
                        if (filename.endsWith(".zip")) {
                            ZipInputStream zip = new ZipInputStream(in);
                            ZipEntry entry = zip.getNextEntry();
                            while (entry != null) {
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                if (baos != null) {
                                    byte[] arr = new byte[4096];
                                    int index = 0;
                                    while ((index = zip.read(arr, 0, 4096)) != -1) {
                                        baos.write(arr, 0, index);
                                    }
                                }
                                InputStream is = new ByteArrayInputStream(baos.toByteArray());
                                writeFile(root, packageName, is);
                                entry = zip.getNextEntry();
                            }
                            zip.close();
                        } else {
                            writeFile(root, packageName, in);

                        }

                        in.close();
                    } catch (Exception e) {
                        res.getWriter().println("Failed to upload " + filename + ". " + e.getMessage());
                    }
                }
                // URLs               
                if (item.isFormField() && item.getFieldName().equals("urls")
                        && item.getString().equals("") == false) {
                    String urlListAsStr = item.getString();
                    String[] urlList = urlListAsStr.split("\n");

                    for (String urlStr : urlList) {
                        try {
                            URL url = new URL(urlStr);
                            URLConnection urlc = url.openConnection();

                            InputStream in = urlc.getInputStream();

                            writeFile(root, packageName, in);

                            in.close();
                        } catch (Exception e) {
                            res.getWriter().println("Failed to upload " + urlStr);
                            return;
                        }
                    }
                }
            }
        } catch (Exception e) {
            res.getWriter().println("Error occurred while creating file. Error Message : " + e.getMessage());
        }
    }
}

From source file:org.owasp.dependencycheck.utils.FileUtils.java

/**
 * Extracts the contents of an archive into the specified directory. The files are only extracted if they are
 * supported by the analyzers loaded into the specified engine. If the engine is specified as null then all files
 * are extracted./*from  w  w  w.j a v a 2 s.  com*/
 *
 * @param archive an archive file such as a WAR or EAR
 * @param extractTo a directory to extract the contents to
 * @param engine the scanning engine
 * @throws ExtractionException thrown if there is an error extracting the files
 */
public static void extractFiles(File archive, File extractTo, Engine engine) throws ExtractionException {
    if (archive == null || extractTo == null) {
        return;
    }

    FileInputStream fis = null;
    ZipInputStream zis = null;

    try {
        fis = new FileInputStream(archive);
    } catch (FileNotFoundException ex) {
        LOGGER.log(Level.FINE, null, ex);
        throw new ExtractionException("Archive file was not found.", ex);
    }
    zis = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry;
    try {
        while ((entry = zis.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                final File d = new File(extractTo, entry.getName());
                if (!d.exists() && !d.mkdirs()) {
                    final String msg = String.format("Unable to create '%s'.", d.getAbsolutePath());
                    throw new ExtractionException(msg);
                }
            } else {
                final File file = new File(extractTo, entry.getName());
                final String ext = getFileExtension(file.getName());
                if (engine == null || engine.supportsExtension(ext)) {
                    BufferedOutputStream bos = null;
                    FileOutputStream fos;
                    try {
                        fos = new FileOutputStream(file);
                        bos = new BufferedOutputStream(fos, BUFFER_SIZE);
                        int count;
                        final byte data[] = new byte[BUFFER_SIZE];
                        while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                            bos.write(data, 0, count);
                        }
                        bos.flush();
                    } catch (FileNotFoundException ex) {
                        LOGGER.log(Level.FINE, null, ex);
                        final String msg = String.format("Unable to find file '%s'.", file.getName());
                        throw new ExtractionException(msg, ex);
                    } catch (IOException ex) {
                        LOGGER.log(Level.FINE, null, ex);
                        final String msg = String.format("IO Exception while parsing file '%s'.",
                                file.getName());
                        throw new ExtractionException(msg, ex);
                    } finally {
                        if (bos != null) {
                            try {
                                bos.close();
                            } catch (IOException ex) {
                                LOGGER.log(Level.FINEST, null, ex);
                            }
                        }
                    }
                }
            }
        }
    } catch (IOException ex) {
        final String msg = String.format("Exception reading archive '%s'.", archive.getName());
        LOGGER.log(Level.FINE, msg, ex);
        throw new ExtractionException(msg, ex);
    } finally {
        try {
            zis.close();
        } catch (IOException ex) {
            LOGGER.log(Level.FINEST, null, ex);
        }
    }
}

From source file:com.glaf.core.util.ZipUtils.java

public static void unzip(java.io.InputStream inputStream, String dir) throws Exception {
    File file = new File(dir);
    FileUtils.mkdirsWithExistsCheck(file);
    ZipInputStream zipInputStream = null;
    FileOutputStream fileoutputstream = null;
    BufferedOutputStream bufferedoutputstream = null;
    try {/*from www .j  a  v a 2s.  c  o m*/
        zipInputStream = new ZipInputStream(inputStream);

        java.util.zip.ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            boolean isDirectory = zipEntry.isDirectory();
            byte abyte0[] = new byte[BUFFER];
            String s1 = zipEntry.getName();

            s1 = convertEncoding(s1);

            String s2 = dir + sp + s1;
            s2 = FileUtils.getJavaFileSystemPath(s2);

            if (s2.indexOf('/') != -1 || isDirectory) {
                String s4 = s2.substring(0, s2.lastIndexOf('/'));
                File file2 = new File(s4);
                FileUtils.mkdirsWithExistsCheck(file2);
            }
            if (isDirectory) {
                continue;
            }
            fileoutputstream = new FileOutputStream(s2);
            bufferedoutputstream = new BufferedOutputStream(fileoutputstream, BUFFER);
            int i = 0;
            while ((i = zipInputStream.read(abyte0, 0, BUFFER)) != -1) {
                bufferedoutputstream.write(abyte0, 0, i);
            }
            bufferedoutputstream.flush();
            IOUtils.closeStream(fileoutputstream);
            IOUtils.closeStream(bufferedoutputstream);
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(zipInputStream);
        IOUtils.closeStream(fileoutputstream);
        IOUtils.closeStream(bufferedoutputstream);
    }
}

From source file:util.TraversalZipTool.java

/**
 * Returns the zip entries as Media beans.
 *
 * @param zipBytes/*w  ww  .j a v a  2  s .c  om*/
 * @return List of Media beans
 */
public List getEntries(byte[] zipBytes) throws SomeZipException {

    ByteArrayInputStream bis = null;
    ZipInputStream zis = null;
    ZipEntry zipEntry = null;
    List entries = new ArrayList();
    byte[] b = null;

    try {
        bis = new ByteArrayInputStream(zipBytes);
        zis = new ZipInputStream(bis);
        boolean notDone = true;
        zipEntry = zis.getNextEntry();
        while (zipEntry != null) {
            if (zipEntry.isDirectory()) {
                zipEntry = zis.getNextEntry();
                continue;
            }
            b = new byte[MAX_MEDIA_SIZE];
            int offset = 0;
            int rb = 0;
            while ((zis.available() != 0) && ((rb = zis.read(b, offset, CHUNK)) != -1)) {
                offset += rb;
            }
            if ((zis.available() == 0) || (rb == -1)) {
                String entryName = zipEntry.getName();
                String suffix = getSuffix(entryName);
                if (validImage.isValidSuffix(suffix)) {
                    Media media = new Media();
                    //logger.info("Found New Image " + offset + " bytes");
                    media.setData(new String(b, 0, offset).getBytes());
                    media.setSize(offset);
                    //logger.info("ZipEntry name = " + entryName);
                    media.setName(fileName(entryName));
                    entries.add(media);
                } else {
                    logger.warn("Bad image file in zip, ignoring " + entryName);
                }
                zis.closeEntry();
                zipEntry = zis.getNextEntry();
            }
        }
        zis.close();
    } catch (Exception e) {
        throw new SomeZipException("Error processing zip bytes", e);
    }
    return entries;
}