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

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

Introduction

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

Prototype

public ZipFile(String name) throws IOException 

Source Link

Document

Opens the given file for reading, assuming "UTF8".

Usage

From source file:com.nit.async.DeckTask.java

private TaskData doInBackgroundImportReplace(TaskData... params) {
    // Log.i(AnkiDroidApp.TAG, "doInBackgroundImportReplace");
    Collection col = params[0].getCollection();
    String path = params[0].getString();
    Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources();

    // extract the deck from the zip file
    String fileDir = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpzip";
    File dir = new File(fileDir);
    if (dir.exists()) {
        BackupManager.removeDir(dir);/*from www. j  a v a 2 s  . co  m*/
    }

    publishProgress(new TaskData(res.getString(R.string.import_unpacking)));
    // from anki2.py
    String colFile = fileDir + "/collection.anki2";
    ZipFile zip;
    try {
        zip = new ZipFile(new File(path));
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - Error while unzipping: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace0");
        return new TaskData(false);
    }
    if (!Utils.unzipFiles(zip, fileDir, new String[] { "collection.anki2", "media" }, null)
            || !(new File(colFile)).exists()) {
        return new TaskData(-2, null, false);
    }

    Collection tmpCol = null;
    try {
        tmpCol = Storage.Collection(colFile);
        if (!tmpCol.validCollection()) {
            tmpCol.close();
            return new TaskData(-2, null, false);
        }
    } finally {
        if (tmpCol != null) {
            tmpCol.close();
        }
    }

    publishProgress(new TaskData(res.getString(R.string.importing_collection)));
    String colPath;
    if (col != null) {
        // unload collection and trigger a backup
        colPath = col.getPath();
        AnkiDroidApp.closeCollection(true);
        BackupManager.performBackup(colPath, true);
    }
    // overwrite collection
    colPath = AnkiDroidApp.getCollectionPath();
    File f = new File(colFile);
    f.renameTo(new File(colPath));
    int addedCount = -1;
    try {
        col = AnkiDroidApp.openCollection(colPath);

        // because users don't have a backup of media, it's safer to import new
        // data and rely on them running a media db check to get rid of any
        // unwanted media. in the future we might also want to duplicate this step
        // import media
        HashMap<String, String> nameToNum = new HashMap<String, String>();
        HashMap<String, String> numToName = new HashMap<String, String>();
        File mediaMapFile = new File(fileDir, "media");
        if (mediaMapFile.exists()) {
            JsonReader jr = new JsonReader(new FileReader(mediaMapFile));
            jr.beginObject();
            String name;
            String num;
            while (jr.hasNext()) {
                num = jr.nextName();
                name = jr.nextString();
                nameToNum.put(name, num);
                numToName.put(num, name);
            }
            jr.endObject();
            jr.close();
        }
        String mediaDir = col.getMedia().getDir();
        int total = nameToNum.size();
        int i = 0;
        for (Map.Entry<String, String> entry : nameToNum.entrySet()) {
            String file = entry.getKey();
            String c = entry.getValue();
            File of = new File(mediaDir, file);
            if (!of.exists()) {
                Utils.unzipFiles(zip, mediaDir, new String[] { c }, numToName);
            }
            ++i;
            publishProgress(new TaskData(res.getString(R.string.import_media_count, (i + 1) * 100 / total)));
        }
        zip.close();
        // delete tmp dir
        BackupManager.removeDir(dir);

        publishProgress(new TaskData(res.getString(R.string.import_update_counts)));
        // Update the counts
        DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col));
        if (result == null) {
            return null;
        }
        return new TaskData(addedCount, result.getObjArray(), true);
    } catch (RuntimeException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - RuntimeException: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace1");
        return new TaskData(false);
    } catch (FileNotFoundException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - FileNotFoundException: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace2");
        return new TaskData(false);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - IOException: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace3");
        return new TaskData(false);
    }
}

From source file:com.android.tradefed.device.NativeDevice.java

