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:nl.edia.sakai.tool.skinmanager.impl.SkinFileSystemServiceImpl.java

protected void validateSkinZip(File file) throws SkinException {
    ZipFile myZipFile = null;
    try {//from   w w w . ja  va2s  .  co m
        boolean isToolFound = false;
        boolean isPortalFound = false;
        boolean isImagesFound = false;
        myZipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> myEntries = myZipFile.entries();
        while (myEntries.hasMoreElements()) {
            ZipEntry myZipEntry = (ZipEntry) myEntries.nextElement();
            String myName = myZipEntry.getName();
            if (myName.contains("..") || myName.startsWith("/")) {
                throw new SkinException("Illegal file name found in zip file '" + myName + "'");
            }
            if (!myZipEntry.isDirectory()) {
                if (myName.equals("tool.css")) {
                    isToolFound = true;
                } else if (myName.equals("portal.css")) {
                    isPortalFound = true;
                } else if (PATTERN_IMAGES_DIR_CONTENT.matcher(myName).matches()) {
                    isImagesFound = true;
                }
            } else {
                if (PATTERN_IMAGES_DIR_EMPTY.matcher(myName).matches()) {
                    isImagesFound = true;
                }
            }
        }

        if (!isPortalFound) {
            throw getMissingResourceException("portal.css", false);
        }
        if (!isToolFound) {
            throw getMissingResourceException("tool.css", false);
        }
        if (!isImagesFound) {
            throw getMissingResourceException("images", true);
        }
    } catch (ZipException z) {
        throw new SkinException("Error reading zip file", z);
    } catch (IOException e) {
        throw new SkinException("IO Error reading zip file", e);
    } finally {
        if (myZipFile != null) {
            try {
                myZipFile.close();
            } catch (IOException e) {
                // ignore
            }
        }

    }

}

From source file:it.polito.tellmefirst.web.rest.clients.ClientEpub.java

