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.netease.hearttouch.hthotfix.patch.PatchRefGeneratorTransformExecutor.java

public void transformJar(File inputFile, File outputFile) throws IOException {
    final JarFile jar = new JarFile(inputFile);
    final OutputJar outputJar = new OutputJar(outputFile);
    for (final Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) {
        final JarEntry entry = entries.nextElement();
        if (entry.isDirectory()) {
            continue;
        }//  w  ww  . j av  a2 s  .co  m
        final InputStream is = jar.getInputStream(entry);
        try {

            byte[] bytecode = IOUtils.toByteArray(is);
            if (entry.getName().endsWith(".class")) {
                if (extension.getGeneratePatch() && extension.getScanRef()) {
                    ClassReader cr = new ClassReader(bytecode);
                    String className = cr.getClassName();
                    if (extension.getGeneratePatch() && extension.getScanRef()) {
                        if (!refScanInstrument.isPatchClass(className.replace("/", "."))) {
                            boolean bPatchRef = refScanInstrument.hasReference(bytecode, project);
                            if (bPatchRef) {
                                patchJarHelper.writeClassToDirectory(className, bytecode);
                            }
                        }
                    }
                }
                outputJar.writeEntry(entry, bytecode);
            } else {
                outputJar.writeEntry(entry, bytecode);
            }
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
    outputJar.close();
}

From source file:ezbake.deployer.utilities.VersionHelper.java

private static String getVersionFromManifest(File artifact) throws IOException {
    String versionNumber = null;//from  w  w  w.  ja  v  a 2s.co m
    try (JarFile jar = new JarFile(artifact)) {
        Manifest manifest = jar.getManifest();
        Attributes attributes = manifest.getMainAttributes();
        if (attributes != null) {
            for (Object o : attributes.keySet()) {
                Attributes.Name key = (Attributes.Name) o;
                String keyword = key.toString();
                if (keyword.equals("Implementation-Version") || keyword.equals("Bundle-Version")) {
                    versionNumber = (String) attributes.get(key);
                    break;
                }
            }
        }
    }
    return versionNumber;
}

From source file:com.navercorp.pinpoint.bootstrap.java9.module.JarFileAnalyzerTest.java

@Test
public void providers() throws IOException {
    // Jar/*from w w w . j a  va 2  s.c  om*/
    // org.apache.commons.logging.LogFactory=[org.apache.commons.logging.impl.SLF4JLogFactory]
    URL url = CodeSourceUtils.getCodeLocation(LogFactory.class);

    JarFile jarFile = new JarFile(url.getFile());
    PackageAnalyzer analyzer = new JarFileAnalyzer(jarFile);
    PackageInfo analyze = analyzer.analyze();
    List<Providers> providers = analyze.getProviders();
    Providers first = providers.get(0);
    Assert.assertEquals(first.getService(), "org.apache.commons.logging.LogFactory");
    Assert.assertTrue(first.getProviders().contains("org.apache.commons.logging.impl.SLF4JLogFactory"));

}

From source file:org.apache.torque.generator.configuration.JarConfigurationProvider.java

/**
 * Constructor.//from   www  .  ja  v a2s  .  com
 * @param projectPaths the paths needed to interact with the enclosing
 *         project, not null.
 * @param configurationPaths The internal directory structure of the
 *         generator configuration files, not null.
 *
 * @throws NullPointerException if projectPaths or configurationPaths
 *          are null.
 * @throws ConfigurationException if the jar file can not be accessed.
 */
public JarConfigurationProvider(ProjectPaths projectPaths, TorqueGeneratorPaths configurationPaths)
        throws ConfigurationException {
    super(configurationPaths);
    if (projectPaths == null) {
        throw new NullPointerException("projectPaths is null");
    }
    this.projectPaths = projectPaths;
    this.configurationPaths = configurationPaths;

    try {
        jarFile = new JarFile(projectPaths.getConfigurationPath());
    } catch (IOException e) {
        log.error("Could not open jar File " + projectPaths.getConfigurationPath().getAbsolutePath());
        throw new ConfigurationException(e);
    }
}

From source file:javadepchecker.Main.java

private static boolean depNeeded(String pkg, Collection<String> deps) throws IOException {
    Collection<String> jars = getPackageJars(pkg);
    // We have a virtual with VM provider here
    if (jars.size() == 0)
        return true;
    for (String jarName : jars) {
        JarFile jar = new JarFile(jarName);
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            String name = e.nextElement().getName();
            if (deps.contains(name)) {
                return true;
            }/*from w  ww. j  a v  a  2  s.  c  o  m*/
        }
    }
    return false;
}

From source file:com.orange.mmp.dao.flf.ModuleDaoFlfImpl.java

@SuppressWarnings("unchecked")
public Module createOrUdpdate(Module module) throws MMPDaoException {
    if (module == null || module.getLocation() == null) {
        throw new MMPDaoException("missing or bad data access object");
    }/*  w  ww . ja va  2 s .co m*/

    JarFile jarFile = null;
    try {
        this.lock.lock();
        jarFile = new JarFile(new File(module.getLocation()));
        Manifest manifest = jarFile.getManifest();
        if (manifest == null) {
            throw new MMPDaoException("invalid module archive, MANIFEST file not found");
        }
        String symbolicName = manifest.getMainAttributes().getValue(MODULE_ID_HEADER);
        if (manifest.getMainAttributes().getValue(MODULE_ID_HEADER) != null) {
            if (module instanceof Widget) {
                String[] widgetId = symbolicName.split(com.orange.mmp.widget.Constants.BRANCH_SUFFIX_PATTERN);
                module.setId(widgetId[0]);
            } else {
                module.setId(symbolicName);
            }
        } else
            throw new MMPDaoException("invalid module archive, missing " + MODULE_ID_HEADER + " header");
        if (manifest.getMainAttributes().getValue(MODULE_NAME_HEADER) != null) {
            module.setName(manifest.getMainAttributes().getValue(MODULE_NAME_HEADER));
        } else
            throw new MMPDaoException("invalid module archive, missing " + MODULE_NAME_HEADER + " header");
        if (manifest.getMainAttributes().getValue(MODULE_VERSION_HEADER) != null) {
            module.setVersion(new Version(manifest.getMainAttributes().getValue(MODULE_VERSION_HEADER)));
        } else
            throw new MMPDaoException("invalid module archive, missing " + MODULE_VERSION_HEADER + " header");
        if (manifest.getMainAttributes().getValue(MODULE_CATEGORY_HEADER) != null) {
            module.setCategory(manifest.getMainAttributes().getValue(MODULE_CATEGORY_HEADER));
        } else
            module.setCategory(Constants.MODULE_CATEGORY_LIBRARY);

        File moduleFile = new File(module.getLocation());
        File dstFile;
        if (module instanceof Widget) {
            String[] nameAndBranch = symbolicName.split(com.orange.mmp.widget.Constants.BRANCH_SUFFIX_PATTERN);
            if (nameAndBranch.length > 1)
                dstFile = new File(this.path,
                        nameAndBranch[0].concat(com.orange.mmp.widget.Constants.BRANCH_SUFFIX_PATTERN)
                                .concat(nameAndBranch[1]).concat(".jar"));
            else {
                String defaultBranchId = null;
                Branch defaultBranch = new Branch();
                defaultBranch.setDefault(true);
                Branch defaultBranchesResult[] = (Branch[]) DaoManagerFactory.getInstance().getDaoManager()
                        .getDao("branch").find(defaultBranch);
                if (defaultBranchesResult.length > 0) {
                    defaultBranchId = defaultBranchesResult[0].getId();
                }
                defaultBranch = defaultBranchesResult[0];
                dstFile = new File(this.path,
                        nameAndBranch[0].concat(com.orange.mmp.widget.Constants.BRANCH_SUFFIX_PATTERN)
                                .concat(defaultBranchId).concat(".jar"));
            }
        } else {
            dstFile = new File(this.path, symbolicName.concat(".jar"));
        }
        FileUtils.copyFile(moduleFile, dstFile);
        module.setLocation(dstFile.toURI());
        module.setLastModified(dstFile.lastModified());
        jarFile.close();

        FileUtils.touch(new File(this.path));

        return module;
    } catch (IOException ioe) {
        throw new MMPDaoException("failed to add module : " + ioe.getMessage());
    } finally {
        try {
            if (jarFile != null)
                jarFile.close();
        } catch (IOException ioe) {
            //Nop just log
        }
        this.lock.unlock();
    }
}

From source file:Zip.java

/**
 * Reads a Jar file, displaying the attributes in its manifest and dumping
 * the contents of each file contained to the console.
 *//* w w  w  .  jav a  2  s . co m*/
public static void readJarFile(String fileName) {
    JarFile jarFile = null;
    try {
        // JarFile extends ZipFile and adds manifest information
        jarFile = new JarFile(fileName);
        if (jarFile.getManifest() != null) {
            System.out.println("Manifest Main Attributes:");
            Iterator iter = jarFile.getManifest().getMainAttributes().keySet().iterator();
            while (iter.hasNext()) {
                Attributes.Name attribute = (Attributes.Name) iter.next();
                System.out.println(
                        attribute + " : " + jarFile.getManifest().getMainAttributes().getValue(attribute));
            }
            System.out.println();
        }
        // use the Enumeration to dump the contents of each file to the console
        System.out.println("Jar file entries:");
        for (Enumeration e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = (JarEntry) e.nextElement();
            if (!jarEntry.isDirectory()) {
                System.out.println(jarEntry.getName() + " contains:");
                BufferedReader jarReader = new BufferedReader(
                        new InputStreamReader(jarFile.getInputStream(jarEntry)));
                while (jarReader.ready()) {
                    System.out.println(jarReader.readLine());
                }
                jarReader.close();
            }
        }
    } catch (IOException ioe) {
        System.out.println("An IOException occurred: " + ioe.getMessage());
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:javadepchecker.Main.java

private static boolean depNeeded(String pkg, Collection<String> deps) throws IOException {
    for (String jarName : getPackageJars(pkg)) {
        JarFile jar = new JarFile(jarName);
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            String name = e.nextElement().getName();
            if (deps.contains(name)) {
                return true;
            }//from www.  ja v  a  2s.  com
        }
    }
    return false;
}

From source file:javadepchecker.Main.java

private static boolean depNeeded(String pkg, Collection<String> deps) throws IOException {
    Collection<String> jars = getPackageJars(pkg);
    // We have a virtual with VM provider here
    if (jars.size() == 0) {
        return true;
    }//from  w w w . java2s.  c  om
    for (String jarName : jars) {
        JarFile jar = new JarFile(jarName);
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            String name = e.nextElement().getName();
            if (deps.contains(name)) {
                return true;
            }
        }
    }
    return false;
}

From source file:demo.config.diff.support.ConfigurationMetadataRepositoryLoader.java

private Resource load(ConfigurationMetadataRepositoryJsonBuilder builder, String moduleId, String version,
        boolean mandatory) throws IOException {
    String coordinates = moduleId + ":" + version;
    try {/*from ww  w.  j a va  2s. c  om*/
        ArtifactResult artifactResult = dependencyResolver.resolveDependency(coordinates);
        File file = artifactResult.getArtifact().getFile();
        JarFile jarFile = new JarFile(file);
        ZipEntry entry = jarFile.getEntry("META-INF/spring-configuration-metadata.json");
        if (entry != null) {
            logger.info("Adding meta-data from '" + coordinates + "'");
            try (InputStream stream = jarFile.getInputStream(entry)) {
                builder.withJsonResource(stream);
            }
        } else {
            logger.info("No meta-data found for '" + coordinates + "'");
        }
    } catch (ArtifactResolutionException e) {
        if (mandatory) {
            throw new UnknownSpringBootVersion("Could not load '" + coordinates + "'", version);
        }
        logger.info("Ignoring '" + coordinates + " (not found)");
    }
    return null;
}