Example usage for java.util.zip ZipFile OPEN_READ

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

Introduction

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

Prototype

int OPEN_READ

To view the source code for java.util.zip ZipFile OPEN_READ.

Click Source Link

Document

Mode flag to open a zip file for reading.

Usage

From source file:org.esa.snap.util.ZipUtils.java

public static String getRootFolder(final File file, final String headerFileName) throws IOException {
    final ZipFile productZip = new ZipFile(file, ZipFile.OPEN_READ);

    final Optional result = productZip.stream().filter(ze -> !ze.isDirectory())
            .filter(ze -> ze.getName().toLowerCase().endsWith(headerFileName)).findFirst();
    ZipEntry ze = (ZipEntry) result.get();
    String path = ze.toString();//from  ww w.ja va 2 s.  co m
    int sepIndex = path.lastIndexOf('/');
    if (sepIndex > 0) {
        return path.substring(0, sepIndex) + '/';
    } else {
        return "";
    }
}

From source file:org.nosphere.honker.deptree.DepTreeFilesLoader.java

private List<DepTreeData.SomeFile> loadFilesFromZip(File zipFile) {
    ZipFile zip = null;//  w  w  w .ja  v  a2  s .  co m
    try {
        zip = new ZipFile(zipFile, ZipFile.OPEN_READ);
        List<DepTreeData.SomeFile> files = new ArrayList<>();
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String basename = StringUtils.substringAfterLast(entry.getName(), "/");
            String extension = FilenameUtils.getExtension(basename);
            if (!StringUtils.isEmpty(extension)) {
                basename = FilenameUtils.removeExtension(basename);
            }
            basename = basename.toLowerCase();
            if (BASENAMES.contains(basename)) {
                InputStream fileStream = zip.getInputStream(entry);
                try {
                    String content = IOUtils.toString(fileStream, "UTF-8");
                    files.add(new DepTreeData.SomeFile(basename, entry.getName(), content));
                } finally {
                    IOUtils.closeQuietly(fileStream);
                }
            }
        }
        return files;
    } catch (IOException ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException ignored) {
                // Ignored
            }
        }
    }
}

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

public Publication parseFile(File file) {
    Publication p = super.parseFile(file);

    Format format = new Format(CBZ_FORMAT);

    try {/*from   ww w.ja va2  s .c om*/
        ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ);
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        boolean foundMetadataFile = false;
        boolean foundCover = false;
        boolean foundPlaylist = false;
        String zeCover = null;
        String zePlaylist = null;
        List<String> assets = new ArrayList<String>();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry ze = zipFileEntries.nextElement();
            String name = ze.getName();
            String lower = name.toLowerCase();

            if (lower.endsWith(CBZ_DEFAULT_COVER_JPG) || lower.endsWith(CBZ_DEFAULT_COVER_PNG)) {
                p.isValid(true);
                zeCover = name;
                assets.add(name);
            } else if (lower.endsWith(CBZ_FILE_PLAYLIST)) {
                zePlaylist = name;
            } else if (this.fileHasAllowedExtension(lower, CBZ_IMAGE_EXTENSIONS)) {
                p.isValid(true);
                assets.add(name);
            } else if (lower.endsWith(CBZ_FILE_METADATA)) {
                p.isValid(true);
                foundMetadataFile = true;
                if (this.parseMetadataFile(zipFile, ze, format)) {
                    if (format.getMetadatum("internalPathPlaylist") != null) {
                        foundPlaylist = true;
                    }
                    if (format.getMetadatum("internalPathCover") != null) {
                        foundCover = true;
                    }
                }
            } // end if metadata
        } // end while
        zipFile.close();

        // set cover
        if (!foundCover) {
            // no cover found from metadata
            // found default?
            if (zeCover != null) {
                // use default
                format.addMetadatum("internalPathCover", zeCover);
            } else {
                // sort and use the first image found
                if (assets.size() > 0) {
                    Collections.sort(assets);
                    format.addMetadatum("internalPathCover", assets.get(0));
                }
            }
        }

        // default playlist found?
        if ((!foundPlaylist) && (zePlaylist != null)) {
            format.addMetadatum("internalPathPlaylist", zePlaylist);
        }

        // set number of assets
        format.addMetadatum("numberOfAssets", "" + assets.size());

    } catch (Exception e) {
        // invalidate publication, so it will not be added to library
        p.isValid(false);
    } // end try

    p.addFormat(format);

    // extract cover
    super.extractCover(file, format, p.getID());

    return p;
}

From source file:org.esa.snap.engine_utilities.util.ZipUtils.java

