Example usage for java.util.zip ZipInputStream ZipInputStream

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

Introduction

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

Prototype

public ZipInputStream(InputStream in) 

Source Link

Document

Creates a new ZIP input stream.

Usage

From source file:net.famzangl.minecraft.minebot.settings.MinebotDirectoryCreator.java

public File createDirectory(File dir) throws IOException {
    CodeSource src = MinebotDirectoryCreator.class.getProtectionDomain().getCodeSource();
    if (src != null) {
        URL jar = src.getLocation();
        if (jar.getFile().endsWith("class") && !jar.getFile().contains(".jar!")) {
            System.out.println("WARNING: Using the dev directory for settings.");
            // We are in a dev enviroment.
            return new File(new File(jar.getFile()).getParentFile(), "minebot");
        }//from ww  w .j  ava2 s. c om
        if (dir.isFile()) {
            dir.delete();
        }

        dir.mkdirs();
        ZipInputStream zip = new ZipInputStream(jar.openStream());
        try {
            ZipEntry zipEntry;
            while ((zipEntry = zip.getNextEntry()) != null) {
                String name = zipEntry.getName();
                if (name.startsWith(BASE)) {
                    String[] localName = name.substring(BASE.length()).split("/");
                    File currentDir = dir;
                    for (int i = 0; i < localName.length; i++) {
                        currentDir = new File(currentDir, localName[i]);
                        currentDir.mkdir();
                    }
                    File copyTo = new File(currentDir, localName[localName.length - 1]);
                    extract(zip, copyTo);
                }
            }
        } finally {
            zip.close();
        }
        return dir;
    } else {
        throw new IOException("Could not find minebot directory to extract.");
    }
}

From source file:com.seer.datacruncher.spring.ValidateFilePopupController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String idSchema = request.getParameter("idSchema");
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("file");
    String resMsg = "";

    if (multipartFile.getOriginalFilename().endsWith(FileExtensionType.ZIP.getAbbreviation())) {
        // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one      
        ZipInputStream inStream = null;
        try {/*from   ww w  .  ja  va  2 s  .c om*/
            inStream = new ZipInputStream(multipartFile.getInputStream());
            ZipEntry entry;
            while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    DatastreamsInput datastreamsInput = new DatastreamsInput();
                    datastreamsInput.setUploadedFileName(entry.getName());
                    byte[] byteInput = IOUtils.toByteArray(inStream);
                    resMsg += datastreamsInput.datastreamsInput(new String(byteInput), Long.parseLong(idSchema),
                            byteInput);
                }
                inStream.closeEntry();
            }
        } catch (IOException ex) {
            resMsg = "Error occured during fetch records from ZIP file.";
        } finally {
            if (inStream != null)
                inStream.close();
        }
    } else {
        // Case 1: When user upload a single file. In this cae just validate a single stream 
        String datastream = new String(multipartFile.getBytes());
        DatastreamsInput datastreamsInput = new DatastreamsInput();
        datastreamsInput.setUploadedFileName(multipartFile.getOriginalFilename());

        resMsg = datastreamsInput.datastreamsInput(datastream, Long.parseLong(idSchema),
                multipartFile.getBytes());

    }
    String msg = resMsg.replaceAll("'", "\"").replaceAll("\\n", " ");
    msg = msg.trim();
    response.setContentType("text/html");
    ServletOutputStream out = null;
    out = response.getOutputStream();
    out.write(("{success: " + true + " , message:'" + msg + "',   " + "}").getBytes());
    out.flush();
    out.close();
    return null;
}

From source file:com.ccoe.build.utils.CompressUtils.java

/**
 * Uncompress a zip to files/*www.j  ava 2  s  .  c o m*/
 * @param zip
 * @param unzipdir
 * @param isNeedClean
 * @return
 * @throws FileNotFoundException 
 * @throws IOException 
 */
