Example usage for java.util.zip ZipInputStream getNextEntry

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

Introduction

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

Prototype

public ZipEntry getNextEntry() throws IOException 

Source Link

Document

Reads the next ZIP file entry and positions the stream at the beginning of the entry data.

Usage

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.file.shape.LocalShapeReader.java

private void unzipShapefiles(File shapefileCompressedData) throws IOException {
    IOException error = null;//from  w w  w.  j  ava 2 s .co  m
    if (!shapefilesFolder.exists()) {
        shapefilesFolder.mkdirs();
    }
    InputStream bis = new FileInputStream(shapefileCompressedData);
    ZipInputStream zis = new ZipInputStream(bis);
    ZipEntry ze;
    try {
        while ((ze = zis.getNextEntry()) != null) {
            if (!ze.isDirectory()) {
                String fileName = ze.getName();
                File unzippedFile = new File(shapefilesFolder, fileName);
                byte[] buffer = new byte[1024];
                FileOutputStream fos = new FileOutputStream(unzippedFile);
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
                if (fileName.toLowerCase().endsWith(".shp")) {
                    shapefilePath = unzippedFile.toURI();
                }
            }
        }
    } catch (IOException e) {
        error = e;
    } 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();
        }
    }
    if (error != null) {
        throw error;
    }
}

From source file:com.evolveum.midpoint.ninja.action.worker.ImportProducerWorker.java

@Override
public void run() {
    Log log = context.getLog();/*from w w w  .j a v a 2  s .c  o m*/

    log.info("Starting import");
    operation.start();

    try (InputStream input = openInputStream()) {
        if (!options.isZip()) {
            processStream(input);
        } else {
            ZipInputStream zis = new ZipInputStream(input);
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                if (entry.isDirectory()) {
                    continue;
                }

                if (!StringUtils.endsWith(entry.getName().toLowerCase(), ".xml")) {
                    continue;
                }

                log.info("Processing file {}", entry.getName());
                processStream(zis);
            }
        }
    } catch (IOException ex) {
        log.error("Unexpected error occurred, reason: {}", ex, ex.getMessage());
    } catch (NinjaException ex) {
        log.error(ex.getMessage(), ex);
    } finally {
        markDone();

        if (isWorkersDone()) {
            if (!operation.isFinished()) {
                operation.producerFinish();
            }
        }
    }
}

From source file:com.cloudera.recordservice.tests.ClusterConfiguration.java

/**
 * This method unzips a conf dir return through the CM api and returns the
 * path of the unzipped directory as a string
 *//*from w w  w  .java  2  s  . c  om*/
private String unzipConf(String zipFileName) throws IOException {
    int num = rand_.nextInt(10000000);
    String outDir = "/tmp/" + "confDir" + "_" + num + "/";
    byte[] buffer = new byte[4096];
    FileInputStream fis;
    String filename = "";
    fis = new FileInputStream(zipFileName);
    ZipInputStream zis = new ZipInputStream(fis);
    ZipEntry ze = zis.getNextEntry();
    while (ze != null) {
        filename = ze.getName();
        File unzippedFile = new File(outDir + filename);
        // Ensure that parent directories exist
        new File(unzippedFile.getParent()).mkdirs();
        FileOutputStream fos = new FileOutputStream(unzippedFile);
        int len;
        while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        zis.closeEntry();
        ze = zis.getNextEntry();
    }
    zis.closeEntry();
    zis.close();
    fis.close();
    return outDir + "recordservice-conf/";
}

From source file:eu.europa.ec.markt.dss.validation.SignedDocumentValidator.java

