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:com.squareup.wire.schema.internal.parser.RpcMethodScanner.java

private List<RpcMethodDefinition> searchJar(String jarpath, String serviceName) throws IOException {

    List<RpcMethodDefinition> defs = new ArrayList<>();

    File jarFile = new File(jarpath);
    if (!jarFile.exists() || jarFile.isDirectory()) {
        return defs;
    }//from  w ww . j a v  a  2 s.  c o  m

    ZipInputStream zip = new ZipInputStream(new FileInputStream(jarFile));
    ZipEntry ze;

    while ((ze = zip.getNextEntry()) != null) {
        String entryName = ze.getName();
        if (entryName.endsWith(".proto")) {
            ZipFile zipFile = new ZipFile(jarFile);
            try (InputStream in = zipFile.getInputStream(ze)) {
                defs.addAll(inspectProtoFile(in, serviceName));
                if (!defs.isEmpty()) {
                    zipFile.close();
                    break;
                }
            }
            zipFile.close();
        }
    }

    zip.close();

    return defs;
}

From source file:ca.phon.app.workspace.ExtractProjectArchiveTask.java

/**
 * Get zipped project type./*from  w w  w  .ja  v  a 2s.c  o m*/
 * 
 * @param archive
 * @return the detected archive type and the project root folder name
 * in the zip file - only valid if detected type is ZippedProjectType.PROJECT_BASE_INCLUDED
 */
private Tuple<ZippedProjectType, String> detectZippedProjectType(File archive) {
    ZippedProjectType projType = ZippedProjectType.NOT_A_PROJECT;
    String projRoot = null;

    try (ZipFile zip = new ZipFile(archive)) {
        ZipEntry entry = null;
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            entry = entries.nextElement();

            if (entry.getName().contains("project.xml")) {
                if (entry.getName().equals("project.xml")) {
                    projType = ZippedProjectType.PROJECT_BASE_NOT_INCLUDED;
                    projRoot = "";
                } else {
                    projType = ZippedProjectType.PROJECT_BASE_INCLUDED;

                    File f = new File(entry.getName());
                    File rootFile = f.getParentFile();
                    projRoot = rootFile.getName();
                }
                break;
            }
        }
    } catch (IOException e) {
        LOGGER.warning(e.getMessage());
    }

    return new Tuple<ZippedProjectType, String>(projType, projRoot);
}

From source file:CrossRef.java

/** For each Zip file, for each entry, xref it */
public void processOneZip(String fileName) throws IOException {
    List entries = new ArrayList();
    ZipFile zipFile = null;/* w  w w.  j a v  a  2  s  .c o m*/

    try {
        zipFile = new ZipFile(new File(fileName));
    } catch (ZipException zz) {
        throw new FileNotFoundException(zz.toString() + fileName);
    }
    Enumeration all = zipFile.entries();

    // Put the entries into the List for sorting...
    while (all.hasMoreElements()) {
        ZipEntry zipEntry = (ZipEntry) all.nextElement();
        entries.add(zipEntry);
    }

    // Sort the entries (by class name)
    // Collections.sort(entries);

    // Process all the entries in this zip.
    Iterator it = entries.iterator();
    while (it.hasNext()) {
        ZipEntry zipEntry = (ZipEntry) it.next();
        String zipName = zipEntry.getName();

        // Ignore package/directory, other odd-ball stuff.
        if (zipEntry.isDirectory()) {
            continue;
        }

        // Ignore META-INF stuff
        if (zipName.startsWith("META-INF/")) {
            continue;
        }

        // Ignore images, HTML, whatever else we find.
        if (!zipName.endsWith(".class")) {
            continue;
        }

        // If doing CLASSPATH, Ignore com.* which are "internal API".
        //    if (doingStandardClasses && !zipName.startsWith("java")){
        //       continue;
        //    }

        // Convert the zip file entry name, like
        //   java/lang/Math.class
        // to a class name like
        //   java.lang.Math
        String className = zipName.replace('/', '.').substring(0, zipName.length() - 6); // 6 for ".class"

        // Now get the Class object for it.
        Class c = null;
        try {
            c = Class.forName(className);
        } catch (ClassNotFoundException ex) {
            System.err.println("Error: " + ex);
        }

        // Hand it off to the subclass...
        doClass(c);
    }
}

From source file:io.github.lucaseasedup.logit.config.PredefinedConfiguration.java

