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.UploadConfig.java

private String processZipFile(IPipeLineSession session, String fileName) throws PipeRunException, IOException {
    String result = "";
    Object form_file = session.get("file");
    if (form_file != null) {
        if (form_file instanceof InputStream) {
            InputStream inputStream = (InputStream) form_file;
            String form_fileEncoding = (String) session.get("fileEncoding");
            if (inputStream.available() > 0) {
                /*/*  w  w w.j  a  v a2  s .co  m*/
                 * String fileEncoding; if
                 * (StringUtils.isNotEmpty(form_fileEncoding)) {
                 * fileEncoding = form_fileEncoding; } else { fileEncoding =
                 * Misc.DEFAULT_INPUT_STREAM_ENCODING; }
                 */ZipInputStream archive = new ZipInputStream(inputStream);
                int counter = 1;
                for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) {
                    String entryName = 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;
                        }
                        ByteArrayInputStream bais = new ByteArrayInputStream(b, 0, rb);
                        String fileNameSessionKey = "file_zipentry" + counter;
                        session.put(fileNameSessionKey, bais);
                        if (StringUtils.isNotEmpty(result)) {
                            result += "\n";
                        }
                        String name = "";
                        String version = "";
                        String[] fnArray = splitFilename(entryName);
                        if (fnArray[0] != null) {
                            name = fnArray[0];
                        }
                        if (fnArray[1] != null) {
                            version = fnArray[1];
                        }
                        result += entryName + ":"
                                + processJarFile(session, name, version, entryName, fileNameSessionKey);
                        session.remove(fileNameSessionKey);
                    }
                    archive.closeEntry();
                    counter++;
                }
                archive.close();
            }
        }
    }
    return result;
}

From source file:org.ktunaxa.referral.server.mvc.UploadGeometryController.java

private URL unzipShape(byte[] fileContent) throws IOException {
    String tempDir = System.getProperty("java.io.tmpdir");

    URL url = null;// w  w w.  j  a  v a2  s  .co m
    ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(fileContent));
    try {
        ZipEntry entry;
        while ((entry = zin.getNextEntry()) != null) {
            log.info("Extracting: " + entry);
            String name = tempDir + "/" + entry.getName();
            tempFiles.add(name);
            if (name.endsWith(".shp")) {
                url = new URL("file://" + name);
            }
            int count;
            byte[] data = new byte[BUFFER];
            // write the files to the disk
            deleteFileIfExists(name);
            FileOutputStream fos = new FileOutputStream(name);
            BufferedOutputStream destination = new BufferedOutputStream(fos, BUFFER);
            try {
                while ((count = zin.read(data, 0, BUFFER)) != -1) {
                    destination.write(data, 0, count);
                }
                destination.flush();
            } finally {
                destination.close();
            }
        }
    } finally {
        zin.close();
    }
    if (url == null) {
        throw new IllegalArgumentException("Missing .shp file");
    }
    return url;
}

From source file:com.amazonaws.eclipse.elasticbeanstalk.git.AWSGitPushCommand.java

private void extractZipFile(File zipFile, File destination) throws IOException {
    int BUFFER = 2048;

    FileInputStream fis = new FileInputStream(zipFile);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    BufferedOutputStream dest = null;
    try {/*from   w w  w. j  ava2s.  com*/
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            int count;
            byte data[] = new byte[BUFFER];
            // write the files to the disk

            if (entry.isDirectory())
                continue;

            File entryFile = new File(destination, entry.getName());
            if (!entryFile.getParentFile().exists()) {
                entryFile.getParentFile().mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(entryFile);
            dest = new BufferedOutputStream(fos, BUFFER);
            while ((count = zis.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
        }
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(zis);
        IOUtils.closeQuietly(dest);
    }
}

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

private String processZipFile(InputStream inputStream, String fileEncoding, String jmsRealm,
        boolean automatic_reload, boolean activate_config, String user) throws Exception {
    String result = "";
    if (inputStream.available() > 0) {
        ZipInputStream archive = new ZipInputStream(inputStream);
        int counter = 1;
        for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) {
            String entryName = 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;
                    }/*from   ww  w.  jav  a  2 s  .  c  o m*/
                    rb += chunk;
                }
                ByteArrayInputStream bais = new ByteArrayInputStream(b, 0, rb);
                String fileName = "file_zipentry" + counter;
                if (StringUtils.isNotEmpty(result)) {
                    result += "\n";
                }
                String name = "";
                String version = "";
                String[] fnArray = splitFilename(entryName);
                if (fnArray[0] != null) {
                    name = fnArray[0];
                }
                if (fnArray[1] != null) {
                    version = fnArray[1];
                }
                result += entryName + ":" + ConfigurationUtils.addConfigToDatabase(ibisContext, jmsRealm,
                        activate_config, automatic_reload, name, version, fileName, bais, user);
            }
            archive.closeEntry();
            counter++;
        }
        archive.close();
    }
    return result;
}

