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:de.tudarmstadt.ukp.clarin.webanno.project.page.ImportUtil.java

/**
 * copy Project META_INF from the exported project
 * @param zip the ZIP file./*from  ww w.ja  v a  2  s.co  m*/
 * @param aProject the project.
 * @param aRepository the repository service.
 * @throws IOException if an I/O error occurs.
 */
@SuppressWarnings("rawtypes")
public static void createProjectMetaInf(ZipFile zip, Project aProject, RepositoryService aRepository)
        throws IOException {
    for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();

        // Strip leading "/" that we had in ZIP files prior to 2.0.8 (bug #985)
        String entryName = normalizeEntryName(entry);

        if (entryName.startsWith(META_INF)) {
            File metaInfDir = new File(aRepository.getMetaInfFolder(aProject),
                    FilenameUtils.getPath(entry.getName().replace(META_INF, "")));
            // where the file reside in the META-INF/... directory
            FileUtils.forceMkdir(metaInfDir);
            FileUtils.copyInputStreamToFile(zip.getInputStream(entry),
                    new File(metaInfDir, FilenameUtils.getName(entry.getName())));

            LOG.info("Imported META-INF for project [" + aProject.getName() + "] with id [" + aProject.getId()
                    + "]");
        }
    }
}

From source file:org.easysoa.registry.frascati.FileUtils.java

/**
 * Unzips the given jar in a temp file and returns its files' URLs Inspired
 * from AssemblyFactoryManager.processContribution() (though doesn't add it
 * to the classloader or parse composites)
 * TODO move to util TODO better : delete temp files afterwards (or mark them so) OR rather use jar:url ?
 * @param SCA zip or jar/*w ww. j a  v a2 s  .  c om*/
 * @return unzipped composites URLs
 * @throws ManagerException
 */
public static final Set<URL> unzipAndGetFileUrls(File file) {
    try {
        // Load contribution zip file
        ZipFile zipFile = new ZipFile(file);

        // Get folder name for output
        final String folder = zipFile.getName().substring(zipFile.getName().lastIndexOf(File.separator),
                zipFile.getName().length() - ".zip".length());

        Set<URL> fileURLSet = new HashSet<URL>();

        // Set directory for extracted files

        // TODO : use system temp directory but should use output folder
        // given by
        // runtime component. Will be possible once Assembly Factory modules
        // will
        // be merged

        final String tempDir = System.getProperty("java.io.tmpdir") + File.separator + folder + File.separator;

        Enumeration<? extends ZipEntry> entries = zipFile.entries();

        // Iterate over zip entries
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();

            log.info("ZIP entry: " + entry.getName());

            // create directories
            if (entry.isDirectory()) {
                log.info("create directory : " + tempDir + entry.getName());
                new File(tempDir, entry.getName()).mkdirs();
            } else {
                File f = new File(tempDir, File.separator + entry.getName());
                // register jar files
                int idx = entry.getName().lastIndexOf(File.separator);
                if (idx != -1) {
                    String tmp = entry.getName().substring(0, idx);
                    log.info("create directory : " + tempDir + tmp);
                    new File(tempDir, tmp).mkdirs();
                }
                // extract entry from zip to tempDir
                copy(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(f)));
                // add to res set
                fileURLSet.add(f.toURI().toURL());
            }
        }

        return fileURLSet;

    } catch (IOException e) {
        log.error(e);
        return new HashSet<URL>(0);
    }
}

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

private static String loadPomFromJar(final File file) {
    InputStream is = null;//w w w .  ja  va 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.xml")) {
                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:de.tudarmstadt.ukp.clarin.webanno.project.page.ImportUtil.java

/**
 * copy annotation documents (serialized CASs) from the exported project
 * @param zip the ZIP file./*from  ww w . j  ava 2s .c  om*/
 * @param aProject the project.
 * @param aRepository the repository service.
 * @throws IOException if an I/O error occurs.
 */
@SuppressWarnings("rawtypes")
public static void createAnnotationDocumentContent(ZipFile zip, Project aProject, RepositoryService aRepository)
        throws IOException {
    for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();

        // Strip leading "/" that we had in ZIP files prior to 2.0.8 (bug #985)
        String entryName = normalizeEntryName(entry);

        if (entryName.startsWith(ANNOTATION_AS_SERIALISED_CAS + "/")) {
            String fileName = entryName.replace(ANNOTATION_AS_SERIALISED_CAS + "/", "");

            // the user annotated the document is file name minus extension
            // (anno1.ser)
            String username = FilenameUtils.getBaseName(fileName).replace(".ser", "");

            // name of the annotation document
            fileName = fileName.replace(FilenameUtils.getName(fileName), "").replace("/", "");
            de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument sourceDocument = aRepository
                    .getSourceDocument(aProject, fileName);
            File annotationFilePath = aRepository.getCasFile(sourceDocument, username);

            FileUtils.copyInputStreamToFile(zip.getInputStream(entry), annotationFilePath);

            LOG.info("Imported annotation document content for user [" + username + "] for source document ["
                    + sourceDocument.getId() + "] in project [" + aProject.getName() + "] with id ["
                    + aProject.getId() + "]");
        }
    }
}

From source file:de.tudarmstadt.ukp.clarin.webanno.project.page.ImportUtil.java

/**
 * Copy curation documents from the exported project
 * @param zip the ZIP file.//from ww  w.  j  a  v  a  2s  .  co m
 * @param aProject the project.
 * @param aRepository the repository service.
 * @throws IOException if an I/O error occurs.
 */
