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:com.glaf.core.entity.mybatis.MyBatisSessionFactory.java

public static Map<String, byte[]> getLibMappers() {
    List<String> includes = new ArrayList<String>();
    includes.add("Mapper.xml");
    Map<String, byte[]> dataMap = new HashMap<String, byte[]>();
    String path = SystemProperties.getConfigRootPath() + "/lib";
    File dir = new File(path);
    File contents[] = dir.listFiles();
    if (contents != null) {
        ZipInputStream zipInputStream = null;
        for (int i = 0; i < contents.length; i++) {
            if (contents[i].isFile() && contents[i].getName().startsWith("glaf")
                    && contents[i].getName().endsWith(".jar")) {
                try {
                    zipInputStream = new ZipInputStream(
                            FileUtils.getInputStream(contents[i].getAbsolutePath()));
                    Map<String, byte[]> zipMap = getZipBytesMap(zipInputStream);
                    if (zipMap != null && !zipMap.isEmpty()) {
                        dataMap.putAll(zipMap);
                    }/*from  w w  w  . java  2s. co m*/
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    return dataMap;
}

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

@Test
public void modificationTimesExceedShort() throws Exception {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] data = "data1".getBytes(Charsets.UTF_8);
    try (ZipOutputStream out = new ZipOutputStream(byteArrayOutputStream)) {
        for (long i = 0; i < Short.MAX_VALUE + 1; i++) {
            ZipEntry entry = new ZipEntry("file" + i);
            entry.setSize(data.length);//from   w w  w  .jav  a2 s  .  c  o m
            out.putNextEntry(entry);
            out.write(data);
            out.closeEntry();
        }
    }

    byte[] bytes = byteArrayOutputStream.toByteArray();
    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:be.fedict.eid.dss.document.zip.ZIPDSSDocumentService.java

public DocumentVisualization visualizeDocument(byte[] document, String language, List<MimeType> mimeTypes,
        String documentViewerServlet) throws Exception {

    // get i18n/*from   ww w  .  ja  va2  s  . c o m*/
    ResourceBundle zipResourceBundle = ResourceBundle.getBundle("ZIPMessages", new Locale(language));

    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
    ZipEntry zipEntry;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("<html>");
    stringBuilder.append("<head>");
    stringBuilder.append("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">");
    stringBuilder.append("<title>ZIP package</title>");
    stringBuilder.append("</head>");
    stringBuilder.append("<body>");
    stringBuilder.append(String.format("<h2>%s</h2>", zipResourceBundle.getObject("zipTitle")));
    stringBuilder.append("<table>");
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (ODFUtil.isSignatureFile(zipEntry)) {
            continue;
        }
        String zipEntryName = zipEntry.getName();

        boolean browserViewable = MimeTypeMapper.browserViewable(mimeTypes, zipEntryName);
        String image = browserViewable ? "view.png" : "download.png";

        stringBuilder.append("<tr>");
        stringBuilder.append("<td>");
        stringBuilder.append(String.format("<a href=\"%s\" target=_blank>",
                documentViewerServlet + getResourceId(zipEntry)));
        stringBuilder.append(
                "<img src=\"./images/" + image + "\" style=\" width: 25px; vertical-align: bottom;\" />");
        stringBuilder.append(zipEntryName);
        stringBuilder.append("</a>");

        stringBuilder.append("</td>");
        stringBuilder.append("</tr>");
    }
    stringBuilder.append("</table>");
    stringBuilder.append("</body></html>");

    return new DocumentVisualization("text/html;charset=utf-8", stringBuilder.toString().getBytes());
}

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

protected void initStream(InputSplit inSplit) throws IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Starting " + file);
    }//  www.j  a  v a  2 s. c o  m
    setFile(((FileSplit) inSplit).getPath());

    FSDataInputStream fileIn = fs.open(file);

    String codecString = conf.get(ConfigConstants.CONF_INPUT_COMPRESSION_CODEC, CompressionCodec.ZIP.toString())
            .toUpperCase();
    codec = CompressionCodec.valueOf(codecString);
    switch (codec) {
    case ZIP:
        zipIn = new ZipInputStream(fileIn);
        break;
    case GZIP:
        zipIn = new GZIPInputStream(fileIn);
        String uri = makeURIFromPath(file);
        if (uri.toLowerCase().endsWith(".gz") || uri.toLowerCase().endsWith(".gzip")) {
            uri = uri.substring(0, uri.lastIndexOf('.'));
        }
        setKey(uri, 0, 0, true);
        break;
    default:
        String error = "Unsupported codec: " + codec.name();
        LOG.error(error, new UnsupportedOperationException(error));
    }
}

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

public void initializeMap() throws IOException {
    System.out.println("Entering method ProjectZipConstructor.initializeMap()");
    InputStream skeletonIS = this.getClass().getClassLoader().getResourceAsStream(SKELETON_JAR_FILENAME);
    ZipInputStream zis = new ZipInputStream(skeletonIS);
    ZipEntry ze;// w w  w .j  ava 2 s  . c  om
    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:mj.ocraptor.extraction.tika.parser.epub.EpubParser.java

public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {
    // Because an EPub file is often made up of multiple XHTML files,
    // we need explicit control over the start and end of the document
    XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
    xhtml.startDocument();/*from   ww  w.j  a  va2s.co m*/
    ContentHandler childHandler = new EmbeddedContentHandler(new BodyContentHandler(xhtml));

    ZipInputStream zip = new ZipInputStream(stream);
    ZipEntry entry = zip.getNextEntry();

    TikaImageHelper helper = new TikaImageHelper(metadata);
    try {
        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("metadata.xml")) {
                meta.parse(zip, new DefaultHandler(), metadata, context);
            } else if (entry.getName().endsWith(".opf")) {
                meta.parse(zip, new DefaultHandler(), metadata, context);
            } else if (entry.getName().endsWith(".html") || entry.getName().endsWith(".xhtml")) {
                content.parse(zip, childHandler, metadata, context);
            }
            entry = zip.getNextEntry();
        }
        helper.addTextToHandler(xhtml);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (helper != null) {
            helper.close();
        }
    }

    // Finish everything
    xhtml.endDocument();
}

From source file:io.card.development.recording.Recording.java

private static Hashtable<String, byte[]> unzipFiles(InputStream recordingStream) throws IOException {
    ZipEntry zipEntry;//from  w  ww. ja  v a2 s .  co  m
    ZipInputStream zis = new ZipInputStream(recordingStream);
    Hashtable<String, byte[]> fileHash = new Hashtable<String, byte[]>();
    byte[] buffer = new byte[512];

    while ((zipEntry = zis.getNextEntry()) != null) {
        if (!zipEntry.isDirectory()) {
            int read = 0;
            ByteArrayOutputStream fileStream = new ByteArrayOutputStream();

            do {
                read = zis.read(buffer, 0, buffer.length);
                if (read != -1) {
                    fileStream.write(buffer, 0, read);
                }
            } while (read != -1);

            byte[] fileData = fileStream.toByteArray();
            fileHash.put(zipEntry.getName(), fileData);
        }
    }

    return fileHash;
}

From source file:com.heliosdecompiler.helios.controller.files.OpenedFile.java

private void readQuick() {
    byte[] fileData;

    try {/*from w  w  w  . j a v  a 2 s  . c o  m*/
        fileData = Files.readAllBytes(this.target);
    } catch (IOException e) {
        this.messageHandler.handleException(Message.ERROR_IOEXCEPTION_OCCURRED.format(), e);
        return;
    }

    this.fileContents.clear();
    this.fileContents = new HashMap<>();

    try (ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(fileData))) {
        ZipEntry entry;
        while ((entry = zipInputStream.getNextEntry()) != null) {
            // todo warn about CRC
            if (!entry.isDirectory()) {
                this.fileContents.put(entry.getName(), IOUtils.toByteArray(zipInputStream));
            }
        }
    } catch (Exception ex) {
        this.messageHandler.handleException(Message.ERROR_UNKNOWN_ERROR.format(), ex);
        return;
    }

    // If files is still empty, then it's not a zip file (or something weird happened)
    if (this.fileContents.size() == 0) {
        this.fileContents.put(this.target.toString(), fileData);
    }
}

