Example usage for java.util.zip ZipFile getInputStream

List of usage examples for java.util.zip ZipFile getInputStream

Introduction

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

Prototype

public InputStream getInputStream(ZipEntry entry) throws IOException 

Source Link

Document

Returns an input stream for reading the contents of the specified zip file entry.

Usage

From source file:de.onyxbits.raccoon.appmgr.ExtractWorker.java

@Override
protected File doInBackground() throws Exception {
    ZipFile zip = new ZipFile(source);
    parseResourceTable();/*from  w  w w  .  j a v a2 s .  c o m*/
    if (filenames == null) {
        Enumeration<? extends ZipEntry> e = zip.entries();
        Vector<String> tmp = new Vector<String>();
        while (e.hasMoreElements()) {
            tmp.add(e.nextElement().getName());
        }
        filenames = tmp;
    }

    for (String filename : filenames) {
        ZipEntry entry = zip.getEntry(filename);
        InputStream in = zip.getInputStream(entry);
        OutputStream out = openDestination(filename);

        if (isBinaryXml(filename)) {
            XmlTranslator xmlTranslator = new XmlTranslator();
            ByteBuffer buffer = ByteBuffer.wrap(Utils.toByteArray(in));
            BinaryXmlParser binaryXmlParser = new BinaryXmlParser(buffer, resourceTable);
            binaryXmlParser.setLocale(Locale.getDefault());
            binaryXmlParser.setXmlStreamer(xmlTranslator);
            binaryXmlParser.parse();
            IOUtils.write(xmlTranslator.getXml(), out);
        } else {
            // Simply extract
            IOUtils.copy(in, out);
        }
        in.close();
        out.close();
    }

    zip.close();
    return dest;
}

From source file:org.commonjava.maven.galley.filearc.internal.ZipDownload.java

@Override
public DownloadJob call() {
    final File src = getZipFile();

    if (src.isDirectory()) {
        return this;
    }/*from  w w w.ja v  a  2 s  . com*/

    ZipFile zf = null;
    InputStream in = null;
    OutputStream out = null;
    try {
        zf = isJarOperation() ? new JarFile(src) : new ZipFile(src);

        final ZipEntry entry = zf.getEntry(getFullPath());
        if (entry != null) {
            if (entry.isDirectory()) {
                error = new TransferException("Cannot read stream. Source is a directory: %s!%s",
                        getLocation().getUri(), getFullPath());
            } else {
                in = zf.getInputStream(entry);
                out = getTransfer().openOutputStream(TransferOperation.DOWNLOAD, true, eventMetadata);

                copy(in, out);

                return this;
            }
        } else {
            error = new TransferException("Cannot find entry: %s in: %s", getFullPath(),
                    getLocation().getUri());
        }
    } catch (final IOException e) {
        error = new TransferException("Failed to copy from: %s to: %s. Reason: %s", e, src, getTransfer(),
                e.getMessage());
    } finally {
        closeQuietly(in);
        if (zf != null) {
            //noinspection EmptyCatchBlock
            try {
                zf.close();
            } catch (final IOException e) {
            }
        }

        closeQuietly(out);
    }

    if (error != null) {
        logger.error("Failed to download: {}. Reason: {}", this, error);
    }

    return null;
}

From source file:asciidoc.maven.plugin.AbstractAsciiDocMojo.java

private void unzipEntry(ZipFile zipfile, ZipEntry zipEntry, File outputDir) throws IOException {
    if (zipEntry.isDirectory()) {
        createDir(new File(outputDir, zipEntry.getName()));
        return;//from   w  w w .j a  v a  2s  .c  om
    }
    File outputFile = new File(outputDir, zipEntry.getName());
    if (!outputFile.getParentFile().exists()) {
        createDir(outputFile.getParentFile());
    }
    if (getLog().isDebugEnabled())
        getLog().debug("Extracting " + zipEntry);
    BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(zipEntry));
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
    try {
        IOUtils.copy(inputStream, outputStream);
    } finally {
        outputStream.close();
        inputStream.close();
    }
}

From source file:net.wasdev.maven.plugins.swaggerdocgen.SwaggerProcessor.java

