Example usage for org.apache.commons.compress.archivers.zip ZipFile getEntry

List of usage examples for org.apache.commons.compress.archivers.zip ZipFile getEntry

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipFile getEntry.

Prototype

public ZipArchiveEntry getEntry(String name) 

Source Link

Document

Returns a named entry - or null if no entry by that name exists.

Usage

From source file:at.spardat.xma.xdelta.JarPatcher.java

/**
 * Gets the entry.//  w w w .j  a va2  s.  c o m
 *
 * @param source the source
 * @param name the name
 * @param crc the crc
 * @return the entry
 */
private ZipArchiveEntry getEntry(ZipFile source, String name, long crc) {
    for (ZipArchiveEntry next : source.getEntries(name)) {
        if (next.getCrc() == crc)
            return next;
    }
    if (!JarDelta.zipFilesPattern.matcher(name).matches()) {
        return null;
    } else {
        return source.getEntry(name);
    }
}

From source file:com.silverpeas.util.ZipManagerTest.java

/**
* Test of compressPathToZip method, of class ZipManager.
*
* @throws Exception/*from   w  ww .  j a  v a 2  s .c om*/
*/
@Test
public void testCompressPathToZip() throws Exception {
    String path = PathTestUtil.TARGET_DIR + "test-classes" + separatorChar + "ZipSample";
    String outfilename = PathTestUtil.TARGET_DIR + "temp" + separatorChar + "testCompressPathToZip.zip";
    ZipManager.compressPathToZip(path, outfilename);
    ZipFile zipFile = new ZipFile(new File(outfilename), CharEncoding.UTF_8);
    try {
        Enumeration<? extends ZipEntry> entries = zipFile.getEntries();
        assertThat(zipFile.getEncoding(), is(CharEncoding.UTF_8));
        int nbEntries = 0;
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            nbEntries++;
        }
        assertThat(nbEntries, is(5));
        assertThat(zipFile.getEntry("ZipSample/simple.txt"), is(notNullValue()));
        assertThat(zipFile.getEntry("ZipSample/level1/simple.txt"), is(notNullValue()));
        assertThat(zipFile.getEntry("ZipSample/level1/level2b/simple.txt"), is(notNullValue()));
        assertThat(zipFile.getEntry("ZipSample/level1/level2a/simple.txt"), is(notNullValue()));

        ZipEntry accentuatedEntry = zipFile.getEntry("ZipSample/level1/level2a/s\u00efmplifi\u00e9.txt");
        if (accentuatedEntry == null) {
            accentuatedEntry = zipFile.getEntry("ZipSample/level1/level2a/"
                    + new String("smplifi.txt".getBytes("UTF-8"), Charset.defaultCharset()));
        }
        assertThat(accentuatedEntry, is(notNullValue()));
        assertThat(zipFile.getEntry("ZipSample/level1/level2c/"), is(nullValue()));
    } finally {
        zipFile.close();
    }
}

From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java

/**
 * Compares the content of two zip files. The zip files are considered equal, if
 * the content of all zip entries is equal to the content of its corresponding entry
 * in the other zip file.//from   w  ww .jav  a2 s .  c  o  m
 *
 * @author S3460
 * @param zipSource the zip source
 * @param resultZip the result zip
 * @throws Exception the exception
 */
private void compareFiles(ZipFile zipSource, ZipFile resultZip) throws Exception {
    boolean rc = false;
    try {
        for (Enumeration<ZipArchiveEntry> enumer = zipSource.getEntries(); enumer.hasMoreElements();) {
            ZipArchiveEntry sourceEntry = enumer.nextElement();
            ZipArchiveEntry resultEntry = resultZip.getEntry(sourceEntry.getName());
            assertNotNull("Entry nicht generiert: " + sourceEntry.getName(), resultEntry);
            byte[] oldBytes = toBytes(zipSource, sourceEntry);
            byte[] newBytes = toBytes(resultZip, resultEntry);
            rc = equal(oldBytes, newBytes);
            assertTrue("bytes the same " + sourceEntry, rc);
        }
    } finally {
        zipSource.close();
        resultZip.close();
    }
}

From source file:com.nit.libanki.Utils.java