From source file:de.marius_oe.cfs.cryption.Crypter.java

/**
 * Decrypts the given input stream and stores the decrypted bytes in the
 * destinationFile. If compressStream is <code>true</code>, the given stream
 * has been compressed and is uncompressed after decryption.
 *
 * @param inStream/*from www  . j  a v  a  2  s. c  om*/
 *            source stream with encrypted data and iv at the beginning
 * @param destinationStream
 *            stream for the decrypted data
 * @param compressStream
 *            whether the stream was compressed before encryption
 */
public static void decrypt(InputStream inStream, OutputStream destinationStream, boolean compressStream) {
    logger.debug("decrypting inputstream - compressed: {}", compressStream);

    try {
        // reading iv of stream
        int ivLength = inStream.read();
        byte[] iv = new byte[ivLength];
        inStream.read(iv);

        logger.debug("Decrypt InputStream.");
        inStream = new CipherInputStream(inStream, getCipher(Cipher.DECRYPT_MODE, iv));

        if (compressStream) {
            logger.debug("Decompress InputStream.");

            try {
                inStream = new ZipInputStream(inStream);
                ((ZipInputStream) inStream).getNextEntry();
            } catch (IOException e) {
                logger.debug("Error occured during unzipping - Reason: {}", e.getLocalizedMessage());
                throw new RuntimeException(e);
            }
        }

        // copy stream
        int bytesCopied = IOUtils.copy(inStream, destinationStream);

        logger.debug("decryption done. copied {} decrypted bytes to the outputstream", bytesCopied);

        inStream.close();
        destinationStream.close();
    } catch (IOException e) {
        logger.error("Decryption failed - Reason: {}", e.getLocalizedMessage());
        throw new RuntimeException(e);
    }
}