public static boolean findInZip(final File file, final String prefix, final String suffix) {
    try {//from  w  w w .  j a  va  2  s. c om
        final ZipFile productZip = new ZipFile(file, ZipFile.OPEN_READ);

        final Optional result = productZip.stream().filter(ze -> !ze.isDirectory())
                .filter(ze -> ze.getName().toLowerCase().endsWith(suffix))
                .filter(ze -> ze.getName().toLowerCase().startsWith(prefix)).findFirst();
        return result.isPresent();
    } catch (Exception e) {
        SystemUtils.LOG.warning("unable to read zip file " + file + ": " + e.getMessage());
    }
    return false;
}

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

public Publication parseFile(File file) {
    Publication p = super.parseFile(file);

    Format format = new Format(ABZ_FORMAT);

    try {/*  w w  w.  ja  v a2  s .  c o m*/
        ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ);
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        boolean foundMetadataFile = false;
        boolean foundCover = false;
        boolean foundPlaylist = false;
        String zeCover = null;
        String zePlaylist = null;
        List<String> assets = new ArrayList<String>();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry ze = zipFileEntries.nextElement();
            String name = ze.getName();
            String lower = name.toLowerCase();

            if (lower.endsWith(ABZ_DEFAULT_COVER_JPG) || lower.endsWith(ABZ_DEFAULT_COVER_PNG)) {
                zeCover = name;
            } else if (lower.endsWith(ABZ_EXTENSION_PLAYLIST)) {
                zePlaylist = name;
            } else if (this.fileHasAllowedExtension(lower, ABZ_AUDIO_EXTENSIONS)) {
                p.isValid(true);
                assets.add(name);
            } else if (lower.endsWith(ABZ_FILE_METADATA)) {
                p.isValid(true);
                foundMetadataFile = true;
                if (this.parseMetadataFile(zipFile, ze, format)) {
                    if (format.getMetadatum("internalPathPlaylist") != null) {
                        foundPlaylist = true;
                    }
                    if (format.getMetadatum("internalPathCover") != null) {
                        foundCover = true;
                    }
                }
            } // end if metadata
        } // end while
        zipFile.close();

        // set cover
        if ((!foundCover) && (zeCover != null)) {
            format.addMetadatum("internalPathCover", zeCover);
        }

        // default playlist found?
        if ((!foundPlaylist) && (zePlaylist != null)) {
            format.addMetadatum("internalPathPlaylist", zePlaylist);
        }

        // set number of assets
        format.addMetadatum("numberOfAssets", "" + assets.size());

    } catch (Exception e) {
        // invalidate publication, so it will not be added to library
        p.isValid(false);
    } // end try

    p.addFormat(format);

    // extract cover
    super.extractCover(file, format, p.getID());

    return p;
}

From source file:org.wso2.carbon.uuf.internal.io.util.ZipArtifactHandler.java

public static Path unzip(String appName, Path zipFile) {
    Path appDirectory = TEMP_DIRECTORY.resolve(appName);
    if (Files.exists(appDirectory)) {
        /* A directory already exists in the tmp folder with the same app name, delete it before unzipping the
        new app. *///  ww  w .j a  v  a2s . c om
        try {
            FileUtils.deleteDirectory(appDirectory.toFile());
        } catch (IOException e) {
            throw new FileOperationException(
                    "An error occurred while deleting directory '" + appDirectory + "'.");
        }
        log.debug("Removed the existing app directory '" + appDirectory + "' before extracting app '" + appName
                + "'.");
    }

    ZipFile zip;
    try {
        zip = new ZipFile(zipFile.toFile(), ZipFile.OPEN_READ);
    } catch (IOException e) {
        throw new FileOperationException("Cannot open zip artifact '" + zipFile + "' to extract.", e);
    }
    try {
        Enumeration<? extends ZipEntry> zipEntries = zip.entries();
        while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = zipEntries.nextElement();
            if (zipEntry.isDirectory()) {
                createDirectory(TEMP_DIRECTORY.resolve(zipEntry.getName()));
            } else {
                Path tempFilePath = TEMP_DIRECTORY.resolve(zipEntry.getName());
                // Here 'tempFilePath.getParent()' is never null.
                createDirectory(tempFilePath.getParent());
                try (InputStream inputStream = zip.getInputStream(zipEntry)) {
                    Files.copy(inputStream, tempFilePath);
                } catch (IOException e) {
                    throw new FileOperationException("Cannot copy content of zip entry '" + zipEntry.getName()
                            + "' in zip artifact '" + zipFile + "' to temporary file '" + tempFilePath + "'.",
                            e);
                }
            }
        }
    } finally {
        // Close zip file.
        IOUtils.closeQuietly(zip);
    }

    return appDirectory;
}