/**
 * {@inheritDoc}/*from   w  w w .j a  va  2s.  c  o  m*/
 */
@Override
public InputStreamSource getBugreport() {
    int apiLevel;
    try {
        apiLevel = getApiLevel();
    } catch (DeviceNotAvailableException e) {
        CLog.e("Device became unavailable while checking API level.");
        CLog.e(e);
        return null;
    }

    if (apiLevel < 24) {
        CollectingByteOutputReceiver receiver = new CollectingByteOutputReceiver();
        try {
            executeShellCommand(BUGREPORT_CMD, receiver, BUGREPORT_TIMEOUT, TimeUnit.MILLISECONDS,
                    0 /* don't retry */);
        } catch (DeviceNotAvailableException e) {
            // Log, but don't throw, so the caller can get the bugreport contents even
            // if the device goes away
            CLog.e("Device %s became unresponsive while retrieving bugreport", getSerialNumber());
        }
        return new ByteArrayInputStreamSource(receiver.getOutput());
    } else {
        CLog.d("Api level above 24, using bugreportz instead.");
        File mainEntry = null;
        File bugreportzFile = null;
        try {
            bugreportzFile = getBugreportzInternal();
            if (bugreportzFile == null) {
                CLog.w("Fail to collect the bugreportz.");
                return bugreportzFallback();
            }
            try (ZipFile zip = new ZipFile(bugreportzFile)) {
                // We get the main_entry.txt that contains the bugreport name.
                mainEntry = ZipUtil2.extractFileFromZip(zip, "main_entry.txt");
                String bugreportName = FileUtil.readStringFromFile(mainEntry).trim();
                CLog.d("bugreport name: '%s'", bugreportName);
                File bugreport = ZipUtil2.extractFileFromZip(zip, bugreportName);
                return new FileInputStreamSource(bugreport, true);
            }
        } catch (IOException e) {
            CLog.e("Error while unzipping bugreportz");
            CLog.e(e);
            return bugreportzFallback();
        } finally {
            FileUtil.deleteFile(bugreportzFile);
            FileUtil.deleteFile(mainEntry);
        }
    }
}

From source file:net.sourceforge.pmd.it.ZipFileExtractor.java

/**
 * Extracts the given zip file into the tempDir.
 * @param zipPath the zip file to extract
 * @param tempDir the target directory/*from ww w  .  ja  v a2  s. c o  m*/
 * @throws Exception if any error happens during extraction
 */
public static void extractZipFile(Path zipPath, Path tempDir) throws Exception {
    ZipFile zip = new ZipFile(zipPath.toFile());
    try {
        Enumeration<ZipArchiveEntry> entries = zip.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            File file = tempDir.resolve(entry.getName()).toFile();
            if (entry.isDirectory()) {
                assertTrue(file.mkdirs());
            } else {
                try (InputStream data = zip.getInputStream(entry);
                        OutputStream fileOut = new FileOutputStream(file);) {
                    IOUtils.copy(data, fileOut);
                }
                if ((entry.getUnixMode() & OWNER_EXECUTABLE) == OWNER_EXECUTABLE) {
                    file.setExecutable(true);
                }
            }
        }
    } finally {
        zip.close();
    }
}

From source file:net.test.aliyun.oss.ImportShooterData.java

