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) throws ZipException, IOException 

Source Link

Document

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

Usage

From source file:FeatureExtraction.FeatureExtractorOOXMLStructuralPathsInputStream.java

private void ExtractStructuralFeaturesInMemory(InputStream fileInputStream,
        Map<String, Integer> structuralPaths) {
    String path;//from w  w w  . ja  v a 2s.com
    String directoryPath;
    String fileExtension;
    try {
        File file = new File(fileInputStream.hashCode() + "");
        try (FileOutputStream fos = new FileOutputStream(file)) {
            IOUtils.copy(fileInputStream, fos);
        }

        ZipFile zipFile = new ZipFile(file);

        for (Enumeration e = zipFile.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            path = entry.getName();
            directoryPath = FilenameUtils.getFullPath(path);
            fileExtension = FilenameUtils.getExtension(path);

            AddStructuralPath(directoryPath, structuralPaths);
            AddStructuralPath(path, structuralPaths);

            if (fileExtension.equals("rels") || fileExtension.equals("xml")) {
                AddXMLStructuralPaths(zipFile.getInputStream(entry), path, structuralPaths);
            }
        }
    } catch (IOException ex) {
        Console.PrintException(String.format("Error extracting OOXML structural features from file in memory"),
                ex);
    }
}

From source file:com.fluidops.iwb.cms.fs.ArchiveFile.java

public ArchiveFile(File zip, String path) throws IOException {
    ByteArrayOutputStream buffer = GenUtil.readUrlToBuffer(zip.getInputStream());
    java.io.File tmp = java.io.File.createTempFile("tmp", "zip");
    FileOutputStream out = null;//w w w .j  a v  a2 s. c o m
    try {
        out = new FileOutputStream(tmp);
        out.write(buffer.toByteArray());
        out.flush();
    } finally {
        IOUtils.closeQuietly(out);
    }
    this.path = path;
    this.zip = new ZipFile(tmp);
}

From source file:com.fluidops.iwb.cms.fs.ArchiveFile.java

public ArchiveFile(LocalFile zip, String path) throws IOException {
    this(new ZipFile(zip.file), path);
}

From source file:org.openmrs.module.amrsreports.rule.MohEvaluableRuleProvider.java

/**
 * @see org.openmrs.logic.rule.provider.RuleProvider#afterStartup()
 */// ww w. j av a  2s .c  om
@Override
public void afterStartup() {

    if (log.isDebugEnabled())
        log.debug("Registering AMRS reports summary rules ...");

    try {
        ModuleClassLoader moduleClassLoader = ModuleFactory.getModuleClassLoader(AMRS_REPORT_MODULE);
        for (URL url : moduleClassLoader.getURLs()) {
            String filename = url.getFile();
            if (StringUtils.contains(filename, AMRS_REPORT_MODULE_API)) {
                ZipFile zipFile = new ZipFile(filename);
                for (Enumeration list = zipFile.entries(); list.hasMoreElements();) {
                    ZipEntry entry = (ZipEntry) list.nextElement();
                    String zipFileName = FilenameUtils.getBaseName(entry.getName());
                    String zipFileExtension = FilenameUtils.getExtension(entry.getName());
                    if (StringUtils.endsWith(zipFileName, RULE_CLASS_SUFFIX)
                            && StringUtils.equals(zipFileExtension, CLASS_SUFFIX)) {
                        MohEvaluableRuleVisitor visitor = new MohEvaluableRuleVisitor();
                        ClassReader classReader = new ClassReader(zipFile.getInputStream(entry));
                        classReader.accept(visitor, false);
                    }
                }
                zipFile.close();
            }
        }
    } catch (IOException e) {
        log.error("Processing rule classes failed. Rule might not get registered.");
    }
}

From source file:com.googlecode.dex2jar.test.TestUtils.java