public static boolean unzipFiles(ZipFile zipFile, String targetDirectory, String[] zipEntries,
        HashMap<String, String> zipEntryToFilenameMap) {
    byte[] buf = new byte[FILE_COPY_BUFFER_SIZE];
    File dir = new File(targetDirectory);
    if (!dir.exists() && !dir.mkdirs()) {
        Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Could not create target directory: " + targetDirectory);
        return false;
    }/*ww w  . ja v  a  2  s  . com*/
    if (zipEntryToFilenameMap == null) {
        zipEntryToFilenameMap = new HashMap<String, String>();
    }
    BufferedInputStream zis = null;
    BufferedOutputStream bos = null;
    try {
        for (String requestedEntry : zipEntries) {
            ZipArchiveEntry ze = zipFile.getEntry(requestedEntry);
            if (ze != null) {
                String name = ze.getName();
                if (zipEntryToFilenameMap.containsKey(name)) {
                    name = zipEntryToFilenameMap.get(name);
                }
                File destFile = new File(dir, name);
                File parentDir = destFile.getParentFile();
                if (!parentDir.exists() && !parentDir.mkdirs()) {
                    return false;
                }
                if (!ze.isDirectory()) {
                    // Log.i(AnkiDroidApp.TAG, "uncompress " + name);
                    zis = new BufferedInputStream(zipFile.getInputStream(ze));
                    bos = new BufferedOutputStream(new FileOutputStream(destFile), FILE_COPY_BUFFER_SIZE);
                    int n;
                    while ((n = zis.read(buf, 0, FILE_COPY_BUFFER_SIZE)) != -1) {
                        bos.write(buf, 0, n);
                    }
                    bos.flush();
                    bos.close();
                    zis.close();
                }
            }
        }
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while unzipping archive.", e);
        return false;
    } finally {
        try {
            if (bos != null) {
                bos.close();
            }
        } catch (IOException e) {
            Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while closing output stream.", e);
        }
        try {
            if (zis != null) {
                zis.close();
            }
        } catch (IOException e) {
            Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while closing zip input stream.", e);
        }
    }
    return true;
}

From source file:ee.sk.digidoc.SignedDoc.java

public InputStream findDataFileAsStream(String dfName) {
    try {//from w ww  .  j a  v  a  2s. co  m
        if (m_file != null) {
            StringBuffer sbName = new StringBuffer();
            if (m_path != null) {
                sbName.append(m_path);
                sbName.append(File.separator);
            }
            sbName.append(m_file);
            File fZip = new File(sbName.toString());
            if (fZip.isFile() && fZip.canRead()) {
                ZipFile zis = new ZipFile(fZip);
                ZipArchiveEntry ze = zis.getEntry(dfName);
                if (ze != null) {
                    return zis.getInputStream(ze);
                }
            }
        }
    } catch (Exception ex) {
        m_logger.error("Error reading bdoc: " + ex);
    }
    return null;
}

From source file:org.apache.ambari.view.slider.SliderAppsViewControllerImpl.java