@Override
public void onStart(AppContext appContext) throws Throwable {
    String BasePath = "D:/shooterData/";
    OSSClient client = appContext.getInstance(OSSClient.class);
    String tempPath = appContext.getEnvironment().envVar(Environment.HASOR_TEMP_PATH);
    ///*w w w .  jav a  2  s  . c o  m*/
    File[] zipPacks = new File(BasePath).listFiles();
    long intCount = 0;
    long size = 0;
    for (File zipfile : zipPacks) {
        String fileName = zipfile.getName();
        fileName = fileName.split("\\.")[0];
        ZipFile zipPack = new ZipFile(zipfile);
        Enumeration<ZipArchiveEntry> enumZip = zipPack.getEntries();
        System.out.println(fileName);
        while (enumZip.hasMoreElements()) {
            ZipArchiveEntry ent = enumZip.nextElement();
            if (ent.isDirectory() == true) {
                continue;
            }
            String itemName = ent.getName();
            //
            //            ObjectMetadata info = this.passInfo(tempPath, zipPack, ent);
            //            info.addUserMetadata("oldFileName", itemName);
            //
            //            String key = fileName + "/" + UUID.randomUUID().toString().replace("-", "") + ".rar";
            //InputStream inStream = zipPack.getInputStream(ent);
            //PutObjectResult res = client.putObject("files-subtitle", key, inStream, info);
            //
            intCount++;
            long itemSize = ent.getSize();
            String stated = String.format("%s-%s/%s\t%s\t%s", intCount, fileName, itemName, itemSize, "");
            System.out.println(stated + " -> " + "");
            size = size + itemSize;
        }
        zipPack.close();
    }
    System.out.println(intCount + "\t" + size);
}

From source file:org.abysm.onionzip.ZipFileExtractHelper.java

void setEncodingByDetection() throws IOException {
    UniversalDetector filenameCharsetDetector = new UniversalDetector(null);
    ZipFile zipFile = new ZipFile(zipFilename);
    try {/*from www.  j a va2s.com*/
        for (Enumeration<ZipArchiveEntry> zipArchiveEntryEnumeration = zipFile
                .getEntries(); zipArchiveEntryEnumeration.hasMoreElements();) {
            ZipArchiveEntry entry = zipArchiveEntryEnumeration.nextElement();
            if (!entry.getGeneralPurposeBit().usesUTF8ForNames()) {
                byte[] filename = entry.getRawName();
                filenameCharsetDetector.handleData(filename, 0, filename.length);
            }
        }
    } finally {
        ZipFile.closeQuietly(zipFile);
    }
    filenameCharsetDetector.dataEnd();
    this.encoding = filenameCharsetDetector.getDetectedCharset();
}

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   w  ww  .  j a va 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.brooklyn.rest.resources.CatalogResource.java

@Override
@Beta/*from   w ww . j av a2  s  . c om*/
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();
    }
}

From source file:org.apache.james.mailbox.backup.ZipAssertTest.java

@Test
public void hasNoEntryShouldNotThrowWhenEmpty() throws Exception {
    try (ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(destination)) {
        archiveOutputStream.finish();//from  w ww. j av a 2 s .  co m
    }

    try (ZipFile zipFile = new ZipFile(destination)) {
        assertThatCode(() -> assertThatZip(zipFile).hasNoEntry()).doesNotThrowAnyException();
    }
}

From source file:org.apache.james.mailbox.backup.ZipAssertTest.java

@Test
public void hasNoEntryShouldThrowWhenNotEmpty() throws Exception {
    try (ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(destination)) {

        ZipArchiveEntry archiveEntry = (ZipArchiveEntry) archiveOutputStream.createArchiveEntry(new File("any"),
                ENTRY_NAME);/*from w  w w.j a v  a2 s .  com*/
        archiveOutputStream.putArchiveEntry(archiveEntry);
        IOUtils.copy(new ByteArrayInputStream(ENTRY_CONTENT), archiveOutputStream);
        archiveOutputStream.closeArchiveEntry();

        archiveOutputStream.finish();
    }

    try (ZipFile zipFile = new ZipFile(destination)) {
        assertThatThrownBy(() -> assertThatZip(zipFile).hasNoEntry()).isInstanceOf(AssertionError.class);
    }
}

From source file:org.apache.james.mailbox.backup.ZipAssertTest.java

@Test
public void containsExactlyEntriesMatchingShouldNotThrowWhenBothEmpty() throws Exception {
    try (ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(destination)) {
        archiveOutputStream.finish();/*from   w  w w.j a va  2 s .com*/
    }

    try (ZipFile zipFile = new ZipFile(destination)) {
        assertThatCode(() -> assertThatZip(zipFile).containsOnlyEntriesMatching()).doesNotThrowAnyException();
    }
}