private static SignedDocumentValidator getInstanceForAsics(Document document) throws IOException {

    ZipInputStream asics = new ZipInputStream(document.openStream());

    try {/* w  ww . j  av  a 2s  .c om*/

        ByteArrayOutputStream datafile = null;
        ByteArrayOutputStream signatures = null;
        ZipEntry entry;

        boolean cadesSigned = false;
        boolean xadesSigned = false;

        while ((entry = asics.getNextEntry()) != null) {
            if (entry.getName().equalsIgnoreCase(SIGNATURES_P7S)) {
                if (xadesSigned) {
                    throw new NotETSICompliantException(MSG.MORE_THAN_ONE_SIGNATURE);
                }
                signatures = new ByteArrayOutputStream();
                IOUtils.copy(asics, signatures);
                signatures.close();
                cadesSigned = true;
            } else if (entry.getName().equalsIgnoreCase(SIGNATURES_XML)) {
                if (cadesSigned) {
                    throw new NotETSICompliantException(MSG.MORE_THAN_ONE_SIGNATURE);
                }
                signatures = new ByteArrayOutputStream();
                IOUtils.copy(asics, signatures);
                signatures.close();
                xadesSigned = true;
            } else if (entry.getName().equalsIgnoreCase(MIMETYPE)) {
                ByteArrayOutputStream mimetype = new ByteArrayOutputStream();
                IOUtils.copy(asics, mimetype);
                mimetype.close();
                if (!Arrays.equals(mimetype.toByteArray(), MIMETYPE_ASIC_S.getBytes())) {
                    throw new NotETSICompliantException(MSG.UNRECOGNIZED_TAG);
                }
            } else if (entry.getName().indexOf("/") == -1) {
                if (datafile == null) {
                    datafile = new ByteArrayOutputStream();
                    IOUtils.copy(asics, datafile);
                    datafile.close();
                } else {
                    throw new ProfileException("ASiC-S profile support only one data file");
                }
            }
        }

        if (xadesSigned) {
            ASiCXMLDocumentValidator xmlValidator = new ASiCXMLDocumentValidator(
                    new InMemoryDocument(signatures.toByteArray()), datafile.toByteArray());
            return xmlValidator;
        } else if (cadesSigned) {
            CMSDocumentValidator pdfValidator = new CMSDocumentValidator(
                    new InMemoryDocument(signatures.toByteArray()));
            pdfValidator.setExternalContent(new InMemoryDocument(datafile.toByteArray()));
            return pdfValidator;
        } else {
            throw new RuntimeException("Is not xades nor cades signed");
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        try {
            asics.close();
        } catch (IOException e) {
        }
    }

}

From source file:com.skcraft.launcher.creator.util.ModInfoReader.java

/**
 * Detect the mods listed in the given .jar
 *
 * @param file The file/*from  w  w  w .j a v  a  2 s.  c  o  m*/
 * @return A list of detected mods
 */
public List<? extends ModInfo> detectMods(File file) {
    Closer closer = Closer.create();

    try {
        FileInputStream fis = closer.register(new FileInputStream(file));
        BufferedInputStream bis = closer.register(new BufferedInputStream(fis));
        ZipInputStream zis = closer.register(new ZipInputStream(bis));

        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            if (entry.getName().equalsIgnoreCase(FORGE_INFO_FILENAME)) {
                List<ForgeModInfo> mods;
                String content = CharStreams.toString(new InputStreamReader(zis, Charsets.UTF_8));

                try {
                    mods = mapper.readValue(content, ForgeModManifest.class).getMods();
                } catch (JsonMappingException | JsonParseException e) {
                    mods = mapper.readValue(content, new TypeReference<List<ForgeModInfo>>() {
                    });
                }

                if (mods != null) {
                    // Ignore "examplemod"
                    return Collections.unmodifiableList(
                            mods.stream().filter(info -> !info.getModId().equals("examplemod"))
                                    .collect(Collectors.toList()));
                } else {
                    return Collections.emptyList();
                }

            } else if (entry.getName().equalsIgnoreCase(LITELOADER_INFO_FILENAME)) {
                String content = CharStreams.toString(new InputStreamReader(zis, Charsets.UTF_8));
                return new ImmutableList.Builder<ModInfo>()
                        .add(mapper.readValue(content, LiteLoaderModInfo.class)).build();
            }
        }

        return Collections.emptyList();
    } catch (JsonMappingException e) {
        log.log(Level.WARNING, "Unknown format " + FORGE_INFO_FILENAME + " file in " + file.getAbsolutePath(),
                e);
        return Collections.emptyList();
    } catch (JsonParseException e) {
        log.log(Level.WARNING, "Corrupt " + FORGE_INFO_FILENAME + " file in " + file.getAbsolutePath(), e);
        return Collections.emptyList();
    } catch (IOException e) {
        log.log(Level.WARNING, "Failed to read " + file.getAbsolutePath(), e);
        return Collections.emptyList();
    } finally {
        try {
            closer.close();
        } catch (IOException ignored) {
        }
    }
}

From source file:com.squareup.wire.schema.internal.parser.RpcMethodScanner.java

private List<RpcMethodDefinition> searchJar(String jarpath, String serviceName) throws IOException {

    List<RpcMethodDefinition> defs = new ArrayList<>();

    File jarFile = new File(jarpath);
    if (!jarFile.exists() || jarFile.isDirectory()) {
        return defs;
    }//from  www.j a va2 s. co  m

    ZipInputStream zip = new ZipInputStream(new FileInputStream(jarFile));
    ZipEntry ze;

    while ((ze = zip.getNextEntry()) != null) {
        String entryName = ze.getName();
        if (entryName.endsWith(".proto")) {
            ZipFile zipFile = new ZipFile(jarFile);
            try (InputStream in = zipFile.getInputStream(ze)) {
                defs.addAll(inspectProtoFile(in, serviceName));
                if (!defs.isEmpty()) {
                    zipFile.close();
                    break;
                }
            }
            zipFile.close();
        }
    }

    zip.close();

    return defs;
}

