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:com.magnet.tools.tests.ScenarioUtils.java

/**
 * Utility method to unzip a file/*from   w  ww.j a  v a2 s . c  o  m*/
 *
 * @param file      file to unzip
 * @param outputDir destination directory
 * @throws IOException if an io exception occurs
 */
public static void unzip(File file, File outputDir) throws IOException {
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File entryDestination = new File(outputDir, entry.getName());
            if (entry.isDirectory()) {
                if (!entryDestination.mkdirs()) {
                    throw new IllegalStateException("Cannot create directory " + entryDestination);
                }
                continue;
            }
            if (entryDestination.getParentFile().mkdirs()) {
                throw new IllegalStateException("Cannot create directory " + entryDestination.getParentFile());
            }
            InputStream in = zipFile.getInputStream(entry);
            OutputStream out = new FileOutputStream(entryDestination);
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    } finally {
        if (null != zipFile) {
            try {
                zipFile.close();
            } catch (Exception e) {
                /* do nothing */
            }
        }
    }
}

From source file:org.agnitas.util.ZipUtilities.java

/**
 * Readou of a Zip file//from   www .  j  ava 2 s  .com
 * @param zipFile
 * @return all file entries
 * @throws IOException
 */
public static Map<String, byte[]> readExistingZipFile(File zipFile) throws IOException {
    Map<String, byte[]> returnMap = new HashMap<String, byte[]>();

    ZipFile sourceZipFile = null;
    BufferedInputStream bufferedInputStream = null;
    ByteArrayOutputStream byteArrayOutputStream = null;

    try {
        sourceZipFile = new ZipFile(zipFile);

        // readout of all entries
        Enumeration<? extends ZipEntry> srcEntries = sourceZipFile.entries();
        while (srcEntries.hasMoreElements()) {
            ZipEntry sourceZipFileEntry = srcEntries.nextElement();

            bufferedInputStream = new BufferedInputStream(sourceZipFile.getInputStream(sourceZipFileEntry));
            byteArrayOutputStream = new ByteArrayOutputStream();

            byte[] bufferArray = new byte[1024];
            int byteBufferFillLength = bufferedInputStream.read(bufferArray);
            while (byteBufferFillLength > -1) {
                byteArrayOutputStream.write(bufferArray, 0, byteBufferFillLength);
                byteBufferFillLength = bufferedInputStream.read(bufferArray);
            }

            returnMap.put(sourceZipFileEntry.getName(), byteArrayOutputStream.toByteArray());

            byteArrayOutputStream.close();
            byteArrayOutputStream = null;

            bufferedInputStream.close();
            bufferedInputStream = null;
        }

        sourceZipFile.close();

        return returnMap;
    } finally {
        if (bufferedInputStream != null) {
            try {
                bufferedInputStream.close();
            } catch (Exception e) {
            }
            bufferedInputStream = null;
        }

        if (byteArrayOutputStream != null) {
            try {
                byteArrayOutputStream.close();
            } catch (Exception e) {
            }
            byteArrayOutputStream = null;
        }

        if (sourceZipFile != null) {
            try {
                sourceZipFile.close();
            } catch (Exception e) {
            }
            sourceZipFile = null;
        }
    }
}

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

/**
 * Check if the zip file is webanno compatible
 * /*  ww w .j ava 2  s . c o m*/
 * @param aZipFile the file.
 * @return if it is valid.
 * @throws ZipException if the ZIP file is corrupt.
 * @throws IOException if an I/O error occurs.
 *
 */
@SuppressWarnings({ "rawtypes" })
public static boolean isZipValidWebanno(File aZipFile) throws ZipException, IOException {

    boolean isZipValidWebanno = false;
    ZipFile zip = new ZipFile(aZipFile);
    for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();
        if (entry.toString().replace("/", "").startsWith(ImportUtil.EXPORTED_PROJECT)
                && entry.toString().replace("/", "").endsWith(".json")) {
            isZipValidWebanno = true;
            break;
        }
    }
    return isZipValidWebanno;
}

From source file:org.geoserver.rest.util.IOUtils.java

/**
 * Inflate the provided {@link ZipFile} in the provided output directory.
 * //from  w  w  w.ja  v a  2 s  .  c  o  m
 * @param archive the {@link ZipFile} to inflate.
 * @param outputDirectory the directory where to inflate the archive.
 * @throws IOException in case something bad happens.
 * @throws FileNotFoundException in case something bad happens.
 */