private HashMap<String, String> parseEpub(File file) throws IOException, TMFVisibleException {

    LOG.debug("[parseEpub] - BEGIN");

    ZipFile fi = new ZipFile(file);

    for (Enumeration e = fi.entries(); e.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) e.nextElement();
        if (entry.getName().endsWith("ncx")) {
            InputStream tocMaybeDirty = fi.getInputStream(entry);
            Scanner scanner = new Scanner(tocMaybeDirty, "UTF-8").useDelimiter("\\A");
            String theString = scanner.hasNext() ? scanner.next() : "";
            tocMaybeDirty.close();//from   w  w w .  ja  v a2 s . c  om
            scanner.close();

            String res = theString.replaceAll(">[\\s]*?<", "><");

            InputStream toc = new ByteArrayInputStream(res.getBytes(StandardCharsets.UTF_8));

            try {
                DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document doc = dBuilder.parse(toc);
                toc.close();

                if (doc.hasChildNodes()) {
                    findNavMap(doc.getChildNodes());
                }
            } catch (Exception ex) {
                LOG.error("Unable to navigate the TOC");
            }

            removeEmptyTOC(epub);

            //search anchors in links and split
            Set set = epub.entrySet();
            Iterator i = set.iterator();
            while (i.hasNext()) {
                Map.Entry me = (Map.Entry) i.next();
                if (me.getValue().toString().contains("#")) {
                    String[] parts = me.getValue().toString().split("#");
                    String anchor = parts[1];
                    epub.put(me.getKey().toString(), anchor);
                }
            }
        }
        if (entry.getName().endsWith("opf")) { //manage files because order is important
            InputStream content = fi.getInputStream(entry);

            Scanner scanner = new Scanner(content, "UTF-8").useDelimiter("\\A");
            String contentString = scanner.hasNext() ? scanner.next() : "";
            content.close();
            scanner.close();

            String filenameRegex = "href=\"(.*.htm(|l))\".*media-type=\"application/xhtml";
            Pattern pattern = Pattern.compile(filenameRegex);
            Matcher matcher = pattern.matcher(contentString);

            Integer count = 0;
            while (matcher.find()) {
                files.put(count, matcher.group(1));
                count++;
            }
        }
        if (entry.getName().endsWith("html") || entry.getName().endsWith("htm")
                || entry.getName().endsWith("xhtml")) {
            InputStream htmlFile = fi.getInputStream(entry);

            Scanner scanner = new Scanner(htmlFile, "UTF-8").useDelimiter("\\A");
            String htmlString = scanner.hasNext() ? scanner.next() : "";

            String regex1 = htmlString.replaceAll("^[^_]*?<body>", ""); //remove head
            String regex2 = regex1.replaceAll("</body>.*$", ""); //remove tail
            String htmlCleaned = regex2.replaceAll("<a.*?/>", ""); //anchor with one tag

            String[] bits = entry.getName().split("/");
            String fileName = bits[bits.length - 1];

            htmls.put(fileName, htmlCleaned);
        }
    }
    fi.close();
    Integer i;
    for (i = 0; i < files.size(); i++) {
        stringBuilder.append("<p id=\"" + files.get(i) + "\"></p>"); // "anchor" also the heads of each files
        stringBuilder.append(htmls.get(files.get(i)));
    }
    String htmlAll = stringBuilder.toString();

    /* We have all needed files, start to split
       For each link -> made a chunk
       Start from the bottom */
    Metadata metadata = new Metadata();
    Parser parser = new HtmlParser();
    ListIterator<Map.Entry<String, String>> iter = new ArrayList<>(epub.entrySet()).listIterator(epub.size());

    while (iter.hasPrevious()) {
        Map.Entry<String, String> me = iter.previous();
        try {
            ContentHandler contenthandler = new BodyContentHandler(10 * htmlAll.length());
            Scanner sc = new Scanner(htmlAll);
            sc.useDelimiter("id=\"" + me.getValue().toString() + "\">");
            htmlAll = sc.next();
            InputStream stream = new ByteArrayInputStream(sc.next().getBytes(StandardCharsets.UTF_8));
            parser.parse(stream, contenthandler, metadata, new ParseContext());
            String chapterText = contenthandler.toString().toLowerCase().replaceAll("\\d+.*", "");
            String chapterTextWithoutNo = chapterText.replaceAll("\\d+.*", "");
            // Remove the Project Gutenberg meta information from the text
            String chapterTextCleaned = chapterTextWithoutNo.split("end of the project gutenberg ebook")[0];
            epub.put(me.getKey().toString(), chapterTextCleaned);

        } catch (Exception ex) {
            LOG.error("Unable to parse content for index: " + me.getKey() + ", this chapter will be deleted");
            removeChapter(epub, me.getKey().toString());
        }
    }

    /* I remove the Project Gutenberg license chapter from the Map, because it is useless
      for the classification and it generates a Lucene Exception in case of the Italian language
      (the license text is always in English).
            
      You can use this method in order to remove each chapter that is useless for classifying
      your Epub document. */
    removeChapter(epub, "A Word from Project Gutenberg");
    removeEmptyItems(epub);

    //If the Epub file has a bad structure, I try to use the basic Epub extractor of Tika.
    if (epub.size() == 0) {
        LOG.info("The Epub file has a bad structure. Try to use the Tika extractor");
        epub.put("All text", autoParseAll(file));
    }

    removeEmptyItems(epub);

    if (epub.size() == 0) {
        LOG.error("Unable to extract text from this Epub");
        throw new TMFVisibleException("Unable to extract any text from this Epub.");
    }

    removeDownloadedFile(TEMPORARY_PATH);

    LOG.debug("[parseEpub] - END");

    return epub;
}

From source file:org.dspace.installer_edm.InstallerEDMAskosi.java

/**
 * Descomprime el zip y copia los archivos a un directorio
 *
 * @param sourcePackageFile archivo zip//from w  w w  .  ja v a 2 s .c  om
 * @param destDir directorio destino de la copia
 * @return   xito de la copia
 */
