Example usage for java.util.jar JarFile JarFile

List of usage examples for java.util.jar JarFile JarFile

Introduction

In this page you can find the example usage for java.util.jar JarFile JarFile.

Prototype

public JarFile(File file) throws IOException 

Source Link

Document

Creates a new JarFile to read from the specified File object.

Usage

From source file:com.datatorrent.stram.webapp.OperatorDiscoverer.java

public void buildTypeGraph() {
    Map<String, JarFile> openJarFiles = new HashMap<String, JarFile>();
    Map<String, File> openClassFiles = new HashMap<String, File>();
    // use global cache to load resource in/out of the same jar as the classes
    Set<String> resourceCacheSet = new HashSet<>();
    try {/*from ww w  .  j  a  v  a2  s.c  om*/
        for (String path : pathsToScan) {
            File f = null;
            try {
                f = new File(path);
                if (!f.exists() || f.isDirectory()
                        || (!f.getName().endsWith("jar") && !f.getName().endsWith("class"))) {
                    continue;
                }
                if (GENERATED_CLASSES_JAR.equals(f.getName())) {
                    continue;
                }
                if (f.getName().endsWith("class")) {
                    typeGraph.addNode(f);
                    openClassFiles.put(path, f);
                } else {
                    JarFile jar = new JarFile(path);
                    openJarFiles.put(path, jar);
                    java.util.Enumeration<JarEntry> entriesEnum = jar.entries();
                    while (entriesEnum.hasMoreElements()) {
                        final java.util.jar.JarEntry jarEntry = entriesEnum.nextElement();
                        String entryName = jarEntry.getName();
                        if (jarEntry.isDirectory()) {
                            continue;
                        }
                        if (entryName.endsWith("-javadoc.xml")) {
                            try {
                                processJavadocXml(jar.getInputStream(jarEntry));
                                // break;
                            } catch (Exception ex) {
                                LOG.warn("Cannot process javadoc {} : ", entryName, ex);
                            }
                        } else if (entryName.endsWith(".class")) {
                            TypeGraph.TypeGraphVertex newNode = typeGraph.addNode(jarEntry, jar);
                            // check if any visited resources belong to this type
                            for (Iterator<String> iter = resourceCacheSet.iterator(); iter.hasNext();) {
                                String entry = iter.next();
                                if (entry.startsWith(entryName.substring(0, entryName.length() - 6))) {
                                    newNode.setHasResource(true);
                                    iter.remove();
                                }
                            }
                        } else {
                            String className = entryName;
                            boolean foundClass = false;
                            // check if this resource belongs to any visited type
                            while (className.contains("/")) {
                                className = className.substring(0, className.lastIndexOf('/'));
                                TypeGraph.TypeGraphVertex tgv = typeGraph.getNode(className.replace('/', '.'));
                                if (tgv != null) {
                                    tgv.setHasResource(true);
                                    foundClass = true;
                                    break;
                                }
                            }
                            if (!foundClass) {
                                resourceCacheSet.add(entryName);
                            }
                        }
                    }
                }
            } catch (IOException ex) {
                LOG.warn("Cannot process file {}", f, ex);
            }
        }

        typeGraph.trim();

    } finally {
        for (Entry<String, JarFile> entry : openJarFiles.entrySet()) {
            try {
                entry.getValue().close();
            } catch (IOException e) {
                DTThrowable.wrapIfChecked(e);
            }
        }
    }
}

From source file:com.taobao.android.builder.tools.asm.ClazzBasicHandler.java

public void execute() throws IOException {

    logger.info("[ClazzReplacer] rewriteJar from " + jar.getAbsolutePath() + " to " + outJar.getAbsolutePath());

    JarFile jarFile = new JarFile(jar);

    JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outJar)));

    Enumeration<JarEntry> jarFileEntries = jarFile.entries();

    while (jarFileEntries.hasMoreElements()) {

        JarEntry ze = jarFileEntries.nextElement();

        String pathName = ze.getName();

        logger.info(jar.getAbsolutePath() + "->" + pathName);

        if (!pathName.endsWith(".class")) {
            justCopy(jarFile, jos, ze, pathName);
            continue;
        }/* w  w  w .j a  v a  2  s.  co  m*/

        handleClazz(jarFile, jos, ze, pathName);

    }

    jarFile.close();
    //        IOUtils.closeQuietly(fileOutputStream);
    IOUtils.closeQuietly(jos);
}

