Example usage for java.util.zip ZipFile ZipFile

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

Introduction

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

Prototype

public ZipFile(File file, Charset charset) throws IOException 

Source Link

Document

Opens a ZIP file for reading given the specified File object.

Usage

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 {/*from  w  w  w.ja  va 2s.co 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:com.aurel.track.dbase.InitReportTemplateBL.java

public static void addReportTemplates() {
    URL urlSrc;//from w ww.j  av  a 2s  .  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 av  a 2  s. c  o  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());
    }/* w  ww  .ja v a 2s  .c  o  m*/
    zipFile.close();

    // sort
    Collections.sort(acc);

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

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

public Publication parseFile(File file) {
    Publication p = super.parseFile(file);
    Format format = new Format(EPUB_FORMAT);
    pathThumbnailSourceRelativeToOPF = null;
    coverManifestItemID = null;/*from  w w  w. j  a va2  s.  c om*/

    String OPFPath = this.getOPFPath(file);
    if (OPFPath != null) {
        try {
            ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ);
            ZipEntry OPFEntry = zipFile.getEntry(OPFPath);
            if (OPFEntry != null) {

                InputStream is;

                // first pass: parse metadata
                is = zipFile.getInputStream(OPFEntry);
                parser = Xml.newPullParser();
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                parser.setInput(is, null);
                parser.nextTag();
                this.parsePackage(format, 1);
                is.close();

                // second pass: parse manifest
                is = zipFile.getInputStream(OPFEntry);
                parser = Xml.newPullParser();
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                parser.setInput(is, null);
                parser.nextTag();
                this.parsePackage(format, 2);
                is.close();

                // item is valid
                p.isValid(true);

                // set the cover path, relative to the EPUB container (aka ZIP) root
                if (pathThumbnailSourceRelativeToOPF != null) {
                    // concatenate OPFPath parent directory and pathThumbnailSourceRelativeToOPF
                    File tmp = new File(new File(OPFPath).getParent(), pathThumbnailSourceRelativeToOPF);
                    // remove leading "/"
                    format.addMetadatum("internalPathCover", tmp.getAbsolutePath().substring(1));
                }

            }
            zipFile.close();
        } catch (Exception e) {
            // invalidate item, so it will not be added to library
            p.isValid(false);
        }
    }

    p.addFormat(format);

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

    return p;
}

From source file:eionet.gdem.utils.ZipUtil.java

/**
 * Unzips files to output directory.//from   w  ww  .j  av  a  2  s . c o m
 * @param inZip Zip file
 * @param outDir Output directory
 * @throws IOException If an error occurs.
 */
public static void unzip(String inZip, String outDir) throws IOException {

    File sourceZipFile = new File(inZip);
    File unzipDestinationDirectory = new File(outDir);

    // Open Zip file for reading
    ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

    // Create an enumeration of the entries in the zip file
    Enumeration zipFileEntries = zipFile.entries();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
        // grab a zip file entry
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();

        String currentEntry = entry.getName();
        // System.out.println("Extracting: " + entry);

        File destFile = new File(unzipDestinationDirectory, currentEntry);

        // grab file's parent directory structure
        File destinationParent = destFile.getParentFile();

        // create the parent directory structure if needed
        destinationParent.mkdirs();

        // extract file if not a directory
        if (!entry.isDirectory()) {
            BufferedInputStream is = null;
            BufferedOutputStream dest = null;
            try {
                is = new BufferedInputStream(zipFile.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte[] data = new byte[BUFFER];

                // write the current file to disk
                FileOutputStream fos = new FileOutputStream(destFile);
                dest = new BufferedOutputStream(fos, BUFFER);

                // read and write until last byte is encountered
                while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, currentByte);
                }
            } finally {
                IOUtils.closeQuietly(dest);
                IOUtils.closeQuietly(is);
            }
        }
    }
    zipFile.close();
}

From source file:com.ichi2.libanki.sync.RemoteMediaServer.java

/**
 * args: files//from   w w w.ja va2  s .  co m
 * <br>
 * This method returns a ZipFile with the OPEN_DELETE flag, ensuring that the file on disk will
 * be automatically deleted when the stream is closed.
 */
public ZipFile downloadFiles(List<String> top) throws UnknownHttpResponseException {
    try {
        HttpResponse resp;
        resp = super.req("downloadFiles",
                super.getInputStream(Utils.jsonToString(new JSONObject().put("files", new JSONArray(top)))));
        String zipPath = mCol.getPath().replaceFirst("collection\\.anki2$", "tmpSyncFromServer.zip");
        // retrieve contents and save to file on disk:
        super.writeToFile(resp.getEntity().getContent(), zipPath);
        return new ZipFile(new File(zipPath), ZipFile.OPEN_READ | ZipFile.OPEN_DELETE);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Timber.e(e, "Failed to download requested media files");
        throw new RuntimeException(e);
    }
}

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

