Example usage for java.util.zip ZipFile entries

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

Introduction

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

Prototype

public Enumeration<? extends ZipEntry> entries() 

Source Link

Document

Returns an enumeration of the ZIP file entries.

Usage

From source file:com.axelor.apps.base.service.imports.importer.Importer.java

protected void unZip(File file, File directory) throws ZipException, IOException {

    File extractFile = null;//from  w  ww.  j  a va 2s.  c o m
    FileOutputStream fileOutputStream = null;
    ZipFile zipFile = new ZipFile(file);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while (entries.hasMoreElements()) {
        try {
            ZipEntry entry = entries.nextElement();
            InputStream entryInputStream = zipFile.getInputStream(entry);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;

            extractFile = new File(directory, entry.getName());
            if (entry.isDirectory()) {
                extractFile.mkdirs();
                continue;
            } else {
                extractFile.getParentFile().mkdirs();
                extractFile.createNewFile();
            }

            fileOutputStream = new FileOutputStream(extractFile);
            while ((bytesRead = entryInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }

        } catch (IOException ioException) {
            log.error(ioException.getMessage());
            continue;
        } finally {
            if (fileOutputStream == null) {
                continue;
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
            }
        }
    }

    zipFile.close();

}

From source file:org.jini.commands.compress.Unzip.java

/**
 * Method where the zipped file will be decompressed
 *
 * @param zip/*from  w  w w .ja  v  a2 s  .  co m*/
 * @param extractTo
 * @throws IOException
 */
public void unzip(File zip, File extractTo) throws IOException {
    ZipFile archive = new ZipFile(zip);
    Enumeration e = archive.entries();
    while (e.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) e.nextElement();
        File file = new File(extractTo, entry.getName());
        if (entry.isDirectory() && !file.exists()) {
            file.mkdirs();
        } else {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            InputStream in = archive.getInputStream(entry);
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));

            byte[] buffer = new byte[8192];
            int read;

            while (-1 != (read = in.read(buffer))) {
                out.write(buffer, 0, read);
            }

            in.close();
            out.close();
        }
    }
}

From source file:org.atombeat.xquery.functions.util.GetZipEntries.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {/*from  w  w  w.j  a v a2s  . com*/
        String path = args[0].getStringValue();
        ZipFile zf = new ZipFile(path);
        log.debug(zf.getName());
        log.debug(zf.size());
        log.debug(zf.hashCode());
        ZipEntry e;
        Enumeration<? extends ZipEntry> entries = zf.entries();
        ValueSequence s = new ValueSequence();
        for (int i = 0; entries.hasMoreElements(); i++) {
            log.debug(i);
            e = entries.nextElement();
            log.debug(e.getName());
            log.debug(e.getComment());
            log.debug(e.isDirectory());
            log.debug(e.getCompressedSize());
            log.debug(e.getCrc());
            log.debug(e.getMethod());
            log.debug(e.getSize());
            log.debug(e.getTime());
            if (!e.isDirectory())
                s.add(new StringValue(e.getName()));
        }
        return s;
    } catch (Exception e) {
        throw new XPathException("error processing zip file: " + e.getLocalizedMessage(), e);
    }

}

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

@Override
protected File doInBackground() throws Exception {
    ZipFile zip = new ZipFile(source);
    parseResourceTable();/*w ww  .j av  a 2s . 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.openmrs.module.clinicalsummary.io.UploadSummariesTask.java

/**
 * In order to correctly perform the encryption - decryption process, user must store their init vector table. This init vector will be given to the
 * user as a small file and it is required to perform the decryption process.
 *
 * @throws Exception// ww w. j av  a 2s  .  c  om
 */
protected void processInitVector() throws Exception {
    String encryptedFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ENCRYPTED),
            ".");
    ZipFile encryptedFile = new ZipFile(new File(TaskUtils.getEncryptedOutputPath(), encryptedFilename));

    Enumeration<? extends ZipEntry> entries = encryptedFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry zipEntry = entries.nextElement();
        if (zipEntry.getName().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.");
            }
        }
    }
}

From source file:no.uio.medicine.virsurveillance.parsers.CSVsGBDdata.java