From source file:ml.shifu.shifu.util.IndependentTreeModelUtils.java

public boolean convertZipSpecToBinary(File zipSpecFile, File outputGbtFile) {
    ZipInputStream zipInputStream = null;
    FileOutputStream fos = null;// www.j  ava  2  s.  c  o m

    try {
        zipInputStream = new ZipInputStream(new FileInputStream(zipSpecFile));
        IndependentTreeModel treeModel = null;
        List<List<TreeNode>> trees = null;

        ZipEntry zipEntry = null;
        do {
            zipEntry = zipInputStream.getNextEntry();
            if (zipEntry != null) {
                if (zipEntry.getName().equals(MODEL_CONF)) {
                    ByteArrayOutputStream byos = new ByteArrayOutputStream();
                    IOUtils.copy(zipInputStream, byos);
                    treeModel = JSONUtils.readValue(new ByteArrayInputStream(byos.toByteArray()),
                            IndependentTreeModel.class);
                } else if (zipEntry.getName().equals(MODEL_TREES)) {
                    DataInputStream dataInputStream = new DataInputStream(zipInputStream);
                    int size = dataInputStream.readInt();
                    trees = new ArrayList<List<TreeNode>>(size);
                    for (int i = 0; i < size; i++) {
                        int forestSize = dataInputStream.readInt();
                        List<TreeNode> forest = new ArrayList<TreeNode>(forestSize);
                        for (int j = 0; j < forestSize; j++) {
                            TreeNode treeNode = new TreeNode();
                            treeNode.readFields(dataInputStream);
                            forest.add(treeNode);
                        }
                        trees.add(forest);
                    }
                }
            }
        } while (zipEntry != null);

        if (treeModel != null && CollectionUtils.isNotEmpty(trees)) {
            treeModel.setTrees(trees);
            fos = new FileOutputStream(outputGbtFile);
            treeModel.saveToInputStream(fos);
        } else {
            return false;
        }
    } catch (IOException e) {
        logger.error("Error occurred when convert the zip format model to binary.", e);
        return false;
    } finally {
        IOUtils.closeQuietly(zipInputStream);
        IOUtils.closeQuietly(fos);
    }

    return true;
}