protected List<ZipAsset> getSortedListOfAssets(String path, String[] allowedExtensions) {
    List<ZipAsset> assets = new ArrayList<ZipAsset>();
    try {/*from   www .  ja v  a2 s  .c  om*/
        // 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:it.readbeyond.minstrel.unzipper.Unzipper.java

private String unzip(String inputZip, String destinationDirectory, String mode, JSONObject parameters)
        throws IOException, JSONException {

    // store the zip entries to decompress
    List<String> list = new ArrayList<String>();

    // store the zip entries actually decompressed
    List<String> decompressed = new ArrayList<String>();

    // open input zip file
    File sourceZipFile = new File(inputZip);
    ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

    // open destination directory, creating it if needed    
    File unzipDestinationDirectory = new File(destinationDirectory);
    unzipDestinationDirectory.mkdirs();/*  w ww. j a v a 2  s. co  m*/

    // extract all files
    if (mode.equals(ARGUMENT_MODE_ALL)) {
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            list.add(zipFileEntries.nextElement().getName());
        }
    }

    // extract all files except audio and video
    // (determined by file extension)
    if (mode.equals(ARGUMENT_MODE_ALL_NON_MEDIA)) {
        String[] excludeExtensions = JSONArrayToStringArray(
                parameters.optJSONArray(ARGUMENT_ARGS_EXCLUDE_EXTENSIONS));
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            String name = zipFileEntries.nextElement().getName();
            String lower = name.toLowerCase();
            if (!isFile(lower, excludeExtensions)) {
                list.add(name);
            }
        }
    }

    // extract all small files
    // maximum size is passed in args parameter
    // or, if not passed, defaults to const DEFAULT_MAXIMUM_SIZE_FILE
    if (mode.equals(ARGUMENT_MODE_ALL_SMALL)) {
        long maximum_size = parameters.optLong(ARGUMENT_ARGS_MAXIMUM_FILE_SIZE, DEFAULT_MAXIMUM_SIZE_FILE);
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry ze = zipFileEntries.nextElement();
            if (ze.getSize() <= maximum_size) {
                list.add(ze.getName());
            }
        }
    }

    // extract only the requested files
    if (mode.equals(ARGUMENT_MODE_SELECTED)) {
        String[] entries = JSONArrayToStringArray(parameters.optJSONArray(ARGUMENT_ARGS_ENTRIES));
        for (String entry : entries) {
            ZipEntry ze = zipFile.getEntry(entry);
            if (ze != null) {
                list.add(entry);
            }
        }
    }

    // extract all "structural" files
    if (mode.equals(ARGUMENT_MODE_ALL_STRUCTURE)) {
        String[] extensions = JSONArrayToStringArray(parameters.optJSONArray(ARGUMENT_ARGS_EXTENSIONS));
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            String name = zipFileEntries.nextElement().getName();
            String lower = name.toLowerCase();
            boolean extract = isFile(lower, extensions);
            if (extract) {
                list.add(name);
            }
        }
    }

    // NOTE list contains only valid zip entries
    // perform unzip
    for (String currentEntry : list) {
        ZipEntry entry = zipFile.getEntry(currentEntry);
        File destFile = new File(unzipDestinationDirectory, currentEntry);

        File destinationParent = destFile.getParentFile();
        destinationParent.mkdirs();

        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
            int numberOfBytesRead;
            byte data[] = new byte[BUFFER_SIZE];
            FileOutputStream fos = new FileOutputStream(destFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE);
            while ((numberOfBytesRead = is.read(data, 0, BUFFER_SIZE)) > -1) {
                dest.write(data, 0, numberOfBytesRead);
            }
            dest.flush();
            dest.close();
            is.close();
            fos.close();
            decompressed.add(currentEntry);
        }
    }

    zipFile.close();
    return stringify(decompressed);
}

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

private List<ZipAsset> parseM3UPlaylistEntry(String path, String playlistEntry) {
    List<ZipAsset> assets = new ArrayList<ZipAsset>();
    try {//www .  j a v a  2s  . c o  m
        ZipFile zipFile = new ZipFile(new File(path), ZipFile.OPEN_READ);
        ZipEntry ze = zipFile.getEntry(playlistEntry);
        String text = this.getZipEntryText(zipFile, ze);
        String[] lines = text.split("\n");

        // check that the first line starts with the M3U header
        if ((lines.length > 0) && (lines[0].startsWith(ABZ_M3U_HEADER))) {
            for (int i = 1; i < lines.length; i++) {
                String line = lines[i].trim();

                // if line starts with the M3U preamble, parse it
                if (line.startsWith(ABZ_M3U_LINE_PREAMBLE)) {
                    HashMap<String, String> meta = new HashMap<String, String>();

                    // get track duration and title 
                    Matcher m = ABZ_M3U_LINE_PATTERN.matcher(line);
                    if (m.find()) {
                        meta.put("duration", m.group(1));
                        meta.put("title", m.group(2));
                    }
                    String line2 = lines[i + 1].trim();

                    // generate entry path
                    File w = new File(new File(playlistEntry).getParent(), line2);
                    line2 = w.getAbsolutePath().substring(1);

                    // add asset
                    assets.add(new ZipAsset(line2, meta));

                    // go to the next pair of lines
                    i += 1;
                }
            }
        }

        // close ZIP
        zipFile.close();
    } catch (Exception e) {
        // nothing
    }
    return assets;
}