public static void checkZipFile(File zip) throws ZipException, Exception {
    ZipFile zipFile = new ZipFile(zip);
    for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) {
        ZipEntry entry = e.nextElement();
        if (entry.getName().endsWith(".class")) {
            StringWriter sw = new StringWriter();
            // PrintWriter pw = new PrintWriter(sw);
            InputStream is = zipFile.getInputStream(entry);
            try {
                verify(new ClassReader(IOUtils.toByteArray(is)));
            } finally {
                IOUtils.closeQuietly(is);
            }//  w  w w.j  a  v  a2s  . c o m
            Assert.assertTrue(sw.toString(), sw.toString().length() == 0);
        }
    }
}

From source file:org.openmrs.module.clinicalsummary.rule.EvaluableSummaryRuleProvider.java

/**
 * @see org.openmrs.logic.rule.provider.RuleProvider#afterStartup()
 *///from   w ww.j  a  v a  2 s  . c o  m
@Override
public void afterStartup() {

    if (log.isDebugEnabled())
        log.debug("Registering clinical summary rules ...");

    try {
        ModuleClassLoader moduleClassLoader = ModuleFactory.getModuleClassLoader(CLINICAL_SUMMARY_MODULE);
        for (URL url : moduleClassLoader.getURLs()) {
            String filename = url.getFile();
            if (StringUtils.contains(filename, CLINICAL_SUMMARY_MODULE_API)) {
                ZipFile zipFile = new ZipFile(filename);
                for (Enumeration list = zipFile.entries(); list.hasMoreElements();) {
                    ZipEntry entry = (ZipEntry) list.nextElement();
                    String zipFileName = FilenameUtils.getBaseName(entry.getName());
                    String zipFileExtension = FilenameUtils.getExtension(entry.getName());
                    if (StringUtils.endsWith(zipFileName, RULE_CLASS_SUFFIX)
                            && StringUtils.equals(zipFileExtension, CLASS_SUFFIX)) {
                        EvaluableRuleVisitor visitor = new EvaluableRuleVisitor();
                        ClassReader classReader = new ClassReader(zipFile.getInputStream(entry));
                        classReader.accept(visitor, false);
                    }
                }
                zipFile.close();
            }
        }
    } catch (IOException e) {
        log.error("Processing rule classes failed. Rule might not get registered.");
    }
}

From source file:abfab3d.io.input.STSReader.java

/**
 * Load a STS file into a grid./*from w  w  w  . j a va  2s. c  o  m*/
 *
 * @param file The zip file
 * @return
 * @throws java.io.IOException
 */
public TriangleMesh[] loadMeshes(String file) throws IOException {
    ZipFile zip = null;
    TriangleMesh[] ret_val = null;

    try {
        zip = new ZipFile(file);

        ZipEntry entry = zip.getEntry("manifest.xml");
        if (entry == null) {
            throw new IOException("Cannot find manifest.xml in top level");
        }

        InputStream is = zip.getInputStream(entry);
        mf = parseManifest(is);

        if (mf == null) {
            throw new IOException("Could not parse manifest file");
        }

        List<STSPart> plist = mf.getParts();
        int len = plist.size();

        ret_val = new TriangleMesh[len];
        for (int i = 0; i < len; i++) {
            STSPart part = plist.get(i);
            ZipEntry ze = zip.getEntry(part.getFile());
            MeshReader reader = new MeshReader(zip.getInputStream(ze), "",
                    FilenameUtils.getExtension(part.getFile()));
            IndexedTriangleSetBuilder its = new IndexedTriangleSetBuilder();
            reader.getTriangles(its);

            // TODO: in this case we could return a less heavy triangle mesh struct?
            WingedEdgeTriangleMesh mesh = new WingedEdgeTriangleMesh(its.getVertices(), its.getFaces());
            ret_val[i] = mesh;
        }

        return ret_val;
    } finally {
        if (zip != null)
            zip.close();
    }
}

From source file:com.opengamma.integration.copier.portfolio.reader.ZippedPortfolioReader.java

@SuppressWarnings("unchecked")
public ZippedPortfolioReader(String filename, boolean ignoreVersion) {

    ArgumentChecker.notNull(filename, "filename");

    try {//www  . j  a v a  2s.c om
        _zipFile = new ZipFile(filename);
        _zipEntries = (Enumeration<ZipEntry>) _zipFile.entries();
    } catch (IOException ex) {
        throw new OpenGammaRuntimeException("Could not open " + filename);
    }

    _ignoreVersion = ignoreVersion;

    if (!_ignoreVersion) {
        // Retrieve security hashes listed in config file
        readMetaData("METADATA.INI");
    }

    s_logger.info("Using ZIP archive " + filename);
}

