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.genericworkflownodes.knime.nodes.io.outputfile.OutputFileNodeModel.java

/**
 * {@inheritDoc}/*from   w w w .ja  v  a2  s .  c o m*/
 */
@Override
protected void loadInternals(final File internDir, final ExecutionMonitor exec)
        throws IOException, CanceledExecutionException {
    ZipFile zip = new ZipFile(new File(internDir, "loadeddata"));

    @SuppressWarnings("unchecked")
    Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();

    int BUFFSIZE = 2048;
    byte[] BUFFER = new byte[BUFFSIZE];

    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();

        if (entry.getName().equals("rawdata.bin")) {
            int size = (int) entry.getSize();
            byte[] data = new byte[size];
            InputStream in = zip.getInputStream(entry);
            int len;
            int totlen = 0;
            while ((len = in.read(BUFFER, 0, BUFFSIZE)) >= 0) {
                System.arraycopy(BUFFER, 0, data, totlen, len);
                totlen += len;
            }
            this.data = new String(data);
        }
    }
    zip.close();
}

From source file:com.flexive.tests.disttools.DistPackageTest.java

/**
 * Extracts the flexive-dist.zip package and returns the (temporary) directory handle. All extracted
 * files will be registered for deletion on the JVM exit.
 *
 * @return  the (temporary) directory handle.
 * @throws IOException  if the package could not be extracted
 *//*  ww  w  . j  a v a2s .c om*/
private File extractDistPackage() throws IOException {
    final ZipFile file = getDistFile();
    final File tempDir = createTempDir();
    try {
        final Enumeration<? extends ZipEntry> entries = file.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry zipEntry = entries.nextElement();
            final String path = getTempPath(tempDir, zipEntry);
            if (zipEntry.isDirectory()) {
                final File dir = new File(path);
                dir.mkdirs();
                dir.deleteOnExit();
            } else {
                final InputStream in = file.getInputStream(zipEntry);
                final OutputStream out = new BufferedOutputStream(new FileOutputStream(path));
                // copy streams
                final byte[] buffer = new byte[32768];
                int len;
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                in.close();
                out.close();
                new File(path).deleteOnExit();
            }
        }
    } finally {
        file.close();
    }
    return new File(tempDir + File.separator + "flexive-dist");
}

From source file:org.apache.tez.history.parser.ATSFileParser.java

/**
 * Read zip file contents. Every file can contain "dag", "vertices", "tasks", "task_attempts"
 *
 * @param atsFile/*from   w  ww .j  a  v  a 2 s. co m*/
 * @throws IOException
 * @throws JSONException
 */
private void parseATSZipFile(File atsFile)
        throws IOException, JSONException, TezException, InterruptedException {
    final ZipFile atsZipFile = new ZipFile(atsFile);
    try {
        Enumeration<? extends ZipEntry> zipEntries = atsZipFile.entries();
        while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = zipEntries.nextElement();
            LOG.debug("Processing " + zipEntry.getName());
            InputStream inputStream = atsZipFile.getInputStream(zipEntry);
            JSONObject jsonObject = readJson(inputStream);

            //This json can contain dag, vertices, tasks, task_attempts
            JSONObject dagJson = jsonObject.optJSONObject(Constants.DAG);
            if (dagJson != null) {
                //TODO: support for multiple dags per ATS file later.
                dagInfo = DagInfo.create(dagJson);
            }

            //Process vertex
            JSONArray vertexJson = jsonObject.optJSONArray(Constants.VERTICES);
            if (vertexJson != null) {
                processVertices(vertexJson);
            }

            //Process task
            JSONArray taskJson = jsonObject.optJSONArray(Constants.TASKS);
            if (taskJson != null) {
                processTasks(taskJson);
            }

            //Process task attempts
            JSONArray attemptsJson = jsonObject.optJSONArray(Constants.TASK_ATTEMPTS);
            if (attemptsJson != null) {
                processAttempts(attemptsJson);
            }

            //Process application (mainly versionInfo)
            JSONObject tezAppJson = jsonObject.optJSONObject(Constants.APPLICATION);
            if (tezAppJson != null) {
                processApplication(tezAppJson);
            }
        }
    } finally {
        atsZipFile.close();
    }
}

From source file:org.apache.archiva.remotedownload.AbstractDownloadTest.java

