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:mj.ocraptor.extraction.tika.parser.odf.OpenDocumentParser.java

public void parse(InputStream stream, ContentHandler baseHandler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {

    // TODO: reuse the already opened ZIPFile, if
    // present//from   w  w w  .j av a 2  s.  c o  m

    /*
     * ZipFile zipFile; if (stream instanceof TikaInputStream) { TikaInputStream
     * tis = (TikaInputStream) stream; Object container = ((TikaInputStream)
     * stream).getOpenContainer(); if (container instanceof ZipFile) { zipFile =
     * (ZipFile) container; } else if (tis.hasFile()) { zipFile = new
     * ZipFile(tis.getFile()); } }
     */

    // TODO: if incoming IS is a TIS with a file
    // associated, we should open ZipFile so we can
    // visit metadata, mimetype first; today we lose
    // all the metadata if meta.xml is hit after
    // content.xml in the stream. Then we can still
    // read-once for the content.xml.

    XHTMLContentHandler xhtml = new XHTMLContentHandler(baseHandler, metadata);

    // As we don't know which of the metadata or the content
    // we'll hit first, catch the endDocument call initially
    EndDocumentShieldingContentHandler handler = new EndDocumentShieldingContentHandler(xhtml);

    TikaImageHelper helper = new TikaImageHelper(metadata);
    try {
        // Process the file in turn
        ZipInputStream zip = new ZipInputStream(stream);
        ZipEntry entry = zip.getNextEntry();
        while (entry != null) {
            // TODO: images
            String entryExtension = null;
            try {
                entryExtension = FilenameUtils.getExtension(new File(entry.getName()).getName());
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (entryExtension != null && FileType.isValidImageFileExtension(entryExtension)
                    && Config.inst().getProp(ConfigBool.ENABLE_IMAGE_OCR)) {
                File imageFile = null;
                try {
                    imageFile = TikaImageHelper.saveZipEntryToTemp(zip, entry);
                    helper.addImage(imageFile);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (imageFile != null) {
                        imageFile.delete();
                    }
                }
            } else if (entry.getName().equals("mimetype")) {
                String type = IOUtils.toString(zip, "UTF-8");
                metadata.set(Metadata.CONTENT_TYPE, type);
            } else if (entry.getName().equals("meta.xml")) {
                meta.parse(zip, new DefaultHandler(), metadata, context);
            } else if (entry.getName().endsWith("content.xml")) {
                if (content instanceof OpenDocumentContentParser) {
                    ((OpenDocumentContentParser) content).parseInternal(zip, handler, metadata, context);
                } else {
                    // Foreign content parser was set:
                    content.parse(zip, handler, metadata, context);
                }
            } else if (entry.getName().endsWith("styles.xml")) {
                if (content instanceof OpenDocumentContentParser) {
                    ((OpenDocumentContentParser) content).parseInternal(zip, handler, metadata, context);
                } else {
                    // Foreign content parser was set:
                    content.parse(zip, handler, metadata, context);
                }
            }
            entry = zip.getNextEntry();
        }
        helper.addTextToHandler(xhtml);
    } catch (Exception e) {
        LOG.info("Extract error", e);
    } finally {
        if (helper != null) {
            helper.close();
        }
    }

    // Only now call the end document
    if (handler.getEndDocumentWasCalled()) {
        handler.reallyEndDocument();
    }
}

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

public void initializeMap() throws IOException {
    log.log(Level.INFO, "Entering method ProjectConstructor.initializeMap()");
    InputStream skeletonIS = this.getClass().getClassLoader().getResourceAsStream(SKELETON_FILENAME);
    ZipInputStream zis = new ZipInputStream(skeletonIS);
    ZipEntry ze;//w w  w . j a  v a2s  . c o 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:io.fabric8.maven.generator.springboot.SpringBootGenerator.java

private void copyFilesToFatJar(List<File> libs, List<File> classes, File target) throws IOException {
    File tmpZip = File.createTempFile(target.getName(), null);
    tmpZip.delete();// w  w  w.j a v  a 2 s . c o  m

    // Using Apache commons rename, because renameTo has issues across file systems
    FileUtils.moveFile(target, tmpZip);

    byte[] buffer = new byte[8192];
    ZipInputStream zin = new ZipInputStream(new FileInputStream(tmpZip));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(target));
    for (ZipEntry ze = zin.getNextEntry(); ze != null; ze = zin.getNextEntry()) {
        if (matchesFatJarEntry(libs, ze.getName(), true) || matchesFatJarEntry(classes, ze.getName(), false)) {
            continue;
        }
        out.putNextEntry(ze);
        for (int read = zin.read(buffer); read > -1; read = zin.read(buffer)) {
            out.write(buffer, 0, read);
        }
        out.closeEntry();
    }

    for (File lib : libs) {
        try (InputStream in = new FileInputStream(lib)) {
            out.putNextEntry(createZipEntry(lib, getFatJarFullPath(lib, true)));
            for (int read = in.read(buffer); read > -1; read = in.read(buffer)) {
                out.write(buffer, 0, read);
            }
            out.closeEntry();
        }
    }

    for (File cls : classes) {
        try (InputStream in = new FileInputStream(cls)) {
            out.putNextEntry(createZipEntry(cls, getFatJarFullPath(cls, false)));
            for (int read = in.read(buffer); read > -1; read = in.read(buffer)) {
                out.write(buffer, 0, read);
            }
            out.closeEntry();
        }
    }

    out.close();
    tmpZip.delete();
}

From source file:ZipUtil.java

public static void unZipZipFileToLocation(File zipFile, File targetDir) throws IOException {
    if (!targetDir.isDirectory()) {
        throw new Exception("Target is not a directory.");
    }//from w  ww  . j a va2  s  .  c o  m
    FileInputStream flInStr = new FileInputStream(zipFile);
    try {
        ZipInputStream zis = new ZipInputStream(flInStr);
        try {
            ZipEntry entry = null;
            while ((entry = zis.getNextEntry()) != null) {
                String name = entry.getName();
                File newFile = new File(targetDir, name);
                if (entry.isDirectory() && !newFile.exists()) {
                    newFile.mkdirs();
                } else if (!entry.isDirectory()) {
                    if (newFile.exists()) {
                        newFile.delete();
                    }
                    File parentDir = newFile.getParentFile();
                    if (!parentDir.exists()) {
                        parentDir.mkdirs();
                    }
                    FileOutputStream stmOut = new FileOutputStream(newFile);
                    try {
                        simpleInputStreamToOutputStream(zis, stmOut);
                    } finally {
                        stmOut.close();
                    }
                }
            } //end while.
        } finally {
            zis.close();
        }
    } finally {
        flInStr.close();
    }
}

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

public static byte[] getBytes(InputStream inputStream, String name) {
    byte[] bytes = null;
    ZipInputStream zipInputStream = null;
    try {/*from   w  w w.  j a v  a2  s .  c  om*/
        zipInputStream = new ZipInputStream(inputStream);
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        while (zipEntry != null) {
            String entryName = zipEntry.getName();
            if (entryName.equalsIgnoreCase(name)) {
                bytes = FileUtils.getBytes(zipInputStream);
                if (bytes != null) {
                    break;
                }
            }
            zipEntry = zipInputStream.getNextEntry();
        }
        return bytes;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(zipInputStream);
    }
}

From source file:dk.dma.ais.reader.AisReaders.java

static InputStream createFileInputStream(String filename) throws IOException {
    InputStream in = new FileInputStream(filename);
    if (filename.endsWith(".gz")) {
        in = new GZIPInputStream(in);
    } else if (filename.endsWith(".zip")) {
        // TODO: currently only reads the first zip entry
        in = new ZipInputStream(in);
        ((ZipInputStream) in).getNextEntry();
    }//  www  . ja v a 2s  .  c o m

    return in;
}

From source file:be.fedict.eid.dss.document.odf.ODFDSSDocumentService.java

private void checkIntegrity(XMLSignature xmlSignature, byte[] document, byte[] originalDocument)
        throws IOException {
    if (null != originalDocument) {
        throw new IllegalArgumentException("cannot perform original document verifications");
    }//from   w  w  w.  j av a2  s . c  om
    Set<String> dsReferenceUris = new HashSet<String>();
    SignedInfo signedInfo = xmlSignature.getSignedInfo();
    @SuppressWarnings("unchecked")
    List<Reference> references = signedInfo.getReferences();
    for (Reference reference : references) {
        String referenceUri = reference.getURI();
        dsReferenceUris.add(referenceUri);
    }
    ZipInputStream odfZipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
    ZipEntry zipEntry;
    while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
        if (false == ODFUtil.isToBeSigned(zipEntry)) {
            continue;
        }
        String uri = zipEntry.getName().replaceAll(" ", "%20");
        if (false == dsReferenceUris.contains(uri)) {
            LOG.warn("no ds:Reference for ODF entry: " + zipEntry.getName());
            throw new RuntimeException("no ds:Reference for ODF entry: " + zipEntry.getName());
        }
    }
}

From source file:com.comcast.magicwand.spells.web.chrome.ChromePhoenixDriver.java

private void extractZip(File sourceZipFile, String destinationDir) throws IOException {
    LOG.debug("Extracting [{}] to dir [{}]", sourceZipFile, destinationDir);
    ZipInputStream zis = null;/*from w  ww.j a  v a2  s . c o  m*/
    ZipEntry entry;

    try {
        zis = new ZipInputStream(FileUtils.openInputStream(sourceZipFile));

        while (null != (entry = zis.getNextEntry())) {
            File dst = Paths.get(destinationDir, entry.getName()).toFile();

            FileOutputStream output = FileUtils.openOutputStream(dst);
            try {
                IOUtils.copy(zis, output);
                output.close();
            } finally {
                IOUtils.closeQuietly(output);
            }
        }
        zis.close();
    } finally {
        IOUtils.closeQuietly(zis);
    }
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.Utils.java

public static byte[] getShapeDataFromZip(byte[] localSourceData) {
    byte[] data = null;
    InputStream in = new ByteArrayInputStream(localSourceData);
    ZipInputStream zis = new ZipInputStream(in);
    ZipEntry ze;/*from w  w  w  .j a  v  a 2  s  .c o  m*/
    try {
        while ((ze = zis.getNextEntry()) != null) {
            if (!ze.isDirectory()) {
                String fileName = ze.getName().toLowerCase();
                if (fileName.endsWith(".shp")) {
                    long entrySize = ze.getSize();
                    if (entrySize != -1) {
                        data = IOUtils.toByteArray(zis, entrySize);
                        break;
                    }
                }
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            zis.closeEntry();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            zis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return data;
}

From source file:com.bemis.portal.fileuploader.service.impl.FileUploaderLocalServiceImpl.java

public void uploadFiles(long companyId, long groupId, long userId, File file, long fileTypeId,
        String[] assetTagNames) throws IOException, PortalException {

    String fileName = file.getName();

    if (!fileName.endsWith(".zip")) {
        if (_log.isWarnEnabled()) {
            _log.warn(">>> Unsupported compressed file type. Supports ZIP" + "compressed files only. ");
        }/*from  w ww  . j a v a 2  s .  c om*/

        throw new FileUploaderException("error.unsupported-file-type");
    }

    DataOutputStream outputStream = null;

    try (ZipInputStream inputStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)))) {

        ZipEntry fileEntry;
        while ((fileEntry = inputStream.getNextEntry()) != null) {
            boolean isDir = fileEntry.isDirectory();
            boolean isSubDirFile = fileEntry.getName().contains(SLASH);

            if (isDir || isSubDirFile) {
                if (_log.isWarnEnabled()) {
                    _log.warn(">>> Directory found inside the zip file " + "uploaded.");
                }

                continue;
            }

            String fileEntryName = fileEntry.getName();

            String extension = PERIOD + FileUtil.getExtension(fileEntryName);

            File tempFile = null;

            try {
                tempFile = File.createTempFile("tempfile", extension);

                byte[] buffer = new byte[INPUT_BUFFER];

                outputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tempFile)));

                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.flush();

                String fileDescription = BLANK;
                String changeLog = BLANK;

                uploadFile(companyId, groupId, userId, tempFile, fileDescription, fileEntryName, fileTypeId,
                        changeLog, assetTagNames);
            } finally {
                StreamUtil.cleanUp(outputStream);

                if ((tempFile != null) && tempFile.exists()) {
                    tempFile.delete();
                }
            }
        }
    } catch (FileNotFoundException fnfe) {
        if (_log.isWarnEnabled()) {
            _log.warn(">>> Unable to upload files" + fnfe);
        }
    }
}