From source file:com.mgmtp.jfunk.data.source.ArchiveDataSource.java

private Map<String, DataSet> getDataSets() {
    if (dataSets == null) {
        String archiveFileName = configuration.get("dataSource." + getName() + ".archiveFileName");
        if (archiveFileName == null) {
            throw new IllegalStateException("No archive files configured.");
        }/*from w w w  .  j  a  v a 2  s . c  o m*/
        log.info("Using " + archiveFileName);

        dataSets = newHashMap();
        try {
            ZipFile zip = new ZipFile(archiveFileName);
            for (Enumeration<? extends ZipEntry> zipEntryEnum = zip.entries(); zipEntryEnum
                    .hasMoreElements();) {
                ZipEntry zipEntry = zipEntryEnum.nextElement();
                String name = zipEntry.getName();
                Matcher matcher = KEY_PATTERN.matcher(name);
                if (matcher.find()) {
                    InputStream is = null;
                    try {
                        is = zip.getInputStream(zipEntry);
                        String key = matcher.group(1);
                        ExtendedProperties props = new ExtendedProperties();
                        props.load(is);
                        log.debug("Adding data for key=" + key);
                        dataSets.put(key, new DefaultDataSet(props));
                    } finally {
                        closeQuietly(is);
                    }
                }
            }
        } catch (IOException ex) {
            throw new JFunkException("Error getting data sets.", ex);
        }
    }
    return dataSets;
}

From source file:edu.isi.wings.portal.classes.StorageHandler.java

public static String unzipFile(File f, String todirname, String toDirectory) {
    File todir = new File(toDirectory);
    if (!todir.exists())
        todir.mkdirs();//from   ww w. ja  v  a 2 s. c o m

    try {
        // Check if the zip file contains only one directory
        ZipFile zfile = new ZipFile(f);
        String topDir = null;
        boolean isOneDir = true;
        for (Enumeration<? extends ZipEntry> e = zfile.entries(); e.hasMoreElements();) {
            ZipEntry ze = e.nextElement();
            String name = ze.getName().replaceAll("/.+$", "");
            name = name.replaceAll("/$", "");
            // OSX Zips carry an extra __MACOSX directory. Ignore it
            if (name.equals("__MACOSX"))
                continue;

            if (topDir == null)
                topDir = name;
            else if (!topDir.equals(name)) {
                isOneDir = false;
                break;
            }
        }
        zfile.close();

        // Delete existing directory (if any)
        FileUtils.deleteDirectory(new File(toDirectory + File.separator + todirname));

        // Unzip file(s) into toDirectory/todirname
        ZipInputStream zis = new ZipInputStream(new FileInputStream(f));
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName();
            // OSX Zips carry an extra __MACOSX directory. Ignore it
            if (fileName.startsWith("__MACOSX")) {
                ze = zis.getNextEntry();
                continue;
            }

            // Get relative file path translated to 'todirname'
            if (isOneDir)
                fileName = fileName.replaceFirst(topDir, todirname);
            else
                fileName = todirname + File.separator + fileName;

            // Create directories
            File newFile = new File(toDirectory + File.separator + fileName);
            if (ze.isDirectory())
                newFile.mkdirs();
            else
                newFile.getParentFile().mkdirs();

            try {
                // Copy file
                FileOutputStream fos = new FileOutputStream(newFile);
                IOUtils.copy(zis, fos);
                fos.close();

                String mime = new Tika().detect(newFile);
                if (mime.equals("application/x-sh") || mime.startsWith("text/"))
                    FileUtils.writeLines(newFile, FileUtils.readLines(newFile));

                // Set all files as executable for now
                newFile.setExecutable(true);
            } catch (FileNotFoundException fe) {
                // Silently ignore
                //fe.printStackTrace();
            }
            ze = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();

        return toDirectory + File.separator + todirname;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}