private List<SliderAppType> loadAppTypes() {
    List<SliderAppType> appTypes = null;
    String appsFolderPath = getAppsFolderPath();
    File appsFolder = new File(appsFolderPath);
    if (appsFolder.exists()) {
        File[] appZips = appsFolder.listFiles((FilenameFilter) new RegexFileFilter("^.*\\.zip$"));
        if (appZips != null) {
            appTypes = new ArrayList<SliderAppType>();
            for (File appZip : appZips) {
                try {
                    ZipFile zipFile = new ZipFile(appZip);
                    Metainfo metainfo = new MetainfoParser()
                            .parse(zipFile.getInputStream(zipFile.getEntry("metainfo.xml")));
                    // Create app type object
                    if (metainfo.getApplication() != null) {
                        Application application = metainfo.getApplication();
                        ZipArchiveEntry appConfigZipEntry = zipFile.getEntry("appConfig-default.json");
                        ZipArchiveEntry appConfigSecuredZipEntry = zipFile
                                .getEntry("appConfig-secured-default.json");
                        if (appConfigZipEntry == null) {
                            throw new IllegalStateException("Slider App package '" + appZip.getName()
                                    + "' does not contain 'appConfig-default.json' file");
                        }//from  ww  w .  j a  v  a 2  s.  c om
                        ZipArchiveEntry resourcesZipEntry = zipFile.getEntry("resources-default.json");
                        ZipArchiveEntry resourcesSecuredZipEntry = zipFile
                                .getEntry("resources-secured-default.json");
                        if (resourcesZipEntry == null) {
                            throw new IllegalStateException("Slider App package '" + appZip.getName()
                                    + "' does not contain 'resources-default.json' file");
                        }
                        SliderAppType appType = new SliderAppType();
                        appType.setId(application.getName());
                        appType.setTypeName(application.getName());
                        appType.setTypeDescription(application.getComment());
                        appType.setTypeVersion(application.getVersion());
                        appType.setTypePackageFileName(appZip.getName());
                        // Configs
                        appType.typeConfigsUnsecured = parseAppTypeConfigs(zipFile, appConfigZipEntry,
                                appZip.getName(), application.getName());
                        if (appConfigSecuredZipEntry != null) {
                            appType.typeConfigsSecured = parseAppTypeConfigs(zipFile, appConfigSecuredZipEntry,
                                    appZip.getName(), application.getName());
                        }
                        // Resources
                        appType.resourcesUnsecured = parseAppTypeResources(zipFile, resourcesZipEntry);
                        if (resourcesSecuredZipEntry != null) {
                            appType.resourcesSecured = parseAppTypeResources(zipFile, resourcesSecuredZipEntry);
                        }
                        // Components
                        ArrayList<SliderAppTypeComponent> appTypeComponentList = new ArrayList<SliderAppTypeComponent>();
                        for (Component component : application.getComponents()) {
                            if ("CLIENT".equals(component.getCategory())) {
                                continue;
                            }
                            SliderAppTypeComponent appTypeComponent = new SliderAppTypeComponent();
                            appTypeComponent.setDisplayName(component.getName());
                            appTypeComponent.setId(component.getName());
                            appTypeComponent.setName(component.getName());
                            appTypeComponent.setYarnMemory(1024);
                            appTypeComponent.setYarnCpuCores(1);
                            // Updated below if present in resources.json
                            appTypeComponent.setInstanceCount(1);
                            // appTypeComponent.setPriority(component.);
                            if (component.getMinInstanceCount() != null) {
                                appTypeComponent
                                        .setInstanceCount(Integer.parseInt(component.getMinInstanceCount()));
                            }
                            if (component.getMaxInstanceCount() != null) {
                                appTypeComponent
                                        .setMaxInstanceCount(Integer.parseInt(component.getMaxInstanceCount()));
                            }
                            appTypeComponent.setCategory(component.getCategory());
                            appTypeComponentList.add(appTypeComponent);
                        }

                        MetricsHolder metricsHolder = new MetricsHolder();
                        metricsHolder.setJmxMetrics(readMetrics(zipFile, "jmx_metrics.json"));
                        metricsHolder.setTimelineMetrics(readMetrics(zipFile, "timeline_metrics.json"));
                        appType.setSupportedMetrics(getSupportedMetrics(metricsHolder.getTimelineMetrics()));
                        appMetrics.put(appType.uniqueName(), metricsHolder);

                        appType.setTypeComponents(appTypeComponentList);
                        appTypes.add(appType);
                    }
                } catch (ZipException e) {
                    logger.warn("Unable to parse Slider App package " + appZip.getAbsolutePath(), e);
                } catch (IOException e) {
                    logger.warn("Unable to parse Slider App package " + appZip.getAbsolutePath(), e);
                } catch (Throwable e) {
                    logger.warn("Unable to parse Slider App package " + appZip.getAbsolutePath(), e);
                }
            }
        }
    }
    return appTypes;
}

From source file:org.apache.ambari.view.slider.SliderAppsViewControllerImpl.java

Map<String, Map<String, Map<String, Metric>>> readMetrics(ZipFile zipFile, String fileName) {
    Map<String, Map<String, Map<String, Metric>>> metrics = null;
    try {//from  ww  w .  j  a v a  2 s . com
        InputStream inputStream = zipFile.getInputStream(zipFile.getEntry(fileName));
        ObjectMapper mapper = new ObjectMapper();

        metrics = mapper.readValue(inputStream,
                new TypeReference<Map<String, Map<String, Map<String, Metric>>>>() {
                });
    } catch (IOException e) {
        logger.info("Error reading metrics for file " + fileName + ". " + e.getMessage());
    }

    return metrics;
}

From source file:org.apache.ant.compress.resources.ZipResource.java

/**
 * Return an InputStream for reading the contents of this Resource.
 * @return an InputStream object./*  w ww.j a va2 s  . co  m*/
 * @throws IOException if the zip file cannot be opened,
 *         or the entry cannot be read.
 */
public InputStream getInputStream() throws IOException {
    if (isReference()) {
        return ((Resource) getCheckedRef()).getInputStream();
    }
    File f = getZipfile();
    if (f == null) {
        return super.getInputStream();
    }

    final ZipFile z = new ZipFile(f, getEncoding());
    ZipArchiveEntry ze = z.getEntry(getName());
    if (ze == null) {
        z.close();
        throw new BuildException("no entry " + getName() + " in " + getArchive());
    }
    return new FilterInputStream(z.getInputStream(ze)) {
        public void close() throws IOException {
            FileUtils.close(in);
            z.close();
        }

        protected void finalize() throws Throwable {
            try {
                close();
            } finally {
                super.finalize();
            }
        }
    };
}

From source file:org.apache.ant.compress.resources.ZipResource.java