public void parse(String deathFolder) throws IOException {
    File f = new File(deathFolder);
    Runtime runtime = Runtime.getRuntime();
    if (f.isDirectory()) {
        String[] filesInDir = f.list();

        for (String fil : filesInDir) {
            if (fil.endsWith(".zip")) {
                ZipFile zipFile = new ZipFile(deathFolder + "/" + fil);

                Enumeration<? extends ZipEntry> entries = zipFile.entries();

                while (entries.hasMoreElements()) {
                    System.out.println(
                            "Used memory: " + (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024)
                                    + " Free memory: " + (runtime.freeMemory()) / (1024 * 1024));

                    ZipEntry entry = entries.nextElement();
                    InputStream stream = zipFile.getInputStream(entry);
                    BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
                    CSVParser parser = CSVFormat.RFC4180.withDelimiter(',').withIgnoreEmptyLines().withHeader()
                            .parse(br);/* www. j a v a2  s.c  om*/

                    List<CSVRecord> records = parser.getRecords();
                    System.out.println("Reading records: " + zipFile.getName() + "/" + entry);
                    /*for (int i=0;i<records.size();i++) {
                    CSVRecord csvRecord = records.get(i);*/
                    for (CSVRecord csvRecord : records) {
                        if (csvRecord.isMapped("age_group_id")) { //age group 22 corresponds to all ages
                            if (csvRecord.get("age_group_id").equalsIgnoreCase("22")) {
                                String location = null;
                                String year = null;
                                String sex = null;
                                String cause = null;
                                String number = null;
                                String metric = null;

                                if (csvRecord.isMapped("location_code")) {
                                    location = csvRecord.get("location_code");
                                }
                                if (csvRecord.isMapped("year")) {
                                    year = csvRecord.get("year");
                                }
                                if (csvRecord.isMapped("sex_id")) { //1=male, 2 = female
                                    if (csvRecord.get("sex_id").equalsIgnoreCase(("1"))) {
                                        sex = "m";
                                    } else if (csvRecord.get("sex_id").equalsIgnoreCase("2")) {
                                        sex = "f";
                                    }
                                }
                                if (csvRecord.isMapped("cause_name")) {
                                    cause = csvRecord.get("cause_name");
                                }
                                if (csvRecord.isMapped("mean")) {
                                    number = csvRecord.get("mean");
                                }
                                if (csvRecord.isMapped("metric") && csvRecord.isMapped("unit")) {
                                    metric = csvRecord.get("metric") + "-" + csvRecord.get("unit");
                                }

                                if (location != null && year != null && sex != null && cause != null
                                        && number != null && metric != null) {
                                    try {
                                        sqlM.addSanitaryIssueToCountry(location, year, sex, cause, metric,
                                                number);
                                    } catch (SQLException ex) {

                                        Logger.getLogger(CSVsGBDdata.class.getName()).log(Level.SEVERE, null,
                                                ex);
                                    }
                                }

                            }

                        }

                    }

                    parser.close();

                    stream.close();
                    br.close();
                }
                zipFile.close();
            }
        }
    } else {
        System.out.println("Not a directory");
    }
}

From source file:net.sourceforge.jweb.maven.mojo.PropertiesOverideMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (disabled) {
        this.getLog().info("plugin was disabled");
        return;/*from   w  ww. j  ava 2 s .  co m*/
    }
    processConfiguration();
    if (replacements.isEmpty()) {
        this.getLog().info("Nothing to replace with");
        return;
    }

    String name = this.builddir.getAbsolutePath() + File.separator + this.finalName + "." + this.packing;//the final package
    this.getLog().debug("final artifact: " + name);// the final package

    try {
        File finalWarFile = new File(name);
        File tempFile = File.createTempFile(finalWarFile.getName(), null);
        tempFile.delete();//check deletion
        boolean renameOk = finalWarFile.renameTo(tempFile);
        if (!renameOk) {
            getLog().error("Can not rename file, please check.");
            return;
        }

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile));
        ZipFile zipFile = new ZipFile(tempFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (acceptMime(entry)) {
                getLog().info("applying replacements for " + entry.getName());
                InputStream inputStream = zipFile.getInputStream(entry);
                String src = IOUtils.toString(inputStream, encoding);
                //do replacement
                for (Entry<String, String> e : replacements.entrySet()) {
                    src = src.replaceAll("#\\{" + e.getKey() + "}", e.getValue());
                }
                out.putNextEntry(new ZipEntry(entry.getName()));
                IOUtils.write(src, out, encoding);
                inputStream.close();
            } else {
                //not repalce, just put entry back to out zip
                out.putNextEntry(entry);
                InputStream inputStream = zipFile.getInputStream(entry);
                byte[] buf = new byte[512];
                int len = -1;
                while ((len = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                inputStream.close();
                continue;
            }
        }
        zipFile.close();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:ZipExploder.java

/** Get all the entries in a ZIP file. */
protected Map getEntries(ZipFile zf) {
    Enumeration e = zf.entries();
    Map m = new HashMap();
    while (e.hasMoreElements()) {
        ZipEntry ze = (ZipEntry) e.nextElement();
        m.put(ze.getName(), ze);//from w  ww .  j  av  a 2 s  .  c om
    }
    return m;
}

From source file:averroes.JarOrganizer.java

/**
 * Process a given JAR file.//from w  w w.ja  v  a  2 s  .  c o m
 * 
 * @param fileName
 * @param fromApplicationArchive
 */
private void processArchive(String fileName, boolean fromApplicationArchive) {
    // Exit if the fileName is empty
    if (fileName.trim().length() <= 0) {
        return;
    }

    File file = new File(fileName);
    System.out.println("Processing " + (fromApplicationArchive ? "input" : "library") + " archive: "
            + file.getAbsolutePath());

    try {
        ZipFile archive = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = archive.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.getName().endsWith(".class")) {
                addClass(archive, entry, fromApplicationArchive);
            }
        }
        archive.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:fr.ippon.wip.config.dao.DeployConfigurationDecorator.java

/**
 * Extract configurations contained in a zipFile.
 * /*from ww  w  . j  a  v a2 s  . com*/
 * @param zipFile
 *            the file containing the configurations
 */
private List<WIPConfiguration> unzip(final ZipFile zipFile) {
    List<WIPConfiguration> configurations = new ArrayList<WIPConfiguration>();
    Iterator<? extends ZipEntry> xmlEntries = filter(forEnumeration(zipFile.entries()), xmlPredicate);

    while (xmlEntries.hasNext()) {
        try {
            String configName = FilenameUtils.getBaseName(xmlEntries.next().getName());
            WIPConfiguration configuration = zip.unzip(zipFile, configName);

            if (configuration != null)
                configurations.add(configuration);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return configurations;
}