From source file:mSearch.filmlisten.FilmlisteLesen.java

private InputStream selectDecompressor(String source, InputStream in) throws Exception {
    if (source.endsWith(Const.FORMAT_XZ)) {
        in = new XZInputStream(in);
    } else if (source.endsWith(Const.FORMAT_ZIP)) {
        ZipInputStream zipInputStream = new ZipInputStream(in);
        zipInputStream.getNextEntry();
        in = zipInputStream;//from w  w w . j  a v a2 s .  com
    }
    return in;
}

From source file:name.martingeisse.webide.plugin.PluginBundleWicketResource.java

@Override
protected ResourceResponse newResourceResponse(final Attributes attributes) {

    // fetch the JAR file
    final SQLQuery query = EntityConnectionManager.getConnection().createQuery();
    query.from(QPluginBundles.pluginBundles);
    query.where(QPluginBundles.pluginBundles.id.eq(pluginBundleId));
    final Object[] row = (Object[]) (Object) query.singleResult(QPluginBundles.pluginBundles.jarfile);
    final byte[] jarData = (byte[]) row[0];
    String matchingEntryName;//from   w ww . jav a  2 s.c om
    final byte[] matchingEntryData;

    // if requested, load a single file from the JAR
    if (localPath != null) {
        final String localPathText = localPath.withLeadingSeparator(false).withTrailingSeparator(false)
                .toString();
        try {
            final ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(jarData));
            while (true) {
                final ZipEntry entry = zipInputStream.getNextEntry();
                if (entry == null) {
                    zipInputStream.close();
                    final ResourceResponse response = new ResourceResponse();
                    response.setError(404, "Plugin bundle (id " + pluginBundleId + ") does not contain file: "
                            + localPathText);
                    response.setStatusCode(404);
                    return response;
                }
                if (localPathText.equals(entry.getName())) {
                    matchingEntryName = entry.getName();
                    matchingEntryData = IOUtils.toByteArray(zipInputStream);
                    zipInputStream.close();
                    break;
                }
            }
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        matchingEntryName = null;
        matchingEntryData = null;
    }

    // build the response
    final ResourceResponse response = new ResourceResponse();
    response.setCacheDuration(Duration.NONE);
    response.setContentDisposition(ContentDisposition.ATTACHMENT);
    if (matchingEntryData == null) {
        response.setFileName("plugin-bundle-" + pluginBundleId + ".jar");
    } else {
        final int lastSlashIndex = matchingEntryName.lastIndexOf('/');
        if (lastSlashIndex != -1) {
            matchingEntryName = matchingEntryName.substring(lastSlashIndex + 1);
        }
        response.setFileName(matchingEntryName);
    }
    response.setWriteCallback(new WriteCallback() {
        @Override
        public void writeData(final Attributes attributes) throws IOException {
            attributes.getResponse().write(matchingEntryData == null ? jarData : matchingEntryData);
        }
    });
    return response;

}

From source file:org.openmrs.contrib.metadatarepository.service.impl.PackageManagerImpl.java

public MetadataPackage deserializePackage(byte[] file) {
    Map<String, String> files = new LinkedHashMap<String, String>();

    InputStream input = new ByteArrayInputStream(file);

    ZipInputStream zip = new ZipInputStream(input);
    try {/*  w  ww .j  a v  a  2  s.  c o  m*/
        for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
            String file1 = IOUtils.toString(zip, ENCODING);
            files.put(entry.getName(), file1);
        }
    } catch (IOException e) {
        throw new APIException("error", e);
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException e) {

                log.error(e);
            }
        }
    }
    String header = files.get(HEADER_FILE);

    XStream xstream = new XStream(new DomDriver());

    MetadataPackage deserializedPackage = new MetadataPackage();
    xstream.registerConverter(new DateTimeConverter());
    xstream.alias("package", MetadataPackage.class);
    xstream.omitField(MetadataPackage.class, "file");
    xstream.omitField(MetadataPackage.class, "user");
    xstream.omitField(MetadataPackage.class, "downloadCount");
    xstream.omitField(MetadataPackage.class, "serializedPackage");
    xstream.omitField(MetadataPackage.class, "modules");
    xstream.omitField(MetadataPackage.class, "items");
    xstream.omitField(MetadataPackage.class, "relatedItems");
    deserializedPackage = (MetadataPackage) xstream.fromXML(header);

    return deserializedPackage;
}