From source file:dk.dma.msinm.web.rest.LocationRestService.java

/**
 * Parse the KML file of the uploaded .kmz or .kml file and returns a JSON list of locations
 *
 * @param request the servlet request//  w  w w . jav  a  2s.  c om
 * @return the corresponding list of locations
 */
@POST
@javax.ws.rs.Path("/upload-kml")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/json;charset=UTF-8")
public List<LocationVo> uploadKml(@Context HttpServletRequest request) throws FileUploadException, IOException {
    FileItemFactory factory = RepositoryService.newDiskFileItemFactory(servletContext);
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);

    for (FileItem item : items) {
        if (!item.isFormField()) {
            try {
                // .kml file
                if (item.getName().toLowerCase().endsWith(".kml")) {
                    // Parse the KML and return the corresponding locations
                    return parseKml(IOUtils.toString(item.getInputStream()));
                }

                // .kmz file
                else if (item.getName().toLowerCase().endsWith(".kmz")) {
                    // Parse the .kmz file as a zip file
                    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(item.getInputStream()));
                    ZipEntry entry;

                    // Look for the first zip entry with a .kml extension
                    while ((entry = zis.getNextEntry()) != null) {
                        if (!entry.getName().toLowerCase().endsWith(".kml")) {
                            continue;
                        }

                        log.info("Unzipping: " + entry.getName());
                        int size;
                        byte[] buffer = new byte[2048];
                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                            bytes.write(buffer, 0, size);
                        }
                        bytes.flush();
                        zis.close();

                        // Parse the KML and return the corresponding locations
                        return parseKml(new String(bytes.toByteArray(), "UTF-8"));
                    }
                }

            } catch (Exception ex) {
                log.error("Error extracting kmz", ex);
            }
        }
    }

    // Return an empty result
    return new ArrayList<>();
}