@SuppressWarnings("rawtypes")
public static void createCurationDocumentContent(ZipFile zip, Project aProject, RepositoryService aRepository)
        throws IOException {
    for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();

        // Strip leading "/" that we had in ZIP files prior to 2.0.8 (bug #985)
        String entryName = normalizeEntryName(entry);

        if (entryName.startsWith(CURATION_AS_SERIALISED_CAS)) {
            String fileName = entryName.replace(CURATION_AS_SERIALISED_CAS, "");

            // the user annotated the document is file name minus extension
            // (anno1.ser)
            String username = FilenameUtils.getBaseName(fileName).replace(".ser", "");

            // name of the annotation document
            fileName = fileName.replace(FilenameUtils.getName(fileName), "").replace("/", "");
            de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument sourceDocument = aRepository
                    .getSourceDocument(aProject, fileName);
            File annotationFilePath = aRepository.getCasFile(sourceDocument, username);

            FileUtils.copyInputStreamToFile(zip.getInputStream(entry), annotationFilePath);

            LOG.info("Imported curation document content for user [" + username + "] for source document ["
                    + sourceDocument.getId() + "] in project [" + aProject.getName() + "] with id ["
                    + aProject.getId() + "]");
        }
    }
}

From source file:org.cloudgraph.hbase.mapreduce.GraphMapReduceSetup.java

/**
 * Add entries to <code>packagedClasses</code> corresponding to class files
 * contained in <code>jar</code>.
 * // w  ww. j av  a  2s  .  c  o  m
 * @param jar
 *          The jar who's content to list.
 * @param packagedClasses
 *          map[class -> jar]
 */
private static void updateMap(String jar, Map<String, String> packagedClasses) throws IOException {
    ZipFile zip = null;
    try {
        zip = new ZipFile(jar);
        for (Enumeration<? extends ZipEntry> iter = zip.entries(); iter.hasMoreElements();) {
            ZipEntry entry = iter.nextElement();
            if (entry.getName().endsWith("class")) {
                packagedClasses.put(entry.getName(), jar);
            }
        }
    } finally {
        if (null != zip)
            zip.close();
    }
}

From source file:org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil.java

/**
 * Add entries to <code>packagedClasses</code> corresponding to class files
 * contained in <code>jar</code>.
 * @param jar The jar who's content to list.
 * @param packagedClasses map[class -> jar]
 *//*  w  w  w  . ja  va2s.c  o  m*/
private static void updateMap(String jar, Map<String, String> packagedClasses) throws IOException {
    if (null == jar || jar.isEmpty()) {
        return;
    }
    ZipFile zip = null;
    try {
        zip = new ZipFile(jar);
        for (Enumeration<? extends ZipEntry> iter = zip.entries(); iter.hasMoreElements();) {
            ZipEntry entry = iter.nextElement();
            if (entry.getName().endsWith("class")) {
                packagedClasses.put(entry.getName(), jar);
            }
        }
    } finally {
        if (null != zip)
            zip.close();
    }
}

From source file:org.java.plugin.standard.ShadingPathResolver.java

static void unpack(final ZipFile zipFile, final File destFolder) throws IOException {
    for (Enumeration en = zipFile.entries(); en.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) en.nextElement();
        String name = entry.getName();
        File entryFile = new File(destFolder.getCanonicalPath() + "/" + name); //$NON-NLS-1$
        if (name.endsWith("/")) { //$NON-NLS-1$
            if (!entryFile.exists() && !entryFile.mkdirs()) {
                throw new IOException("can't create folder " + entryFile); //$NON-NLS-1$
            }/*from ww w.  jav  a  2 s . c o m*/
        } else {
            File folder = entryFile.getParentFile();
            if (!folder.exists() && !folder.mkdirs()) {
                throw new IOException("can't create folder " + folder); //$NON-NLS-1$
            }
            OutputStream out = new BufferedOutputStream(new FileOutputStream(entryFile, false));
            try {
                InputStream in = zipFile.getInputStream(entry);
                try {
                    IoUtil.copyStream(in, out, 1024);
                } finally {
                    in.close();
                }
            } finally {
                out.close();
            }
        }
        entryFile.setLastModified(entry.getTime());
    }
}

From source file:org.eclairjs.nashorn.Utils.java

public static void unzipFile(String zipfile, String directory) throws IOException {
    Logger logger = Logger.getLogger(Utils.class);
    int DEFAULT_BUFFER_SIZE = 4096;

    logger.debug("Going to try and unzip: " + zipfile);

    ZipFile zfile = new ZipFile(zipfile);
    Enumeration<? extends ZipEntry> entries = zfile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        logger.debug("Extracting: " + entry.getName());

        File file = new File(directory, entry.getName());
        if (entry.isDirectory()) {
            file.mkdirs();//from w w  w .  j  av  a2 s  . c  o  m
        } else {
            file.getParentFile().mkdirs();
            InputStream in = zfile.getInputStream(entry);
            OutputStream out = new FileOutputStream(file);
            try {
                byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
                while (true) {
                    int readCount = in.read(buffer);
                    if (readCount < 0) {
                        break;
                    }
                    out.write(buffer, 0, readCount);
                }
            } finally {
                in.close();
            }
        }
    }
}

From source file:org.jboss.tools.tycho.sitegenerator.FetchSourcesFromManifests.java

static public void unzipToDirectory(File file, String newPath) throws ZipException, IOException {
    int BUFFER = 2048;
    ZipFile zip = new ZipFile(file);
    (new File(newPath)).mkdirs();
    Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
        // grab a zip file entry
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
        String currentEntry = entry.getName();
        File destFile = new File(newPath, currentEntry);
        File destinationParent = destFile.getParentFile();
        // create the parent directory structure if needed
        destinationParent.mkdirs();/*  w w w .  j a  v  a 2s .c om*/
        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(zip.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);
            BufferedOutputStream 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);
            }
            dest.flush();
            dest.close();
            is.close();
        }
    }
    zip.close();
}