From source file:org.apache.pig.tools.pigstats.ScriptState.java

public String getPigVersion() {
    if (pigVersion == null) {
        String findContainingJar = JarManager.findContainingJar(ScriptState.class);
        if (findContainingJar != null) {
            try {
                JarFile jar = new JarFile(findContainingJar);
                final Manifest manifest = jar.getManifest();
                final Map<String, Attributes> attrs = manifest.getEntries();
                Attributes attr = attrs.get("org/apache/pig");
                pigVersion = attr.getValue("Implementation-Version");
            } catch (Exception e) {
                LOG.warn("unable to read pigs manifest file");
            }//from  w w  w. jav  a2 s.c o m
        } else {
            LOG.warn("unable to read pigs manifest file. Not running from the Pig jar");
        }
    }
    return (pigVersion == null) ? "" : pigVersion;
}

From source file:org.jboss.as.capedwarf.deployment.CapedwarfDeploymentProcessor.java

protected synchronized List<ResourceLoaderSpec> getResources(Map<String, List<ResourceLoaderSpec>> map,
        String version, String path) throws DeploymentUnitProcessingException {
    List<ResourceLoaderSpec> resources = map.get(version);
    if (resources == null) {
        try {//from w w w  . j a v  a 2 s  .  c om
            final List<File> mps = getModulePaths();
            final List<File> jars = findJars(path, version, mps);
            if (jars.isEmpty()) {
                throw new DeploymentUnitProcessingException(String.format("No jars found under %s", path));
            }

            resources = new ArrayList<>();
            for (File jar : jars) {
                final JarFile jarFile = new JarFile(jar);
                final ResourceLoader rl = ResourceLoaders.createJarResourceLoader(jar.getName(), jarFile);
                resources.add(ResourceLoaderSpec.createResourceLoaderSpec(rl));
            }
            map.put(version, resources);
        } catch (DeploymentUnitProcessingException e) {
            throw e;
        } catch (Exception e) {
            throw new DeploymentUnitProcessingException(e);
        }
    }
    return resources;
}

From source file:com.wavemaker.tools.pws.install.PwsInstall.java

private static boolean classExistsInJar(File[] jarFiles, String partnerName, String type) throws IOException {
    String className = partnerName.substring(0, 1).toUpperCase() + partnerName.substring(1) + type;
    boolean exists = false;
    for (File jarF : jarFiles) {
        JarFile jar = new JarFile(jarF);
        Enumeration<JarEntry> entries = jar.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (entry.getName().contains(className)) {
                exists = true;/*  ww  w .  j  a  va2  s .co m*/
                break;
            }
        }
        if (exists) {
            break;
        }
    }

    return exists;
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

/**
 * Does the named signature already exist in the JAR file?
 *
 * @param jarFile/*from   w ww.jav  a  2  s  .  c o  m*/
 *            JAR file
 * @param signatureName
 *            Signature name
 * @return True if it does, false otherwise
 * @throws IOException
 *             If an I/O problem occurs while examining the JAR file
 */
public static boolean hasSignature(File jarFile, String signatureName) throws IOException {
    JarFile jar = null;

    try {
        // Look for signature file (DSA or RSA)
        jar = new JarFile(jarFile);

        for (Enumeration<?> jarEntries = jar.entries(); jarEntries.hasMoreElements();) {
            JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
            if (!jarEntry.isDirectory()) {
                if ((jarEntry.getName().equalsIgnoreCase(
                        MessageFormat.format(METAINF_FILE_LOCATION, signatureName, DSA_SIG_BLOCK_EXT)))
                        || (jarEntry.getName().equalsIgnoreCase(MessageFormat.format(METAINF_FILE_LOCATION,
                                signatureName, RSA_SIG_BLOCK_EXT)))) {
                    return true;
                }
            }
        }

        return false;
    } finally {
        IOUtils.closeQuietly(jar);
    }
}

From source file:com.liferay.ide.project.core.util.ProjectImportUtil.java