private boolean copyPackageZipFile(File sourcePackageFile, String destDir) {
    try {
        // lectura de los archivos que componen el zip
        ZipFile zf = new ZipFile(sourcePackageFile.getAbsolutePath());
        Enumeration entries = zf.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.isDirectory()) {
                File dirAux = new File(destDir + entry.getName());
                if (!dirAux.exists() && !dirAux.mkdir()) {
                    installerEDMDisplay.showQuestion(currentStepGlobal, "copyPackageZipFile.failcreate",
                            new String[] { dirAux.getAbsolutePath() });
                }
            } else {
                if (verbose)
                    installerEDMDisplay.showQuestion(currentStepGlobal, "copyPackageZipFile.extract",
                            new String[] { entry.getName() });
                int index = entry.getName().lastIndexOf(47);
                if (index == -1) {
                    index = entry.getName().lastIndexOf(92);
                }
                if (index > 0) {
                    File dir = new File(destDir + entry.getName().substring(0, index));
                    if (!dir.exists() && !dir.mkdirs()) {
                        installerEDMDisplay.showQuestion(currentStepGlobal, "copyPackageZipFile.failcreate.dir",
                                new String[] { dir.getAbsolutePath() });
                    }
                }
                // lectura del archivo interno y posterior escritura al directorio final
                byte[] buffer = new byte[1024];

                InputStream in = zf.getInputStream(entry);
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(destDir + entry.getName()));
                int len;
                while ((len = in.read(buffer)) >= 0) {
                    out.write(buffer, 0, len);
                }
                in.close();
                out.close();
            }
        }
        return true;
    } catch (IOException e) {
        showException(e);
    }
    return false;
}

From source file:com.jayway.maven.plugins.android.phase09package.ApkMojo.java

private void updateWithMetaInf(ZipOutputStream zos, File jarFile, Set<String> entries, boolean metaInfOnly)
        throws IOException {
    ZipFile zin = new ZipFile(jarFile);

    for (Enumeration<? extends ZipEntry> en = zin.entries(); en.hasMoreElements();) {
        ZipEntry ze = en.nextElement();

        if (ze.isDirectory()) {
            continue;
        }/*w ww  . j  ava  2s.  c  o m*/

        String zn = ze.getName();

        if (metaInfOnly) {
            if (!zn.startsWith("META-INF/")) {
                continue;
            }

            if (this.extractDuplicates && !entries.add(zn)) {
                continue;
            }

            if (!this.apkMetaInf.isIncluded(zn)) {
                continue;
            }
        }
        final ZipEntry ne;
        if (ze.getMethod() == ZipEntry.STORED) {
            ne = new ZipEntry(ze);
        } else {
            ne = new ZipEntry(zn);
        }

        zos.putNextEntry(ne);

        InputStream is = zin.getInputStream(ze);

        copyStreamWithoutClosing(is, zos);

        is.close();
        zos.closeEntry();
    }

    zin.close();
}

From source file:org.ambraproject.article.service.IngesterImpl.java

/**
 * Process files from the archive and store them to the {@link FileStoreService}
 *
 * @param archive - the archive being ingested
 * @param doi/*from ww  w . j av  a2 s  .  c o m*/
 * @throws java.io.IOException - if there's a problem reading from the zip file
 * @throws org.ambraproject.filestore.FileStoreException
 *                             - if there's a problem writing files to the file store
 */
private void storeFiles(final ZipFile archive, String doi) throws IOException, FileStoreException {
    log.info("Removing existing files (if any) for {}", doi);

    try {
        documentManagementService.removeFromFileSystem(doi);
    } catch (Exception e) {
        throw new FileStoreException("Error removing existing files from the file store", e);
    }

    log.info("Storing files from archive {} to the file store", archive.getName());
    Enumeration<? extends ZipEntry> entries = archive.entries();

    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (!entry.getName().equalsIgnoreCase("manifest.dtd")) {
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                inputStream = archive.getInputStream(entry);
                outputStream = fileStoreService.getFileOutStream(FSIDMapper.zipToFSID(doi, entry.getName()),
                        entry.getSize());
                fileStoreService.copy(inputStream, outputStream);
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        log.warn("Error closing input stream while writing files", e);
                    }
                }
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        log.warn("Error closing output stream while writing files", e);
                    }
                }
            }
        }
    }
    log.info("Finished storing files from archive {}", archive.getName());
}

From source file:org.guvnor.m2repo.backend.server.GuvnorM2Repository.java