private String readPackageDefString() throws IOException {
    String jarUrlPath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
    String jarPath = URLDecoder.decode(jarUrlPath, "UTF-8");

    try (ZipFile jarZipFile = new ZipFile(jarPath)) {
        ZipEntry packageDefEntry = jarZipFile.getEntry(packageDefPathname);

        try (InputStream packageDefInputStream = jarZipFile.getInputStream(packageDefEntry)) {
            return IoUtils.toString(packageDefInputStream);
        }/*  ww w . java2  s.c  om*/
    }
}

From source file:it.eng.spagobi.engines.talend.services.JobUploadService.java

private String[] processUploadedFile(FileItem item, JobDeploymentDescriptor jobDeploymentDescriptor)
        throws ZipException, IOException, SpagoBIEngineException {
    String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();

    if (fieldName.equalsIgnoreCase("deploymentDescriptor"))
        return null;

    RuntimeRepository runtimeRepository = TalendEngine.getRuntimeRepository();
    File jobsDir = new File(runtimeRepository.getRootDir(),
            jobDeploymentDescriptor.getLanguage().toLowerCase());
    File projectDir = new File(jobsDir, jobDeploymentDescriptor.getProject());
    File tmpDir = new File(projectDir, "tmp");
    if (!tmpDir.exists())
        tmpDir.mkdirs();//from   ww w  .  j av  a2s .c  o  m
    File uploadedFile = new File(tmpDir, fileName);

    try {
        item.write(uploadedFile);
    } catch (Exception e) {
        e.printStackTrace();
    }

    String[] dirNames = ZipUtils.getDirectoryNameByLevel(new ZipFile(uploadedFile), 2);
    List dirNameList = new ArrayList();
    for (int i = 0; i < dirNames.length; i++) {
        if (!dirNames[i].equalsIgnoreCase("lib"))
            dirNameList.add(dirNames[i]);
    }
    String[] jobNames = (String[]) dirNameList.toArray(new String[0]);

    runtimeRepository.deployJob(jobDeploymentDescriptor, new ZipFile(uploadedFile));
    uploadedFile.delete();
    tmpDir.delete();

    return jobNames;
}

From source file:net.minecraftforge.fml.server.FMLServerHandler.java