protected List<String> getZipEntriesNames(ZipFile zipFile) {
    try {//from w  ww .  j a v  a2  s.c o m
        List<String> entriesNames = new ArrayList<>();
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            entriesNames.add(entries.nextElement().getName());
        }
        return entriesNames;
    } catch (Throwable e) {
        log.info("fail to get zipEntries {}", e.getMessage(), e);
    }
    return Collections.emptyList();
}

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.");
            }/*from   w ww. j  a va  2 s  .  c o  m*/
        } 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!");
        }
    }
}

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

protected List<ZipAsset> getSortedListOfAssets(String path, String[] allowedExtensions) {
    List<ZipAsset> assets = new ArrayList<ZipAsset>();
    try {//  w ww.  j  a  v a 2  s  .  co  m
        // read assets 
        ZipFile zipFile = new ZipFile(new File(path), ZipFile.OPEN_READ);
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry ze = zipFileEntries.nextElement();
            String name = ze.getName();
            String lower = name.toLowerCase();
            if (this.fileHasAllowedExtension(lower, allowedExtensions)) {
                assets.add(new ZipAsset(name, null));
            }
        }
        zipFile.close();

        // sort assets
        Collections.sort(assets);
    } catch (Exception e) {
        // nop 
    }
    return assets;
}

From source file:org.eclipse.emf.ecp.emf2web.wizard.ViewModelExportWizard.java

/**
 * Extracts the given zip file to the given destination.
 *
 * @param zipFilePath/*from  w  w  w  . ja  v  a  2  s. co m*/
 *            The absolute path of the zip file.
 * @param destinationPath
 *            The absolute path of the destination directory;
 * @throws IOException when extracting or copying fails.
 */
private void extractZip(String zipFilePath, String destinationPath) throws IOException {
    final ZipFile zipFile = new ZipFile(zipFilePath);
    final Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        final ZipEntry entry = entries.nextElement();
        final File entryDestination = new File(destinationPath, entry.getName());
        entryDestination.getParentFile().mkdirs();
        if (entry.isDirectory()) {
            entryDestination.mkdirs();
        } else {
            final InputStream in = zipFile.getInputStream(entry);
            final OutputStream out = new FileOutputStream(entryDestination);
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }
    zipFile.close();
}

From source file:org.jboss.dashboard.factory.Factory.java

protected List<DescriptorFile> initModuleFromZip(File moduleZip) throws IOException {
    List<DescriptorFile> descriptorFiles = new ArrayList<DescriptorFile>();
    ZipFile zf = new ZipFile(moduleZip);
    for (Enumeration en = zf.entries(); en.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) en.nextElement();
        if (entry.getName().endsWith(FACTORY_EXTENSION) && !entry.isDirectory()) {
            InputStream is = zf.getInputStream(entry);
            String componentName = entry.getName();
            componentName = componentName.substring(0, componentName.length() - 1 - FACTORY_EXTENSION.length());
            componentName = componentName.replace('/', '.');
            componentName = componentName.replace('\\', '.');
            Properties prop = new Properties();
            try {
                prop.load(is);//from ww  w .  ja  v  a2  s.co  m
                is.close();
                descriptorFiles.add(new DescriptorFile(componentName, prop, moduleZip + "!" + entry.getName()));
            } catch (IOException e) {
                log.error("Error processing file " + entry.getName() + " inside " + moduleZip
                        + ". It will be ignored.", e);
                continue;
            }
        }
    }
    return descriptorFiles;
}

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.ja  v a 2s . c  o  m
            }
        }
    }
}

From source file:org.hyperic.hq.product.ClientPluginDeployer.java

public List unpackJar(String jar) throws IOException {

    ArrayList jars = new ArrayList();

    ZipFile zipfile = new ZipFile(jar);
    for (Enumeration e = zipfile.entries(); e.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) e.nextElement();
        String name = entry.getName();

        if (entry.isDirectory()) {
            continue;
        }/* ww w.  j  av  a  2s . com*/

        int ix = name.indexOf('/');
        if (ix == -1) {
            continue;
        }

        String prefix = name.substring(0, ix);
        name = name.substring(ix + 1);

        File file = getFile(prefix, name);
        if (file == null) {
            continue;
        }

        if (name.endsWith(".jar")) {
            jars.add(file.toString());
        }

        if (upToDate(entry, file)) {
            continue;
        }

        InputStream is = zipfile.getInputStream(entry);
        try {
            write(is, file);
        } catch (IOException ioe) {
            zipfile.close();
            throw ioe;
        } finally {
            is.close();
        }
    }

    zipfile.close();

    return jars;
}