private String loadGAVFromJarInternal(final File file) {
    InputStream is = null;/*  ww w . j av  a 2s  .c  o m*/
    InputStreamReader isr = null;
    try {
        ZipFile zip = new ZipFile(file);

        for (Enumeration e = zip.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();

            if (entry.getName().startsWith("META-INF/maven") && entry.getName().endsWith("pom.properties")) {
                is = zip.getInputStream(entry);
                isr = new InputStreamReader(is, "UTF-8");
                StringBuilder sb = new StringBuilder();
                for (int c = isr.read(); c != -1; c = isr.read()) {
                    sb.append((char) c);
                }
                return sb.toString();
            }
        }
    } catch (ZipException e) {
        log.error(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage());
    } finally {
        if (isr != null) {
            try {
                isr.close();
            } catch (IOException e) {
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }

    return null;
}

From source file:com.ikon.util.DocConverter.java

/**
 * Convert ZIP to PDF/*from www.ja v  a2s  . co m*/
 */
@SuppressWarnings("rawtypes")
public void zip2pdf(File input, File output) throws ConversionException, DatabaseException, IOException {
    log.debug("** Convert from ZIP to PDF **");
    FileOutputStream fos = null;
    ZipFile zipFile = null;

    try {
        fos = new FileOutputStream(output);

        // Make conversion
        zipFile = new ZipFile(input);
        Document doc = new Document(PageSize.A4);
        PdfWriter.getInstance(doc, fos);
        doc.open();

        for (Enumeration e = zipFile.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            doc.add(new Paragraph(12F, entry.getName()));
        }

        doc.close();
        zipFile.close();
    } catch (ZipException e) {
        throw new ConversionException("Exception in conversion: " + e.getMessage(), e);
    } catch (DocumentException e) {
        throw new ConversionException("Exception in conversion: " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.web.server.SARDeployer.java

/**
 * This method extracts the SAR archive and configures for the SAR and starts the services
 * @param file//  www.j av  a2 s. co  m
 * @param warDirectoryPath
 * @throws IOException
 */
public void extractSar(File file, String warDirectoryPath) throws IOException {
    ZipFile zip = new ZipFile(file);
    ZipEntry ze = null;
    String fileName = file.getName();
    fileName = fileName.substring(0, fileName.indexOf('.'));
    fileName += "sar";
    String fileDirectory;
    CopyOnWriteArrayList classPath = new CopyOnWriteArrayList();
    Enumeration<? extends ZipEntry> entries = zip.entries();
    int numBytes;
    while (entries.hasMoreElements()) {
        ze = entries.nextElement();
        // //System.out.println("Unzipping " + ze.getName());
        String filePath = deployDirectory + "/" + fileName + "/" + ze.getName();
        if (!ze.isDirectory()) {
            fileDirectory = filePath.substring(0, filePath.lastIndexOf('/'));
        } else {
            fileDirectory = filePath;
        }
        // //System.out.println(fileDirectory);
        createDirectory(fileDirectory);
        if (!ze.isDirectory()) {
            FileOutputStream fout = new FileOutputStream(filePath);
            byte[] inputbyt = new byte[8192];
            InputStream istream = zip.getInputStream(ze);
            while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) {
                fout.write(inputbyt, 0, numBytes);
            }
            fout.close();
            istream.close();
            if (ze.getName().endsWith(".jar")) {
                classPath.add(filePath);
            }
        }
    }
    zip.close();
    URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    URL[] urls = loader.getURLs();
    WebClassLoader sarClassLoader = new WebClassLoader(urls);
    for (int index = 0; index < classPath.size(); index++) {
        System.out.println("file:" + classPath.get(index));
        new WebServer().addURL(new URL("file:" + classPath.get(index)), sarClassLoader);
    }
    new WebServer().addURL(new URL("file:" + deployDirectory + "/" + fileName + "/"), sarClassLoader);
    sarsMap.put(fileName, sarClassLoader);
    System.out.println(sarClassLoader.geturlS());
    try {
        Sar sar = (Sar) sardigester.parse(new InputSource(
                new FileInputStream(deployDirectory + "/" + fileName + "/META-INF/" + "mbean-service.xml")));
        CopyOnWriteArrayList mbeans = sar.getMbean();
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        System.out.println(mbs);
        ObjectName objName;
        for (int index = 0; index < mbeans.size(); index++) {
            Mbean mbean = (Mbean) mbeans.get(index);
            System.out.println(mbean.getObjectname());
            System.out.println(mbean.getCls());
            objName = new ObjectName(mbean.getObjectname());
            Class helloWorldService = sarClassLoader.loadClass(mbean.getCls());
            Object obj = helloWorldService.newInstance();
            if (mbs.isRegistered(objName)) {
                mbs.invoke(objName, "stopService", null, null);
                //mbs.invoke(objName, "destroy", null, null);
                mbs.unregisterMBean(objName);
            }
            mbs.registerMBean(obj, objName);
            CopyOnWriteArrayList attrlist = mbean.getMbeanAttribute();
            if (attrlist != null) {
                for (int count = 0; count < attrlist.size(); count++) {
                    MBeanAttribute attr = (MBeanAttribute) attrlist.get(count);
                    Attribute mbeanattribute = new Attribute(attr.getName(), attr.getValue());
                    mbs.setAttribute(objName, mbeanattribute);
                }
            }
            mbs.invoke(objName, "startService", null, null);
        }
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedObjectNameException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstanceAlreadyExistsException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MBeanRegistrationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NotCompliantMBeanException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstanceNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ReflectionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MBeanException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidAttributeValueException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (AttributeNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:eionet.meta.exports.ods.Ods.java

/**
 * Zips file.//w w w .j  a  v a  2  s .c  o  m
 *
 * @param fileToZip
 *            file to zip (full path)
 * @param fileName
 *            file name
 * @throws java.lang.Exception
 *             if operation fails.
 */
private void zip(String fileToZip, String fileName) throws Exception {
    // get source file
    File src = new File(workingFolderPath + ODS_FILE_NAME);
    ZipFile zipFile = new ZipFile(src);
    // create temp file for output
    File tempDst = new File(workingFolderPath + ODS_FILE_NAME + ".zip");
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tempDst));
    // iterate on each entry in zip file
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry zipEntry = entries.nextElement();
        BufferedInputStream bis;
        if (StringUtils.equals(fileName, zipEntry.getName())) {
            bis = new BufferedInputStream(new FileInputStream(new File(fileToZip)));
        } else {
            bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
        }
        ZipEntry ze = new ZipEntry(zipEntry.getName());
        zos.putNextEntry(ze);

        while (bis.available() > 0) {
            zos.write(bis.read());
        }
        zos.closeEntry();
        bis.close();
    }
    zos.finish();
    zos.close();
    zipFile.close();
    // rename file
    src.delete();
    tempDst.renameTo(src);
}

From source file:com.jayway.maven.plugins.android.phase09package.ApkMojo.java

private File removeDuplicatesFromJar(File in, List<String> duplicates) {
    String target = projectOutputDirectory.getAbsolutePath();
    File tmp = new File(target, "unpacked-embedded-jars");
    tmp.mkdirs();/*  www .  ja  v  a  2s  . c  o  m*/
    File out = new File(tmp, in.getName());

    if (out.exists()) {
        return out;
    } else {
        try {
            out.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Create a new Jar file
    final FileOutputStream fos;
    final ZipOutputStream jos;
    try {
        fos = new FileOutputStream(out);
        jos = new ZipOutputStream(fos);
    } catch (FileNotFoundException e1) {
        getLog().error(
                "Cannot remove duplicates : the output file " + out.getAbsolutePath() + " does not found");
        return null;
    }

    final ZipFile inZip;
    try {
        inZip = new ZipFile(in);
        Enumeration<? extends ZipEntry> entries = inZip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            // If the entry is not a duplicate, copy.
            if (!duplicates.contains(entry.getName())) {
                // copy the entry header to jos
                jos.putNextEntry(entry);
                InputStream currIn = inZip.getInputStream(entry);
                copyStreamWithoutClosing(currIn, jos);
                currIn.close();
                jos.closeEntry();
            }
        }
    } catch (IOException e) {
        getLog().error("Cannot removing duplicates : " + e.getMessage());
        return null;
    }

    try {
        inZip.close();
        jos.close();
        fos.close();
    } catch (IOException e) {
        // ignore it.
    }
    getLog().info(in.getName() + " rewritten without duplicates : " + out.getAbsolutePath());
    return out;
}