/**
 * fetches information from the named entry inside the archive.
 *//*from   w ww . j a va  2 s.  com*/
protected void fetchEntry() {
    File f = getZipfile();
    if (f == null) {
        super.fetchEntry();
        return;
    }

    ZipFile z = null;
    try {
        z = new ZipFile(getZipfile(), getEncoding());
        setEntry(z.getEntry(getName()));
    } catch (IOException e) {
        log(e.getMessage(), Project.MSG_DEBUG);
        throw new BuildException(e);
    } finally {
        ZipFile.closeQuietly(z);
    }
}

From source file:org.apache.brooklyn.rest.resources.CatalogResource.java

@Override
@Beta//from w w w  .j  a va 2  s  .c o  m
public Response createFromArchive(byte[] zipInput) {
    if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.ROOT, null)) {
        throw WebResourceUtils.forbidden("User '%s' is not authorized to add catalog item",
                Entitlements.getEntitlementContext().user());
    }

    BundleMaker bm = new BundleMaker(mgmtInternal());
    File f = null, f2 = null;
    try {
        f = Os.newTempFile("brooklyn-posted-archive", "zip");
        try {
            Files.write(zipInput, f);
        } catch (IOException e) {
            Exceptions.propagate(e);
        }

        ZipFile zf;
        try {
            zf = new ZipFile(f);
        } catch (IOException e) {
            throw new IllegalArgumentException("Invalid ZIP/JAR archive: " + e);
        }
        ZipArchiveEntry bom = zf.getEntry("catalog.bom");
        if (bom == null) {
            bom = zf.getEntry("/catalog.bom");
        }
        if (bom == null) {
            throw new IllegalArgumentException("Archive must contain a catalog.bom file in the root");
        }
        String bomS;
        try {
            bomS = Streams.readFullyString(zf.getInputStream(bom));
        } catch (IOException e) {
            throw new IllegalArgumentException("Error reading catalog.bom from ZIP/JAR archive: " + e);
        }

        try {
            zf.close();
        } catch (IOException e) {
            log.debug("Swallowed exception closing zipfile. Full error logged at trace: {}", e.getMessage());
            log.trace("Exception closing zipfile", e);
        }

        VersionedName vn = BasicBrooklynCatalog.getVersionedName(BasicBrooklynCatalog.getCatalogMetadata(bomS));

        Manifest mf = bm.getManifest(f);
        if (mf == null) {
            mf = new Manifest();
        }
        String bundleNameInMF = mf.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
        if (Strings.isNonBlank(bundleNameInMF)) {
            if (!bundleNameInMF.equals(vn.getSymbolicName())) {
                throw new IllegalArgumentException("JAR MANIFEST symbolic-name '" + bundleNameInMF
                        + "' does not match '" + vn.getSymbolicName() + "' defined in BOM");
            }
        } else {
            bundleNameInMF = vn.getSymbolicName();
            mf.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, bundleNameInMF);
        }

        String bundleVersionInMF = mf.getMainAttributes().getValue(Constants.BUNDLE_VERSION);
        if (Strings.isNonBlank(bundleVersionInMF)) {
            if (!bundleVersionInMF.equals(vn.getVersion().toString())) {
                throw new IllegalArgumentException("JAR MANIFEST version '" + bundleVersionInMF
                        + "' does not match '" + vn.getVersion() + "' defined in BOM");
            }
        } else {
            bundleVersionInMF = vn.getVersion().toString();
            mf.getMainAttributes().putValue(Constants.BUNDLE_VERSION, bundleVersionInMF);
        }
        if (mf.getMainAttributes().getValue(Attributes.Name.MANIFEST_VERSION) == null) {
            mf.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
        }

        f2 = bm.copyAddingManifest(f, mf);

        BasicManagedBundle bundleMetadata = new BasicManagedBundle(bundleNameInMF, bundleVersionInMF, null);
        Bundle bundle;
        try (FileInputStream f2in = new FileInputStream(f2)) {
            bundle = ((ManagementContextInternal) mgmt()).getOsgiManager().get()
                    .installUploadedBundle(bundleMetadata, f2in, false);
        } catch (Exception e) {
            throw Exceptions.propagate(e);
        }

        Iterable<? extends CatalogItem<?, ?>> catalogItems = MutableList
                .copyOf(((ManagementContextInternal) mgmt()).getOsgiManager().get().loadCatalogBom(bundle));

        return buildCreateResponse(catalogItems);
    } catch (RuntimeException ex) {
        throw WebResourceUtils.badRequest(ex);
    } finally {
        if (f != null)
            f.delete();
        if (f2 != null)
            f2.delete();
    }
}