/**
 * This method is used to validate whether the given plugin binary is a valid Liferay Plugin Archieve
 *
 * @param binaryFile//from w w  w .  ja  v a2s .co  m
 *            - the binary file to be validated
 * @return
 */
public static boolean isValidLiferayPlugin(File binaryFile) {
    boolean isValid = false;

    JarFile pluginBinary = null;

    try {
        pluginBinary = new JarFile(binaryFile);

        BinaryProjectRecord tempRecord = new BinaryProjectRecord(binaryFile);

        // Check for liferay-plugin-package.properties or liferay-plugin-package.xml
        JarEntry lfrPluginPkgPropsEntry = pluginBinary
                .getJarEntry(getConfigFileLocation(ILiferayConstants.LIFERAY_PLUGIN_PACKAGE_PROPERTIES_FILE));
        JarEntry lfrPluginPkgXmlEntry = pluginBinary.getJarEntry(
                getConfigFileLocation(ILiferayConstants.LIFERAY_PLUGIN_PACKAGE_PROPERTIES_XML_FILE));

        if (lfrPluginPkgPropsEntry != null || lfrPluginPkgXmlEntry != null) {
            isValid = true;
        }

        if (tempRecord.isHook()) {
            isValid = (isValid && pluginBinary
                    .getJarEntry(getConfigFileLocation(ILiferayConstants.LIFERAY_HOOK_XML_FILE)) != null);
        } else if (tempRecord.isLayoutTpl()) {
            isValid = (isValid || pluginBinary
                    .getJarEntry(getConfigFileLocation(ILiferayConstants.LIFERAY_LAYOUTTPL_XML_FILE)) != null);
        } else if (tempRecord.isPortlet()) {
            isValid = (isValid && pluginBinary
                    .getJarEntry(getConfigFileLocation(ILiferayConstants.LIFERAY_PORTLET_XML_FILE)) != null);
        } else if (tempRecord.isTheme()) {
            isValid = (isValid || pluginBinary.getJarEntry(
                    getConfigFileLocation(ILiferayConstants.LIFERAY_LOOK_AND_FEEL_XML_FILE)) != null);
        }

        if (!isValid) {
            return isValid;
        } else {
            // check if its a valid web Archieve
            isValid = isValid
                    || pluginBinary.getJarEntry(getConfigFileLocation(ILiferayConstants.WEB_XML_FILE)) != null;
        }
    } catch (IOException e) {
        isValid = false;
    } finally {
        if (pluginBinary != null) {
            try {
                pluginBinary.close();
            } catch (IOException e) {
            }
        }
    }

    return isValid;
}

From source file:com.app.server.JarDeployer.java

/**
 * This method obtains the class name inside the jar
 * @param jarPath//from   ww w .  j a  va 2s . c o  m
 * @param content
 * @throws IOException
 */
public static void getJarContent(String jarPath, CopyOnWriteArrayList content) throws IOException {
    try {
        log.info("enumer=" + jarPath);

        JarFile jarFile = new JarFile(jarPath);
        Enumeration enumer = (Enumeration) jarFile.entries();
        while (enumer.hasMoreElements()) {
            JarEntry entry = (JarEntry) enumer.nextElement();
            String name = entry.getName();
            if (name.endsWith(".class"))
                content.add(name.replace("/", "."));
        }
        log.info(content);
        jarFile.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.azurenight.maven.TroposphereMojo.java

private JarFile openJarFile(File jar) throws MojoExecutionException {
    try {/* w w  w .j  av  a2s  .  co  m*/
        return new JarFile(jar);
    } catch (IOException e) {
        throw new MojoExecutionException("opening jython artifact jar failed", e);
    }
}

From source file:org.dbmaintain.script.repository.impl.ArchiveScriptLocation.java

protected JarFile createJarFile(File jarFile) {
    try {/*from   w  w w  .  j  ava 2  s.  com*/
        File jarFileWithoutSubPath = getJarFileWithoutSubPath(jarFile);
        return new JarFile(jarFileWithoutSubPath);
    } catch (IOException e) {
        throw new DbMaintainException("Error opening jar file " + jarFile, e);
    }
}