public static List<File> unCompress(File zip, String unzipdir) throws IOException {
    ArrayList<File> unzipfiles = new ArrayList<File>();

    FileInputStream fi = new FileInputStream(zip);
    ZipInputStream zi = new ZipInputStream(new BufferedInputStream(fi));
    try {

        ZipEntry entry;
        while ((entry = zi.getNextEntry()) != null) {
            System.out.println("Extracting: " + entry);
            int count;
            byte data[] = new byte[BUFFER];
            File unzipfile = new File(unzipdir + File.separator + entry.getName());
            FileOutputStream fos = new FileOutputStream(unzipfile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);

            while ((count = zi.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();

            unzipfiles.add(unzipfile);
        }

    } catch (IOException e) {
        throw e;
    } finally {
        IOUtils.closeQuietly(zi);
    }

    return unzipfiles;
}

From source file:com.facebook.buck.util.zip.ZipScrubberTest.java

@Test
public void modificationTimes() throws Exception {

    // Create a dummy ZIP file.
    ByteArrayOutputStream bytesOutputStream = new ByteArrayOutputStream();
    try (ZipOutputStream out = new ZipOutputStream(bytesOutputStream)) {
        ZipEntry entry = new ZipEntry("file1");
        byte[] data = "data1".getBytes(Charsets.UTF_8);
        entry.setSize(data.length);//  www. j a  v a 2s . com
        out.putNextEntry(entry);
        out.write(data);
        out.closeEntry();

        entry = new ZipEntry("file2");
        data = "data2".getBytes(Charsets.UTF_8);
        entry.setSize(data.length);
        out.putNextEntry(entry);
        out.write(data);
        out.closeEntry();
    }

    byte[] bytes = bytesOutputStream.toByteArray();
    // Execute the zip scrubber step.
    ZipScrubber.scrubZipBuffer(bytes.length, ByteBuffer.wrap(bytes));

    // Iterate over each of the entries, expecting to see all zeros in the time fields.
    Date dosEpoch = new Date(ZipUtil.dosToJavaTime(ZipConstants.DOS_FAKE_TIME));
    try (ZipInputStream is = new ZipInputStream(new ByteArrayInputStream(bytes))) {
        for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
            assertThat(entry.getName(), new Date(entry.getTime()), Matchers.equalTo(dosEpoch));
        }
    }
}

From source file:com.jivesoftware.os.routing.bird.endpoints.base.LocateStringResource.java

String getStringResource() {
    Map<String, Long> htSizes = new HashMap<>();
    try {/*from w  w w .j  av  a2 s.  c  o m*/
        try (final ZipFile zf = new ZipFile(jarFileName)) {
            Enumeration<? extends ZipEntry> e = zf.entries();
            while (e.hasMoreElements()) {
                ZipEntry ze = e.nextElement();
                if (!ze.getName().equals(resourceName)) {
                    continue;
                }
                htSizes.put(ze.getName(), ze.getSize());
            }
        }
        // extract resources and put them into the hashtable.
        FileInputStream fis = new FileInputStream(jarFileName);
        BufferedInputStream bis = new BufferedInputStream(fis);
        try (final ZipInputStream zis = new ZipInputStream(bis)) {
            ZipEntry ze;
            while ((ze = zis.getNextEntry()) != null) {
                if (!ze.getName().equals(resourceName)) {
                    continue;
                }
                if (ze.isDirectory()) {
                    continue;
                }
                int size = (int) ze.getSize();
                // -1 means unknown size.
                if (size == -1) {
                    size = htSizes.get(ze.getName()).intValue();
                }
                byte[] b = new byte[size];
                int rb = 0;
                int chunk = 0;
                while ((size - rb) > 0) {
                    chunk = zis.read(b, rb, size - rb);
                    if (chunk == -1) {
                        break;
                    }
                    rb += chunk;
                }
                InputStream inputStream = new ByteArrayInputStream(b);
                StringWriter writer = new StringWriter();
                IOUtils.copy(inputStream, writer, "UTF-8");
                return writer.toString();
            }
        }
    } catch (Exception e) {
        LOG.warn("Failed to locate " + resourceName, e);
    }
    return null;
}

From source file:io.lightlink.excel.StreamingExcelTransformer.java

public void doExport(InputStream template, OutputStream out, ExcelStreamVisitor visitor) throws IOException {
    try {/*from w w  w  .  ja  va 2  s.c om*/
        ZipInputStream zipIn = new ZipInputStream(template);
        ZipOutputStream zipOut = new ZipOutputStream(out);

        ZipEntry entry;

        Map<String, byte[]> sheets = new HashMap<String, byte[]>();

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

            String name = entry.getName();

            if (name.startsWith("xl/sharedStrings.xml")) {

                byte[] bytes = IOUtils.toByteArray(zipIn);
                zipOut.putNextEntry(new ZipEntry(name));
                zipOut.write(bytes);

                sharedStrings = processSharedStrings(bytes);

            } else if (name.startsWith("xl/worksheets/sheet")) {
                byte[] bytes = IOUtils.toByteArray(zipIn);
                sheets.put(name, bytes);
            } else if (name.equals("xl/calcChain.xml")) {
                // skip this file, let excel recreate it
            } else if (name.equals("xl/workbook.xml")) {
                zipOut.putNextEntry(new ZipEntry(name));

                SAXParserFactory factory = SAXParserFactory.newInstance();
                SAXParser saxParser = factory.newSAXParser();
                Writer writer = new OutputStreamWriter(zipOut, "UTF-8");

                byte[] bytes = IOUtils.toByteArray(zipIn);
                saxParser.parse(new ByteArrayInputStream(bytes), new WorkbookTemplateHandler(writer));

                writer.flush();
            } else {
                zipOut.putNextEntry(new ZipEntry(name));
                IOUtils.copy(zipIn, zipOut);
            }

        }

        for (Map.Entry<String, byte[]> sheetEntry : sheets.entrySet()) {
            String name = sheetEntry.getKey();

            byte[] bytes = sheetEntry.getValue();
            zipOut.putNextEntry(new ZipEntry(name));
            processSheet(bytes, zipOut, visitor);
        }

        zipIn.close();
        template.close();

        zipOut.close();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.toString(), e);
    }
}

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

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

    byte[] signatureData = toByteArray();

    /*/*from  w  w  w  .j a  va  2  s  .  com*/
     * 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.vividsolutions.jump.io.CompressedFile.java