public String getDocument() {
    ZipFile warZipFile = null;
    try {/*from   ww  w . java  2 s  . c  o  m*/
        warZipFile = new ZipFile(warFile);

        // Search for META-INF/swagger.json or META-INF/swagger.yaml in the
        // WAR
        ZipEntry entry = warZipFile.getEntry(DEFAULT_SWAGGER_JSON_LOCATION);
        if (entry == null) {
            entry = warZipFile.getEntry(DEFAULT_SWAGGER_YAML_LOCATION);
        }
        if (entry != null) {
            InputStream swaggerStream = warZipFile.getInputStream(entry);
            String swaggerDoc = getSwaggerDocFromStream(swaggerStream);
            // Swagger swaggerModel = new SwaggerParser().parse(swaggerDoc,
            // null, false);
            Swagger swaggerModel = new SwaggerParser().parse(swaggerDoc, null);

            return createYAMLfromPojo(swaggerModel);
        }

        // Search for META-INF/stub/swagger.json or
        // META-INF/stub/swagger.yaml in the WAR
        Swagger swaggerStubModel = null;
        entry = warZipFile.getEntry(DEFAULT_SWAGGER_JSON_STUB_LOCATION);
        if (entry == null) {
            entry = warZipFile.getEntry(DEFAULT_SWAGGER_YAML_STUB_LOCATION);
        }
        if (entry != null) {
            InputStream swaggerStream = warZipFile.getInputStream(entry);
            String swaggerDoc = getSwaggerDocFromStream(swaggerStream);
            swaggerStubModel = new SwaggerParser().parse(swaggerDoc, null);
        }
        // Scan the WAR for annotations and merge with the stub document.
        return getSwaggerDocFromAnnotatedClasses(warZipFile, swaggerStubModel);
    } catch (IOException ioe) {
        logger.severe("Failed to generate the Swagger document.");
    } finally {
        tryToClose(warZipFile);
    }
    return null;
}

From source file:mobac.mapsources.loader.MapPackManager.java

public int getMapPackRevision(File mapPackFile) throws ZipException, IOException {
    ZipFile zip = new ZipFile(mapPackFile);
    try {// w w w. jav  a2 s  .c o m
        ZipEntry entry = zip.getEntry("META-INF/MANIFEST.MF");
        if (entry == null)
            throw new ZipException("Unable to find MANIFEST.MF");
        Manifest mf = new Manifest(zip.getInputStream(entry));
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackRevision").trim();
        return Utilities.parseSVNRevision(mpv);
    } catch (NumberFormatException e) {
        return -1;
    } finally {
        zip.close();
    }
}

From source file:com.skcraft.launcher.launch.JavaRuntimeFetcher.java

private void extract(File zip, File destination) {
    if (!zip.exists()) {
        throw new UnsupportedOperationException("Attempted to extract non-existent file: " + zip);
    }//ww w.  j  a  v a 2  s .co m

    if (destination.mkdirs()) {
        log.log(Level.INFO, "Creating dir: {0}", destination);
    }

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(zip);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (!entry.isDirectory()) {
                InputStream inputStream = zipFile.getInputStream(entry);
                File file = new File(destination, entry.getName());
                copyFile(inputStream, file, SharedLocale.tr("runtimeFetcher.extract", file.getName()), -1);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        Closer.close(zipFile);
    }
}

From source file:org.jboss.dashboard.database.hibernate.HibernateInitializer.java

protected void loadHibernateDescriptors(Configuration hbmConfig) throws IOException {
    Set<File> jars = Application.lookup().getJarFiles();
    for (File jar : jars) {
        ZipFile zf = new ZipFile(jar);
        for (Enumeration en = zf.entries(); en.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) en.nextElement();
            String entryName = entry.getName();
            if (entryName.endsWith("hbm.xml") && !entry.isDirectory()) {
                InputStream is = zf.getInputStream(entry);
                String xml = readXMLForFile(entryName, is);
                xml = processXMLContents(xml);
                hbmConfig.addXML(xml);//  w  w  w .j  a v a2  s  . c o  m
            }
        }
    }
}

From source file:it.readbeyond.minstrel.librarian.FormatHandlerEPUB.java

