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:org.apache.jackrabbit.j2ee.BackwardsCompatibilityIT.java

private void unpack(File archive, File dir) throws IOException {
    ZipFile zip = new ZipFile(archive);
    try {//from   w  w w. j  a  v  a2  s  .c  o m
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.getName().startsWith("META-INF")) {
            } else if (entry.isDirectory()) {
                new File(dir, entry.getName()).mkdirs();
            } else {
                File file = new File(dir, entry.getName());
                file.getParentFile().mkdirs();
                InputStream input = zip.getInputStream(entry);
                try {
                    OutputStream output = new FileOutputStream(file);
                    try {
                        IOUtils.copy(input, output);
                    } finally {
                        output.close();
                    }
                } finally {
                    input.close();
                }
            }
        }
    } finally {
        zip.close();
    }
}

From source file:eu.diversify.disco.experiments.testing.Tester.java

private void unzipDistribution(String archiveName) throws IOException {
    String fileName = escape(archiveName);
    ZipFile zipFile = new ZipFile(fileName);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (!entry.isDirectory()) {
            File entryDestination = new File("target/", entry.getName());
            entryDestination.getParentFile().mkdirs();
            InputStream in = zipFile.getInputStream(entry);
            OutputStream out = new FileOutputStream(entryDestination);
            IOUtils.copy(in, out);// ww w .  j  a  va 2s.co  m
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }
}

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.  j  av  a 2  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:de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.RemoteApiController.java

/**
 * Create a new project.//w w  w . j  a v a 2 s  .  co  m
 *
 * To test, use the Linux "curl" command.
 *
 * curl -v -F 'file=@test.zip' -F 'name=Test' -F 'filetype=tcf'
 * 'http://USERNAME:PASSWORD@localhost:8080/de.tudarmstadt.ukp.clarin.webanno.webapp/api/project
 * '
 *
 * @param aName
 *            the name of the project to create.
 * @param aFileType
 *            the type of the files contained in the ZIP. The possible file types are configured
 *            in the formats.properties configuration file of WebAnno.
 * @param aFile
 *            a ZIP file containing the project data.
 * @throws Exception if there was en error.
 */
@RequestMapping(value = "/project", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public @ResponseStatus(HttpStatus.NO_CONTENT) void createProject(@RequestParam("file") MultipartFile aFile,
        @RequestParam("name") String aName, @RequestParam("filetype") String aFileType) throws Exception {
    LOG.info("Creating project [" + aName + "]");

    if (!ZipUtils.isZipStream(aFile.getInputStream())) {
        throw new InvalidFileNameException("", "is an invalid Zip file");
    }

    // Get current user
    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    User user = userRepository.get(username);
    Project project = null;

    // Configure project
    if (!projectRepository.existsProject(aName)) {
        project = new Project();
        project.setName(aName);

        // Create the project and initialize tags
        projectRepository.createProject(project, user);
        annotationService.initializeTypesForProject(project, user, new String[] {}, new String[] {},
                new String[] {}, new String[] {}, new String[] {}, new String[] {}, new String[] {},
                new String[] {});
        // Create permission for this user
        ProjectPermission permission = new ProjectPermission();
        permission.setLevel(PermissionLevel.ADMIN);
        permission.setProject(project);
        permission.setUser(username);
        projectRepository.createProjectPermission(permission);

        permission = new ProjectPermission();
        permission.setLevel(PermissionLevel.USER);
        permission.setProject(project);
        permission.setUser(username);
        projectRepository.createProjectPermission(permission);
    }
    // Existing project
    else {
        throw new IOException("The project with name [" + aName + "] exists");
    }

    // Iterate through all the files in the ZIP

    // If the current filename does not start with "." and is in the root folder of the ZIP,
    // import it as a source document
    File zimpFile = File.createTempFile(aFile.getOriginalFilename(), ".zip");
    aFile.transferTo(zimpFile);
    ZipFile zip = new ZipFile(zimpFile);

    for (Enumeration<?> zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
        //
        // Get ZipEntry which is a file or a directory
        //
        ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();

        // If it is the zip name, ignore it
        if ((FilenameUtils.removeExtension(aFile.getOriginalFilename()) + "/").equals(entry.toString())) {
            continue;
        }
        // IF the current filename is META-INF/webanno/source-meta-data.properties store it
        // as
        // project meta data
        else if (entry.toString().replace("/", "")
                .equals((META_INF + "webanno/source-meta-data.properties").replace("/", ""))) {
            InputStream zipStream = zip.getInputStream(entry);
            projectRepository.savePropertiesFile(project, zipStream, entry.toString());

        }
        // File not in the Zip's root folder OR not
        // META-INF/webanno/source-meta-data.properties
        else if (StringUtils.countMatches(entry.toString(), "/") > 1) {
            continue;
        }
        // If the current filename does not start with "." and is in the root folder of the
        // ZIP, import it as a source document
        else if (!FilenameUtils.getExtension(entry.toString()).equals("")
                && !FilenameUtils.getName(entry.toString()).equals(".")) {

            uploadSourceDocument(zip, entry, project, user, aFileType);
        }

    }

    LOG.info("Successfully created project [" + aName + "] for user [" + username + "]");

}

From source file:com.googlecode.android_scripting.ZipExtractorTask.java

private long getOriginalSize(ZipFile file) {
    Enumeration<? extends ZipEntry> entries = file.entries();
    long originalSize = 0l;
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (entry.getSize() >= 0) {
            originalSize += entry.getSize();
        }//from  w ww .  ja  v a 2 s. com
    }
    return originalSize;
}