@Override
public void addModAsResource(ModContainer container) {
    String langFile = "assets/" + container.getModId().toLowerCase() + "/lang/en_US.lang";
    File source = container.getSource();
    InputStream stream = null;/*from w w w  .  j a  v a  2s.  com*/
    ZipFile zip = null;
    try {
        if (source.isDirectory() && (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment")) {
            stream = new FileInputStream(new File(source.toURI().resolve(langFile).getPath()));
        } else {
            zip = new ZipFile(source);
            ZipEntry entry = zip.getEntry(langFile);
            if (entry == null)
                throw new FileNotFoundException();
            stream = zip.getInputStream(entry);
        }
        LanguageMap.inject(stream);
    } catch (IOException e) {
        // hush
    } catch (Exception e) {
        FMLLog.getLogger().error(e);
    } finally {
        IOUtils.closeQuietly(stream);
        try {
            if (zip != null)
                zip.close();
        } catch (IOException e) {
            // shush
        }
    }
}

From source file:com.aurel.track.lucene.util.openOffice.OOIndexer.java

private List unzip(String zip, String destination) {
    List destLs = new ArrayList();
    Enumeration entries;//ww w. java  2  s .  c om
    ZipFile zipFile;
    File dest = new File(destination);
    dest.mkdir();
    if (dest.isDirectory()) {

        try {
            zipFile = new ZipFile(zip);

            entries = zipFile.entries();

            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();

                if (entry.isDirectory()) {

                    (new File(dest.getAbsolutePath() + File.separator + entry.getName())).mkdirs();
                    continue;
                }

                if (entry.getName().lastIndexOf("/") > 0) {
                    File f = new File(dest.getAbsolutePath() + File.separator
                            + entry.getName().substring(0, entry.getName().lastIndexOf("/")));
                    f.mkdirs();
                }
                copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(
                        new FileOutputStream(dest.getAbsolutePath() + File.separator + entry.getName())));
                destLs.add(dest.getAbsolutePath() + File.separator + TMP_UNZIP_DIR + File.separator
                        + entry.getName());
            }

            zipFile.close();
        } catch (IOException e) {
            deleteDir(new File(destination));
            LOGGER.error(e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    } else {
        LOGGER.info("There is already a file by that name");
    }
    return destLs;
}

From source file:com.runwaysdk.dataaccess.io.Restore.java

private void unzipFile() {
    this.logPrintStream.println(ServerExceptionMessageLocalizer
            .extractingFileMessage(Session.getCurrentLocale(), this.zipFileLocation));

    try {/*from   w w w . j a  v a  2 s  .co  m*/
        FileIO.write(new ZipFile(this.zipFileLocation), this.restoreDirectory.getAbsolutePath());
        this.log.debug("Unzipped from [" + this.zipFileLocation + "] to [" + this.restoreDirectory + "]");
    } catch (ZipException e) {
        CorruptBackupException cbe = new CorruptBackupException(e);
        cbe.setBackupName(new File(zipFileLocation).getName());
        throw cbe;
    } catch (IOException e) {
        BackupReadException bre = new BackupReadException(e);
        bre.setLocation(new File(zipFileLocation).getName());
        throw bre;
    }
}

From source file:fr.fastconnect.factory.tibco.bw.fcunit.PrepareTestMojo.java

private void removeFileInZipContaining(List<String> contentFilter, File zipFile)
        throws ZipException, IOException {
    ZipScanner zs = new ZipScanner();
    zs.setSrc(zipFile);//  w  w w  .j av a  2 s .co m
    String[] includes = { "**/*.process" };
    zs.setIncludes(includes);
    //zs.setCaseSensitive(true);
    zs.init();
    zs.scan();

    File originalProjlib = zipFile; // to be overwritten
    File tmpProjlib = new File(zipFile.getAbsolutePath() + ".tmp"); // to read
    FileUtils.copyFile(originalProjlib, tmpProjlib);

    ZipFile listZipFile = new ZipFile(tmpProjlib);
    ZipInputStream readZipFile = new ZipInputStream(new FileInputStream(tmpProjlib));
    ZipOutputStream writeZipFile = new ZipOutputStream(new FileOutputStream(originalProjlib));

    ZipEntry zipEntry;
    boolean keep;
    while ((zipEntry = readZipFile.getNextEntry()) != null) {
        keep = true;
        for (String filter : contentFilter) {
            keep = keep && !containsString(filter, listZipFile.getInputStream(zipEntry));
        }
        //         if (!containsString("<pd:type>com.tibco.pe.core.OnStartupEventSource</pd:type>", listZipFile.getInputStream(zipEntry))
        //          && !containsString("<pd:type>com.tibco.plugin.jms.JMSTopicEventSource</pd:type>", listZipFile.getInputStream(zipEntry))) {
        if (keep) {
            writeZipFile.putNextEntry(zipEntry);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = readZipFile.read(buf)) >= 0) {
                writeZipFile.write(buf, 0, len);
            }
            writeZipFile.closeEntry();
            //getLog().info("written");
        } else {
            getLog().info("removed " + zipEntry.getName());
        }

    }

    writeZipFile.close();
    readZipFile.close();
    listZipFile.close();

    originalProjlib.setLastModified(originalProjlib.lastModified() - 100000);
}

From source file:org.ambraproject.admin.action.AdminTopAction.java

/**
 * Ingest the files made available in the ingestion-queue.
 *
 * @return SUCCESS/ERROR//from   w  w w  . jav  a 2 s  . c  o m
 */
public String ingest() {
    if (filesToIngest != null) {
        for (String file : filesToIngest) {

            final String filename = file.trim();
            final File archive = new File(documentManagementService.getDocumentDirectory(), filename);
            log.info("Starting ingest of " + filename);
            Article article = null;
            try {
                article = ingester.ingest(new ZipFile(archive), force);
            } catch (DuplicateArticleIdException de) {
                addActionError("Error ingesting: " + filename + " - " + getMessages(de));
                log.info("attempted to ingest duplicate article without force; archive: " + filename, de);
            } catch (Exception e) {
                addActionError("Error ingesting: " + filename + " - " + getMessages(e));
                log.info("Error ingesting article: " + filename, e);
            }
            if (article != null) {
                try {
                    documentManagementService.generateCrossrefInfoDoc(
                            ingestArchiveProcessor.extractArticleXml(new ZipFile(archive)),
                            URI.create(article.getDoi()));
                    documentManagementService.generateIngestedData(archive, article.getDoi());
                    log.info("Successfully ingested archive '" + filename + ", stored article "
                            + article.getDoi());
                    addActionMessage("Ingested: " + filename);
                } catch (Exception e) {
                    log.error("error moving files after successful ingest", e);
                    addActionError("Error ingesting: " + filename + " - " + getMessages(e));
                }
            }
        }
    }
    // create a faux journal object for template
    if (!setCommonFields()) {
        return ERROR;
    }

    return SUCCESS;
}