/**
 * Searches through the .zip file looking for a file with the given extension.
 * Returns null if it doesn't find one.//w  ww.  j  a  v a  2 s.com
 * 
 * @deprecated only used by very old data readers which only deliver the first file in zip file [ede 05.2012]
 */
public static String getInternalZipFnameByExtension(String extension, String compressedFile) throws Exception {
    // zip file
    String inside_zip_extension;
    InputStream IS_low = new FileInputStream(compressedFile);
    ZipInputStream fr_high = new ZipInputStream(IS_low);

    // need to find the correct file within the .zip file
    ZipEntry entry;

    entry = fr_high.getNextEntry();

    while (entry != null) {
        inside_zip_extension = entry.getName().substring(entry.getName().length() - extension.length());

        if (inside_zip_extension.compareToIgnoreCase(extension) == 0) {
            return (entry.getName());
        }

        entry = fr_high.getNextEntry();
    }

    return null;
}

From source file:com.diffplug.gradle.ZipMisc.java

/**
 * Modifies only the specified entries in a zip file. 
 *
 * @param input       a source from a zip file
 * @param output      an output to a zip file
 * @param toModify      a map from path to an input stream for the entries you'd like to change
 * @param toOmit      a set of entries you'd like to leave out of the zip
 * @throws IOException// w  w w . j a  v a 2  s .c om
 */
public static void modify(ByteSource input, ByteSink output, Map<String, Function<byte[], byte[]>> toModify,
        Predicate<String> toOmit) throws IOException {
    try (ZipInputStream zipInput = new ZipInputStream(input.openBufferedStream());
            ZipOutputStream zipOutput = new ZipOutputStream(output.openBufferedStream())) {
        while (true) {
            // read the next entry
            ZipEntry entry = zipInput.getNextEntry();
            if (entry == null) {
                break;
            }

            Function<byte[], byte[]> replacement = toModify.get(entry.getName());
            if (replacement != null) {
                byte[] clean = ByteStreams.toByteArray(zipInput);
                byte[] modified = replacement.apply(clean);
                // if it's the entry being modified, enter the modified stuff
                try (InputStream replacementStream = new ByteArrayInputStream(modified)) {
                    ZipEntry newEntry = new ZipEntry(entry.getName());
                    newEntry.setComment(entry.getComment());
                    newEntry.setExtra(entry.getExtra());
                    newEntry.setMethod(entry.getMethod());
                    newEntry.setTime(entry.getTime());

                    zipOutput.putNextEntry(newEntry);
                    copy(replacementStream, zipOutput);
                }
            } else if (!toOmit.test(entry.getName())) {
                // if it isn't being modified, just copy the file stream straight-up
                ZipEntry newEntry = new ZipEntry(entry);
                newEntry.setCompressedSize(-1);
                zipOutput.putNextEntry(newEntry);
                copy(zipInput, zipOutput);
            }

            // close the entries
            zipInput.closeEntry();
            zipOutput.closeEntry();
        }
    }
}