From source file:org.openmrs.module.clinicalsummary.io.UploadSummariesTask.java

/**
 * Method that will be called to process the summary collection file. The upload process will unpack the zipped collection of summary files and then
 * decrypt them./*w ww.j a v  a 2  s .  c o  m*/
 *
 * @throws Exception
 */
protected void processSummaries() throws Exception {
    String zipFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ZIP), ".");
    String encryptedFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ENCRYPTED),
            ".");

    File file = new File(TaskUtils.getZippedOutputPath(), zipFilename);
    OutputStream outStream = new BufferedOutputStream(new FileOutputStream(file));
    ZipFile encryptedFile = new ZipFile(new File(TaskUtils.getEncryptedOutputPath(), encryptedFilename));

    Enumeration<? extends ZipEntry> entries = encryptedFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry zipEntry = entries.nextElement();
        String zipEntryName = zipEntry.getName();
        if (!zipEntryName.endsWith(TaskConstants.FILE_TYPE_SAMPLE)
                && !zipEntryName.endsWith(TaskConstants.FILE_TYPE_SECRET)) {
            int count;
            byte[] data = new byte[TaskConstants.BUFFER_SIZE];
            CipherInputStream zipCipherInputStream = new CipherInputStream(
                    encryptedFile.getInputStream(zipEntry), cipher);
            while ((count = zipCipherInputStream.read(data, 0, TaskConstants.BUFFER_SIZE)) != -1) {
                outStream.write(data, 0, count);
            }
            zipCipherInputStream.close();
        }
    }
    outStream.close();

    File outputPath = TaskUtils.getSummaryOutputPath();
    ZipFile zipFile = new ZipFile(file);
    Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
    while (zipEntries.hasMoreElements()) {
        ZipEntry zipEntry = zipEntries.nextElement();
        processedFilename = zipEntry.getName();
        File f = new File(outputPath, zipEntry.getName());
        // ensure that the parent path exists
        File parent = f.getParentFile();
        if (parent.exists() || parent.mkdirs()) {
            FileCopyUtils.copy(zipFile.getInputStream(zipEntry),
                    new BufferedOutputStream(new FileOutputStream(f)));
        }
    }
}

From source file:com.flexive.tests.disttools.DistPackageTest.java