public Publication parseFile(File file) {
    Publication p = super.parseFile(file);
    Format format = new Format(EPUB_FORMAT);
    pathThumbnailSourceRelativeToOPF = null;
    coverManifestItemID = null;/*from w  w  w.j  a va  2s.  c om*/

    String OPFPath = this.getOPFPath(file);
    if (OPFPath != null) {
        try {
            ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ);
            ZipEntry OPFEntry = zipFile.getEntry(OPFPath);
            if (OPFEntry != null) {

                InputStream is;

                // first pass: parse metadata
                is = zipFile.getInputStream(OPFEntry);
                parser = Xml.newPullParser();
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                parser.setInput(is, null);
                parser.nextTag();
                this.parsePackage(format, 1);
                is.close();

                // second pass: parse manifest
                is = zipFile.getInputStream(OPFEntry);
                parser = Xml.newPullParser();
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                parser.setInput(is, null);
                parser.nextTag();
                this.parsePackage(format, 2);
                is.close();

                // item is valid
                p.isValid(true);

                // set the cover path, relative to the EPUB container (aka ZIP) root
                if (pathThumbnailSourceRelativeToOPF != null) {
                    // concatenate OPFPath parent directory and pathThumbnailSourceRelativeToOPF
                    File tmp = new File(new File(OPFPath).getParent(), pathThumbnailSourceRelativeToOPF);
                    // remove leading "/"
                    format.addMetadatum("internalPathCover", tmp.getAbsolutePath().substring(1));
                }

            }
            zipFile.close();
        } catch (Exception e) {
            // invalidate item, so it will not be added to library
            p.isValid(false);
        }
    }

    p.addFormat(format);

    // extract cover
    super.extractCover(file, format, p.getID());

    return p;
}

From source file:net.sf.zekr.engine.translation.TranslationData.java

/**
 * Verify the zip archive and close the zip file handle finally.
 * //from w  ww . j a v a2 s. co m
 * @return <code>true</code> if translation verified, <code>false</code> otherwise.
 * @throws IOException
 */
public boolean verify() throws IOException {
    ZipFile zf = new ZipFile(archiveFile);
    ZipEntry ze = zf.getEntry(file);
    if (ze == null) {
        logger.error("Load failed. No proper entry found in \"" + archiveFile.getName() + "\".");
        return false;
    }

    byte[] textBuf = new byte[(int) ze.getSize()];
    boolean result;
    result = verify(zf.getInputStream(ze), textBuf);
    zf.close();
    return result;
}

From source file:org.openmrs.module.clinicalsummary.web.controller.upload.UploadSummariesController.java

public void validate(final String filename, final String password) throws Exception {
    String encryptedFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ENCRYPTED),
            ".");
    ZipFile encryptedFile = new ZipFile(new File(TaskUtils.getEncryptedOutputPath(), encryptedFilename));

    byte[] initVector = null;
    byte[] encryptedSampleBytes = null;
    Enumeration<? extends ZipEntry> entries = encryptedFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry zipEntry = entries.nextElement();
        String zipEntryName = zipEntry.getName();
        if (zipEntryName.endsWith(TaskConstants.FILE_TYPE_SECRET)) {
            InputStream inputStream = encryptedFile.getInputStream(zipEntry);
            initVector = FileCopyUtils.copyToByteArray(inputStream);
            if (initVector.length != IV_SIZE) {
                throw new Exception("Secret file is corrupted or invalid secret file are being used.");
            }//  w  w  w.j  a va 2 s.  c om
        } else if (zipEntryName.endsWith(TaskConstants.FILE_TYPE_SAMPLE)) {
            InputStream inputStream = encryptedFile.getInputStream(zipEntry);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            FileCopyUtils.copy(inputStream, baos);
            encryptedSampleBytes = baos.toByteArray();
        }
    }

    if (initVector != null && encryptedSampleBytes != null) {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(TaskConstants.SECRET_KEY_FACTORY);
        KeySpec spec = new PBEKeySpec(password.toCharArray(), password.getBytes(), 1024, 128);
        SecretKey tmp = factory.generateSecret(spec);
        // generate the secret key
        SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), TaskConstants.KEY_SPEC);
        // create the cipher
        Cipher cipher = Cipher.getInstance(TaskConstants.CIPHER_CONFIGURATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(initVector));
        // decrypt the sample
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(encryptedSampleBytes);
        CipherInputStream cipherInputStream = new CipherInputStream(byteArrayInputStream, cipher);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileCopyUtils.copy(cipherInputStream, baos);

        String sampleText = baos.toString();
        if (!sampleText.contains("This is sample text")) {
            throw new Exception("Upload parameters incorrect!");
        }
    }
}