public static void inflate(ZipFile archive, File outputDirectory, String fileName)
        throws IOException, FileNotFoundException {

    final Enumeration<? extends ZipEntry> entries = archive.entries();
    try {
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();

            if (!entry.isDirectory()) {
                final String name = entry.getName();
                final String ext = FilenameUtils.getExtension(name);
                final InputStream in = new BufferedInputStream(archive.getInputStream(entry));
                final File outFile = new File(outputDirectory,
                        fileName != null ? new StringBuilder(fileName).append(".").append(ext).toString()
                                : name);
                final OutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));

                IOUtils.copyStream(in, out, true, true);

            } else {
                //if the entry is a directory attempt to make it
                new File(outputDirectory, entry.getName()).mkdirs();
            }
        }
    } finally {
        try {
            archive.close();
        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.FINE))
                LOGGER.isLoggable(Level.FINE);
        }
    }

}

From source file:org.geosdi.geoplatform.services.utility.PublishUtility.java

private static boolean renameZipShp(String userName, InfoPreview infoPreview, String tempUserDir)
        throws ResourceNotFoundFault {
    String tempUserZipDir = PublishUtility.createDir(tempUserDir + PublishUtility.ZIP_DIR_NAME);
    boolean result = false;
    LayerPublishAction layerPublishAction = infoPreview.getLayerPublishAction();
    String newName = userName + "_shp_" + infoPreview.getNewName();
    if (layerPublishAction != null && layerPublishAction.equals(LayerPublishAction.RENAME) && newName != null
            && !newName.equalsIgnoreCase(infoPreview.getDataStoreName())) {
        String fileName = tempUserZipDir + infoPreview.getDataStoreName() + ".zip";
        File previousFile = new File(fileName);
        ZipFile zipSrc = null;
        String renameDirPath = tempUserZipDir + "rename" + System.getProperty("file.separator");
        try {/*from  ww  w  .  jav a 2s .  c om*/
            PublishUtility.createDir(renameDirPath);
            logger.debug("********* ManageRename renameDirPath: " + renameDirPath);
            //Decomprime il contenuto dello zip nella cartella rename
            zipSrc = new ZipFile(previousFile);
            Enumeration<? extends ZipEntry> entries = zipSrc.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                PublishUtility.extractEntryToFile(entry, zipSrc, renameDirPath);
            }
            logger.debug("********* ManageRename element unzipped");
            //Dopo l'estrazione rinominare e creare zip
            compressFiles(tempUserZipDir, renameDirPath, newName + ".zip", infoPreview.getDataStoreName(),
                    newName);
            logger.debug("********* ManageRename after compress file");
            //Cancellare vecchio zip
            previousFile.delete();
            logger.debug("********* ManageRename after delete previous file");
            result = Boolean.TRUE;
        } catch (Exception e) {
            logger.error("ERRORE : " + e);
            throw new ResourceNotFoundFault(e.getMessage());
        } finally {
            try {
                zipSrc.close();
                //Cancella cartella rename
                PublishUtility.deleteDir(renameDirPath);
                logger.debug("********* ManageRename succesfully removed rename dir");
            } catch (IOException ex) {
            }
        }
        logger.debug("Shape Zip renamed: " + result);
        if (result) {
            infoPreview.setDataStoreName(newName);
        }
    }
    return result;
}

From source file:org.agnitas.util.ZipUtilities.java

/**
 * Open an existing Zip file for adding new entries.
 * All existing entries in the zipped file will be copied in the new one.
 * //from   w ww  .  jav  a 2s  . c o  m
 * @param zipFile
 * @return
 * @throws IOException 
 * @throws ZipException 
 */
public static ZipOutputStream openExistingZipFileForExtension(File zipFile) throws IOException {
    // Rename source Zip file (Attention: the String path and name of the zipFile are preserved
    File originalFileTemp = new File(
            zipFile.getParentFile().getAbsolutePath() + "/" + String.valueOf(System.currentTimeMillis()));
    zipFile.renameTo(originalFileTemp);

    ZipFile sourceZipFile = new ZipFile(originalFileTemp);
    ZipOutputStream zipOutputStream = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(zipFile)));

    BufferedInputStream bufferedInputStream = null;

    try {
        // copy entries
        Enumeration<? extends ZipEntry> srcEntries = sourceZipFile.entries();
        while (srcEntries.hasMoreElements()) {
            ZipEntry sourceZipFileEntry = srcEntries.nextElement();
            zipOutputStream.putNextEntry(sourceZipFileEntry);

            bufferedInputStream = new BufferedInputStream(sourceZipFile.getInputStream(sourceZipFileEntry));

            byte[] bufferArray = new byte[1024];
            int byteBufferFillLength = bufferedInputStream.read(bufferArray);
            while (byteBufferFillLength > -1) {
                zipOutputStream.write(bufferArray, 0, byteBufferFillLength);
                byteBufferFillLength = bufferedInputStream.read(bufferArray);
            }

            zipOutputStream.closeEntry();

            bufferedInputStream.close();
            bufferedInputStream = null;
        }

        zipOutputStream.flush();
        sourceZipFile.close();
        originalFileTemp.delete();

        return zipOutputStream;
    } catch (IOException e) {
        // delete existing Zip file
        if (zipFile.exists()) {
            if (zipOutputStream != null) {
                try {
                    zipOutputStream.close();
                } catch (Exception ex) {
                }
                zipOutputStream = null;
            }
            zipFile.delete();
        }

        // revert renaming of source Zip file
        originalFileTemp.renameTo(zipFile);
        throw e;
    } finally {
        if (bufferedInputStream != null) {
            try {
                bufferedInputStream.close();
            } catch (Exception e) {
            }
            bufferedInputStream = null;
        }
    }
}

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