From source file:de.ingrid.importer.udk.util.Zipper.java

/**
 * Extracts the given ZIP-File and return a vector containing String
 * representation of the extracted files.
 * //from  w  w  w. j  ava 2 s  .  c  o  m
 * @param zipFileName
 *            the name of the ZIP-file
 * @param targetDir
 *            the target directory
 * @param keepSubfolders
 *            boolean parameter, whether to keep the folder structure
 * 
 * @return a Vector<String> containing String representation of the allowed
 *         files from the ZipperFilter.
 * @return null if the input data was invalid or an Exception occurs
 */
public static final List<String> extractZipFile(InputStream myInputStream, final String targetDir,
        final boolean keepSubfolders, ZipperFilter zipperFilter) {
    if (log.isDebugEnabled()) {
        log.debug("extractZipFile: inputStream=" + myInputStream + ", targetDir='" + targetDir
                + "', keepSubfolders=" + keepSubfolders);
    }

    ArrayList<String> extractedFiles = new ArrayList<String>();

    FileOutputStream fos = null;

    File outdir = new File(targetDir);

    // make some checks
    if (outdir.isFile()) {
        String msg = "The Target Directory \"" + outdir + "\" must not be a file .";
        log.error(msg);
        System.err.println(msg);
        return null;
    }

    // create necessary directories for the output directory
    outdir.mkdirs();

    // Start Unzipping ...
    try {
        if (log.isDebugEnabled()) {
            log.debug("Start unzipping");
        }

        ZipInputStream zis = new ZipInputStream(myInputStream);
        if (log.isDebugEnabled()) {
            log.debug("ZipInputStream from InputStream=" + zis);
        }

        // for every zip-entry
        ZipEntry zEntry;
        String name;
        while ((zEntry = zis.getNextEntry()) != null) {
            name = zEntry.toString();
            if (log.isDebugEnabled()) {
                log.debug("Zip Entry name: " + name + ", size:" + zEntry.getSize());
            }

            boolean isDir = name.endsWith(separator);
            // System.out.println("------------------------------");
            // System.out.println((isDir? "<d>":"< >")+name);

            String[] nameSplitted = name.split(separator);

            // If it's a File, take all Splitted Names except the last one
            int len = (isDir ? nameSplitted.length : nameSplitted.length - 1);

            String currStr = targetDir;

            if (keepSubfolders) {

                // create all directories from the entry
                for (int j = 0; j < len; j++) {
                    // System.out.println("Dirs: " + nameSplitted[j]);
                    currStr += nameSplitted[j] + File.separator;
                    // System.out.println("currStr: "+currStr);

                    File currDir = new File(currStr);
                    currDir.mkdirs();

                }
            }

            // if the entry is a file, then create it.
            if (!isDir) {

                // set the file name of the output file.
                String outputFileName = null;
                if (keepSubfolders) {
                    outputFileName = currStr + nameSplitted[nameSplitted.length - 1];
                } else {
                    outputFileName = targetDir + nameSplitted[nameSplitted.length - 1];
                }

                File outputFile = new File(outputFileName);
                fos = new FileOutputStream(outputFile);

                // write the File
                if (log.isDebugEnabled()) {
                    log.debug("Write Zip Entry '" + name + "' to file '" + outputFile + "'");
                }
                writeFile(zis, fos, buffersize);
                if (log.isDebugEnabled()) {
                    log.debug("FILE WRITTEN: " + outputFile.getAbsolutePath());
                }

                // add the file to the vector to be returned

                if (zipperFilter != null) {
                    String[] accFiles = zipperFilter.getAcceptedFiles();
                    String currFileName = outputFile.getAbsolutePath();

                    for (int i = 0; i < accFiles.length; i++) {
                        if (currFileName.endsWith(accFiles[i])) {
                            extractedFiles.add(currFileName);
                        }
                    }

                } else {
                    extractedFiles.add(outputFile.getAbsolutePath());
                }

            }

        } // end while

        zis.close();

    } catch (Exception e) {
        log.error("Problems unzipping file", e);
        e.printStackTrace();
        return null;
    }

    return extractedFiles;
}