@Test(groups = "dist")
public void basicDistPackageAnalysis() throws IOException {
    final ZipFile file = getDistFile();

    // parse zipfile entries, extract names
    final Enumeration<? extends ZipEntry> entries = file.entries();
    final List<String> entryNames = new ArrayList<String>();
    while (entries.hasMoreElements()) {
        final ZipEntry entry = entries.nextElement();
        entryNames.add(entry.getName());
    }//from w  w w. j av  a  2s. c  o  m

    // first check some mandatory files
    for (String requiredEntry : new String[] {
            // flexive JAR distribution
            "/lib/flexive-ant.jar", "/lib/flexive-ejb.jar", "/lib/flexive-extractor.jar",
            "/lib/flexive-shared.jar", "/lib/flexive-sqlParser.jar", "/lib/flexive-web-shared.jar",

            // basic build files
            "/build.xml", "/build.project.xml", "/build.component.xml", "/database.properties",

            // basic plugins
            "/applications/flexive-plugin-jsf-core.jar", }) {
        Assert.assertTrue(entryNames.contains("flexive-dist" + requiredEntry));
    }
}

From source file:com.yunmel.syncretic.utils.io.IOUtils.java

/**
 * ZIPZIPdescFileName//w  w w .  j  a v a 2 s.co m
 * 
 * @param zipFileName ?ZIP
 * @param descFileName 
 */
public static boolean unZipFiles(String zipFileName, String descFileName) {
    String descFileNames = descFileName;
    if (!descFileNames.endsWith(File.separator)) {
        descFileNames = descFileNames + File.separator;
    }
    try {
        // ?ZIPZipFile
        ZipFile zipFile = new ZipFile(zipFileName);
        ZipEntry entry = null;
        String entryName = null;
        String descFileDir = null;
        byte[] buf = new byte[4096];
        int readByte = 0;
        // ?ZIPentry
        @SuppressWarnings("rawtypes")
        Enumeration enums = zipFile.entries();
        // ??entry
        while (enums.hasMoreElements()) {
            entry = (ZipEntry) enums.nextElement();
            // entry??
            entryName = entry.getName();
            descFileDir = descFileNames + entryName;
            if (entry.isDirectory()) {
                // entry
                new File(descFileDir).mkdirs();
                continue;
            } else {
                // entry
                new File(descFileDir).getParentFile().mkdirs();
            }
            File file = new File(descFileDir);
            // ?
            OutputStream os = new FileOutputStream(file);
            // ZipFileentry?
            InputStream is = zipFile.getInputStream(entry);
            while ((readByte = is.read(buf)) != -1) {
                os.write(buf, 0, readByte);
            }
            os.close();
            is.close();
        }
        zipFile.close();
        log.debug("?!");
        return true;
    } catch (Exception e) {
        log.debug("" + e.getMessage());
        return false;
    }
}

From source file:de.psdev.energylogger.parser.EnergyLoggerDataParserImpl.java

@Override
public List<LogEntry> parseZippedDataFiles(final ZipFile zipFile) {
    final long startTime = System.currentTimeMillis();
    final List<LogEntry> logEntries = new ArrayList<LogEntry>();
    final Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
    while (zipEntries.hasMoreElements()) {
        final ZipEntry zipEntry = zipEntries.nextElement();
        logEntries.addAll(handleZipEntry(zipFile, zipEntry));
    }//from w  w  w.  ja va 2  s . c  o m
    final long runtime = System.currentTimeMillis() - startTime;
    LOG.info("Parsed {} logentries in {}", logEntries.size(), runtime);
    return logEntries;
}

From source file:io.github.jeremgamer.preview.actions.Launch.java

private void extractNatives() throws IOException {
    for (String s : NATIVE_JARS) {
        File archive = new File(s);
        ZipFile zipFile = new ZipFile(archive, Charset.forName("Cp437"));
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File entryDestination = new File(VANILLA_NATIVE_DIR.replaceAll("<version>", "1.8.1"),
                    entry.getName());// w  ww. j  av  a  2  s. c o  m
            entryDestination.getParentFile().mkdirs();
            if (entry.isDirectory())
                entryDestination.mkdirs();
            else {
                InputStream in = zipFile.getInputStream(entry);
                OutputStream out = new FileOutputStream(entryDestination);
                IOUtils.copy(in, out);
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
                in.close();
                out.close();
            }
        }
        zipFile.close();
    }
}