From source file:sloca.controller.fileUpdate.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods to process updating files/*ww w  .  jav  a  2s .com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {

        //Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //Configure a repository to ensure a secure temp location
        //is used
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");

        //Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        //Parse the reqeust
        List<FileItem> items = upload.parseRequest(request);
        //Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (!item.isFormField()) {
                InputStream is = item.getInputStream();

                ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
                ZipEntry ze;

                while ((ze = zis.getNextEntry()) != null) {
                    String filePath = repository + File.separator + ze.getName();
                    if (ze.getName().equals("demographics.csv") | ze.getName().equals("location.csv")) {
                        // out.println("entered print if<br/>");
                        int count;
                        byte data[] = new byte[BUFFER];
                        FileOutputStream fos = new FileOutputStream(filePath);
                        BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);
                        while ((count = zis.read(data, 0, BUFFER)) != -1) {
                            bos.write(data, 0, count);
                        }
                        bos.flush();
                        bos.close();
                    }
                }
                zis.close();
            }
        }

        File[] files = new File(repository.toString()).listFiles();

        boolean isDemoInserted = false;
        boolean isLocInserted = false;

        boolean isDemoValidFile = false;
        boolean isLocValidFile = false;
        //check if zip files contain the any of the 3 data files
        for (File file : files) {

            String fileName = file.getName();
            if (fileName.contains("demographics.csv")) {
                isDemoValidFile = true;
            } else if (fileName.contains("location.csv")) {
                isLocValidFile = true;
            }
        }
        //if uploaded folder does not contain the files, it will go back to bootstrap.jsp
        if (!isDemoValidFile && !isLocValidFile) {

            request.setAttribute("fileUploadError", "Invalid .zip file");
            RequestDispatcher rd = request.getRequestDispatcher("adminDisplay.jsp");
            rd.forward(request, response);
            return;
        }
        //while all the files are not inserted
        BootStrapManager bm = new BootStrapManager();
        for (File file : files) {
            String fileName = file.getName();
            String filePath = repository + File.separator + fileName;
            //out.println("</br>" + filePath);
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
                br.readLine();
                String line = null;
                if (!isDemoInserted && fileName.contains("demographics.csv")) {
                    bm.updateDemo(filePath);
                    isDemoInserted = true;

                }

                if (!isLocInserted && fileName.contains("location.csv")) {
                    bm.updateLoc(filePath);
                    isLocInserted = true;
                }

                br.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    br.close();
                }
            }

            file.delete();
        }

        //            out.println(
        //                    "Size of Demographics errors: " + BootStrapManager.demoErrorList.size());
        //            out.println(
        //                    "Size of Location Lookup errors: " + BootStrapManager.locLookUpErrorList.size());
        //            out.println(
        //                    "Size of Location errors: " + BootStrapManager.locErrorList.size());
        response.sendRedirect("updateResults.jsp");
    } catch (FileUploadException e) {
        out.println("gone case");
    } finally {
        out.close();

    }
}

From source file:com.marklogic.contentpump.CompressedRDFReader.java

@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
    boolean stillReading = super.nextKeyValue();
    if (stillReading) {
        return true;
    }//from  w  w  w. jav a 2s  . c o m

    // Ok, we've run out of data in the current file, are there more?
    URI zipURI = file.toUri();
    if (codec.equals(CompressionCodec.ZIP)) {
        ZipInputStream zis = (ZipInputStream) zipIn;

        ByteArrayOutputStream baos;
        while ((currZipEntry = zis.getNextEntry()) != null) {
            if (currZipEntry.getSize() == 0) {
                continue;
            }

            long size = currZipEntry.getSize();
            if (size == -1) {
                baos = new ByteArrayOutputStream();
                // if we don't know the size, assume it's big!
                initParser(zipURI.toASCIIString() + "/" + currZipEntry.getName(), INMEMORYTHRESHOLD);
            } else {
                baos = new ByteArrayOutputStream((int) size);
                initParser(zipURI.toASCIIString() + "/" + currZipEntry.getName(), size);
            }
            int nb;
            while ((nb = zis.read(buf, 0, buf.length)) != -1) {
                baos.write(buf, 0, nb);
            }

            parse(currZipEntry.getName(), new ByteArrayInputStream(baos.toByteArray()));
            boolean gotTriples = super.nextKeyValue();
            if (gotTriples) {
                return true;
            }
        }
        // end of zip
        if (iterator != null && iterator.hasNext()) {
            close();
            initStream(iterator.next());
            return super.nextKeyValue();
        }

        return false;
    } else {
        return false;
    }
}

From source file:io.sledge.core.impl.installer.SledgePackageConfigurer.java

private void createNewZipfileWithReplacedPlaceholders(InputStream packageStream, Path configurationPackagePath,
        Properties envProps) throws IOException {

    // For reading the original configuration package
    ZipInputStream configPackageZipStream = new ZipInputStream(new BufferedInputStream(packageStream),
            Charset.forName("UTF-8"));

    // For outputting the configured (placeholders replaced) version of the package as zip file
    File outZipFile = configurationPackagePath.toFile();
    ZipOutputStream outConfiguredZipStream = new ZipOutputStream(new FileOutputStream(outZipFile));

    ZipEntry zipEntry;/*w  w w .j a va 2s  .co m*/
    while ((zipEntry = configPackageZipStream.getNextEntry()) != null) {

        if (zipEntry.isDirectory()) {
            configPackageZipStream.closeEntry();
            continue;
        } else {
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            int length;
            byte[] buffer = new byte[2048];
            while ((length = configPackageZipStream.read(buffer, 0, buffer.length)) >= 0) {
                output.write(buffer, 0, length);
            }

            InputStream zipEntryInputStream = new BufferedInputStream(
                    new ByteArrayInputStream(output.toByteArray()));

            if (zipEntry.getName().endsWith("instance.properties")) {
                ByteArrayOutputStream envPropsOut = new ByteArrayOutputStream();
                envProps.store(envPropsOut, "Environment configurations");
                zipEntryInputStream = new BufferedInputStream(
                        new ByteArrayInputStream(envPropsOut.toByteArray()));

            } else if (isTextFile(zipEntry.getName(), zipEntryInputStream)) {
                String configuredContent = StrSubstitutor.replace(output, envProps);
                zipEntryInputStream = new BufferedInputStream(
                        new ByteArrayInputStream(configuredContent.getBytes()));
            }

            // Add to output zip file
            addToZipFile(zipEntry.getName(), zipEntryInputStream, outConfiguredZipStream);

            zipEntryInputStream.close();
            configPackageZipStream.closeEntry();
        }
    }

    outConfiguredZipStream.close();
    configPackageZipStream.close();
}