/**
 * copy project log files from the exported project
 * @param zip the ZIP file./*from   w ww.j  av  a2  s .  c  o  m*/
 * @param aProject the project.
 * @param aRepository the repository service.
 * @throws IOException if an I/O error occurs.
 */
@SuppressWarnings("rawtypes")
public static void createProjectLog(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(LOG_DIR)) {
            FileUtils.copyInputStreamToFile(zip.getInputStream(entry), aRepository.getProjectLogFile(aProject));
            LOG.info(
                    "Imported log for project [" + aProject.getName() + "] with id [" + aProject.getId() + "]");
        }
    }
}

From source file:com.sshtools.j2ssh.authentication.UserGridCredential.java

private static void checkCACertificates(CoGProperties cogproperties) throws IOException {
    // check the directories exist and create if they don't
    String globusDir = System.getProperty("user.home") + "/.globus";
    if (!(new File(globusDir).exists())) {
        boolean success = (new File(globusDir).mkdir());
        if (!success) {
            throw new IOException("Couldn't create directory: " + globusDir);
        }/*w ww  . j a v  a2  s  .  c om*/
    }
    String caCertLocations = globusDir + "/certificates";
    File caCertLocationsF = new File(caCertLocations);
    if (!caCertLocationsF.exists()) {
        boolean success = (new File(caCertLocations).mkdir());
        if (!success) {
            throw new IOException("Couldn't create directory: " + caCertLocations);
        }
    }
    if (!caCertLocationsF.isDirectory()) {
        throw new IOException("Location: " + caCertLocations + " is not a directory");
    }
    File tmp = null;
    try {
        // save the zipfile temporarily
        tmp = File.createTempFile("certificates", ".zip");
        copyFile(thisDummy.getClass().getResourceAsStream("certificates.zip"), new FileOutputStream(tmp));
        ZipFile zf = new ZipFile(tmp);
        try {
            Enumeration e = zf.entries();
            while (e.hasMoreElements()) {
                ZipEntry ze = (ZipEntry) e.nextElement();
                String name = ze.getName();
                if (!(new File(caCertLocations + File.separator + name).exists())) {
                    copyFile(zf.getInputStream(ze),
                            new FileOutputStream(new File(caCertLocations + File.separator + name)));
                }
            }
        } finally {
            if (zf != null)
                zf.close();
        }
    } catch (IOException e) {
        throw new IOException("Couldn't load certificates... " + e);
    } finally {
        // delete temp file
        if (tmp != null) {
            if (tmp.exists())
                tmp.delete();
        }
    }
}

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

/**
 * copy guidelines from the exported project
 * @param zip the ZIP file./*  www . ja  v a2s .c  o m*/
 * @param aProject the project.
 * @param aRepository the repository service.
 * @throws IOException if an I/O error occurs.
 */
@SuppressWarnings("rawtypes")
public static void createProjectGuideline(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(GUIDELINE)) {
            String filename = FilenameUtils.getName(entry.getName());
            File guidelineDir = aRepository.getGuidelinesFile(aProject);
            FileUtils.forceMkdir(guidelineDir);
            FileUtils.copyInputStreamToFile(zip.getInputStream(entry), new File(guidelineDir, filename));

            LOG.info("Imported guideline [" + filename + "] for project [" + aProject.getName() + "] with id ["
                    + aProject.getId() + "]");
        }
    }
}

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

/**
 * copy source document files from the exported source documents
 * @param zip the ZIP file./*from w  w w  .j a v a 2  s.c  om*/
 * @param aProject the project.
 * @param aRepository the repository service.
 * @throws IOException if an I/O error occurs.
 */
@SuppressWarnings("rawtypes")
public static void createSourceDocumentContent(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(SOURCE)) {
            String fileName = FilenameUtils.getName(entryName);
            de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument sourceDocument = aRepository
                    .getSourceDocument(aProject, fileName);
            File sourceFilePath = aRepository.getSourceDocumentFile(sourceDocument);
            FileUtils.copyInputStreamToFile(zip.getInputStream(entry), sourceFilePath);

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