From source file:org.esa.snap.engine_utilities.util.ZipUtils.java

public static String getRootFolder(final File file, final String headerFileName) throws IOException {
    final ZipFile productZip = new ZipFile(file, ZipFile.OPEN_READ);

    final Optional result = productZip.stream().filter(ze -> !ze.isDirectory())
            .filter(ze -> ze.getName().toLowerCase().endsWith(headerFileName)).findFirst();
    if (result.isPresent()) {
        ZipEntry ze = (ZipEntry) result.get();
        String path = ze.toString();
        int sepIndex = path.lastIndexOf('/');
        if (sepIndex > 0) {
            return path.substring(0, sepIndex) + '/';
        } else {//from ww w.j  a  va  2s.  c o  m
            return "";
        }
    }
    return "";
}

From source file:com.aurel.track.dbase.InitReportTemplateBL.java

public static void addReportTemplates() {
    URL urlSrc;//from   ww w  .  jav a2s . c o  m
    File srcDir = null;
    //first try to get the template dir through class.getResource(path)
    urlSrc = PluginUtils.class.getResource("/resources/reportTemplates");
    urlSrc = PluginUtils.createValidFileURL(urlSrc);
    if (urlSrc != null) {
        LOGGER.info("Retrieving report templates from " + urlSrc.toString());
        srcDir = new File(urlSrc.getPath());
        Long uuid = new Date().getTime();
        File tmpDir = new File(
                System.getProperty("java.io.tmpdir") + File.separator + "TrackTmp" + uuid.toString());
        if (!tmpDir.isDirectory()) {
            tmpDir.mkdir();
        }
        tmpDir.deleteOnExit();

        File[] files = srcDir.listFiles(new InitReportTemplateBL.Filter());
        if (files == null || files.length == 0) {
            LOGGER.error("Problem unzipping report template: No files.");
            return;
        }
        for (int index = 0; index < files.length; index++) {
            ZipFile zipFile = null;
            try {
                String sname = files[index].getName();
                String oid = sname.substring(sname.length() - 6, sname.length() - 4);
                zipFile = new ZipFile(files[index], ZipFile.OPEN_READ);
                LOGGER.debug("Extracting template from " + files[index].getName());
                unzipFileIntoDirectory(zipFile, tmpDir);

                File descriptor = new File(tmpDir, "description.xml");
                InputStream in = new FileInputStream(descriptor);
                //parse using builder to get DOM representation of the XML file
                Map<String, Object> desc = ReportBL.getTemplateDescription(in);

                String rname = "The name";
                String description = "The description";
                String expfmt = (String) desc.get("format");

                Map<String, String> localizedStuff = (Map<String, String>) desc
                        .get("locale_" + Locale.getDefault().getLanguage());
                if (localizedStuff != null) {
                    rname = localizedStuff.get("listing");
                    description = localizedStuff.get("description");
                } else {
                    localizedStuff = (Map<String, String>) desc.get("locale_en");
                    rname = localizedStuff.get("listing");
                    description = localizedStuff.get("description");
                }

                addReportTemplateToDatabase(new Integer(oid), rname, expfmt, description);

            } catch (IOException e) {
                LOGGER.error("Problem unzipping report template " + files[index].getName());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    }
}

From source file:com.hichinaschool.flashcards.libanki.importer.Anki2Importer.java

public Anki2Importer(Collection col, String file, DeckTask.ProgressCallback progressCallback)
        throws IOException {
    mCol = col;//  w w w .  j a v a  2  s .co m
    mZip = new ZipFile(new File(file), ZipFile.OPEN_READ);
    mTotal = 0;
    mLog = new ArrayList<String>();
    mProgress = progressCallback;
    if (mProgress != null) {
        mResources = mProgress.getResources();
    }
    nameToNum = new HashMap<String, String>();
}

From source file:it.readbeyond.minstrel.unzipper.Unzipper.java

private String list(String inputZip) throws IOException, JSONException {
    // list all files
    List<String> acc = new ArrayList<String>();
    File sourceZipFile = new File(inputZip);
    ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
    Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
    while (zipFileEntries.hasMoreElements()) {
        acc.add(zipFileEntries.nextElement().getName());
    }/*from   www  .  j a  v a 2s. c  o m*/
    zipFile.close();

    // sort
    Collections.sort(acc);

    // return JSON string
    return stringify(acc);
}