From source file:org.smartfrog.avalanche.client.sf.compress.ZipUtils.java

/**
 * Unzips a .zip file and places the contents in outputDir
 * /*from w ww  .  j  a  v a  2 s.  c  o m*/
 * @param zipFile
 * @param outputDir
 * @return 
 * @throws IOException
 */
public static boolean unzip(File zipFile, File outputDir) throws IOException {
    ZipInputStream zipInstream;

    String zipFileName = zipFile.getName();
    if (!zipFile.exists()) {
        log.error("The file " + zipFileName + " does not exist");
        return false;
    }
    if (!zipFile.isFile()) {
        log.error("The file " + zipFileName + " is not a file");
        return false;
    }
    if (!outputDir.exists()) {
        log.error("The directory " + outputDir.getPath() + " does not exist");
        return false;
    }
    if (!outputDir.isDirectory()) {
        log.error("The given path " + outputDir.getPath() + " is not a directory");
        return false;
    }
    if (!outputDir.canWrite()) {
        log.error("Cannot write to the directory " + outputDir.getPath());
        return false;
    }

    FileInputStream in = new FileInputStream(zipFile);
    BufferedInputStream src = new BufferedInputStream(in);
    zipInstream = new ZipInputStream(src);

    byte[] buffer = new byte[chunkSize];
    int len = 0;

    // Loop through the entries in the ZIP archive and read
    // each compressed file.
    do {
        // Need to read the ZipEntry for each file in the archive
        ZipEntry zipEntry = zipInstream.getNextEntry();
        if (zipEntry == null)
            break;

        // Use the ZipEntry name as that of the compressed file.
        File outputFile = new File(outputDir, zipEntry.getName());

        FileOutputStream out = new FileOutputStream(outputFile);
        BufferedOutputStream destination = new BufferedOutputStream(out, chunkSize);

        while ((len = zipInstream.read(buffer, 0, chunkSize)) != -1)
            destination.write(buffer, 0, len);

        destination.flush();
        out.close();
    } while (true);

    zipInstream.close();

    log.info("Unzipped the file " + zipFileName);
    return true;
}

From source file:org.brandroid.openmanager.util.FileManager.java

/**
 * /*from w w w. j  a v  a  2s  .  c om*/
 * @param zip_file
 * @param directory
 */
public void extractZipFiles(OpenPath zip, OpenPath directory) {
    byte[] data = new byte[BUFFER];
    ZipEntry entry;
    ZipInputStream zipstream;

    directory.mkdir();

    try {
        zipstream = new ZipInputStream(zip.getInputStream());

        while ((entry = zipstream.getNextEntry()) != null) {
            OpenPath newFile = directory.getChild(entry.getName());
            if (!newFile.mkdir())
                continue;

            int read = 0;
            FileOutputStream out = null;
            try {
                out = (FileOutputStream) newFile.getOutputStream();
                while ((read = zipstream.read(data, 0, BUFFER)) != -1)
                    out.write(data, 0, read);
            } catch (Exception e) {
                Logger.LogError("Error unzipping " + zip.getAbsolutePath(), e);
            } finally {
                zipstream.closeEntry();
                if (out != null)
                    out.close();
            }
        }

    } catch (FileNotFoundException e) {
        Logger.LogError("Couldn't find file.", e);

    } catch (IOException e) {
        Logger.LogError("Couldn't extract zip.", e);
    }
}