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:ClassSearchUtils.java

/**
 * Search archive files for required resource.
 * @param archive Jar or zip to be searched for classes or other resources.
 *//*from w ww . j  a  v  a  2 s.  c  o  m*/
private void lookInArchive(File archive) {
    log.fine("Looking in archive [" + archive.getName() + "] for extension [" + this.extension + "].");
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(archive);
    } catch (IOException e) {
        log.warning("Non fatal error. Unable to read jar item.");
        return;
    }
    Enumeration entries = jarFile.entries();
    JarEntry entry;
    String entryName;
    while (entries.hasMoreElements()) {
        entry = (JarEntry) entries.nextElement();
        entryName = entry.getName();
        if (entryName.toLowerCase().endsWith(this.extension)) {
            try {
                if (this.extension.equalsIgnoreCase(".class")) {
                    // convert name into java classloader notation
                    entryName = entryName.substring(0, entryName.length() - 6);
                    entryName = entryName.replace('/', '.');

                    // filter ignored resources
                    if (!entryName.startsWith(this.prefix)) {
                        continue;
                    }

                    log.fine("Found class: [" + entryName + "]. ");
                    this.list.add(Class.forName(entryName));
                } else {
                    this.list.add(this.classloader.getResource(entryName));
                    log.fine("Found appropriate resource with name [" + entryName + "]. Resource instance:"
                            + this.classloader.getResource(entryName));
                }
            } catch (Throwable e) {
                // ignore
                log.warning("Unable to load resource [" + entryName + "] form file ["
                        + archive.getAbsolutePath() + "].");
            }
        }
    }
}

From source file:org.apache.hadoop.hbase.util.CoprocessorClassLoader.java

private void init(Path path, String pathPrefix, Configuration conf) throws IOException {
    // Copy the jar to the local filesystem
    String parentDirStr = conf.get(LOCAL_DIR_KEY, DEFAULT_LOCAL_DIR) + TMP_JARS_DIR;
    synchronized (parentDirLockSet) {
        if (!parentDirLockSet.contains(parentDirStr)) {
            Path parentDir = new Path(parentDirStr);
            FileSystem fs = FileSystem.getLocal(conf);
            fs.delete(parentDir, true); // it's ok if the dir doesn't exist now
            parentDirLockSet.add(parentDirStr);
            if (!fs.mkdirs(parentDir) && !fs.getFileStatus(parentDir).isDirectory()) {
                throw new RuntimeException("Failed to create local dir " + parentDirStr
                        + ", CoprocessorClassLoader failed to init");
            }/*from   ww  w.  j av  a  2s. co m*/
        }
    }

    FileSystem fs = path.getFileSystem(conf);
    File dst = new File(parentDirStr,
            "." + pathPrefix + "." + path.getName() + "." + System.currentTimeMillis() + ".jar");
    fs.copyToLocalFile(path, new Path(dst.toString()));
    dst.deleteOnExit();

    addURL(dst.getCanonicalFile().toURI().toURL());

    JarFile jarFile = new JarFile(dst.toString());
    try {
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            Matcher m = libJarPattern.matcher(entry.getName());
            if (m.matches()) {
                File file = new File(parentDirStr, "." + pathPrefix + "." + path.getName() + "."
                        + System.currentTimeMillis() + "." + m.group(1));
                IOUtils.copyBytes(jarFile.getInputStream(entry), new FileOutputStream(file), conf, true);
                file.deleteOnExit();
                addURL(file.toURI().toURL());
            }
        }
    } finally {
        jarFile.close();
    }
}

From source file:com.google.gdt.eclipse.designer.util.Utils.java

/**
 * Get absolute path to the gwt-user.jar.
 * // w  ww .j a va 2s.  com
 * @param project
 *          optional GWT {@link IProject}, if not <code>null</code>, then project-specific
 *          gwt-user.jar may be returned; if <code>null</code>, then workspace-global one.
 */
public static IPath getUserLibPath(final IProject project) {
    // when no project, use workspace-global GWT_HOME
    if (project == null) {
        return new Path(Activator.getGWTLocation()).append("gwt-user.jar");
    }
    // try to find  project-specific GWT location
    return ExecutionUtils.runObject(new RunnableObjectEx<IPath>() {
        public IPath runObject() throws Exception {
            IJavaProject javaProject = JavaCore.create(project);
            String[] entries = ProjectClassLoader.getClasspath(javaProject);
            // try to find gwt-user.jar by name
            String userJarEntry = getUserJarEntry(entries);
            if (userJarEntry != null) {
                return new Path(userJarEntry);
            }
            // try to find gwt-user.jar by contents
            for (String entry : entries) {
                if (entry.endsWith(".jar")) {
                    JarFile jarFile = new JarFile(entry);
                    try {
                        if (jarFile.getEntry("com/google/gwt/core/Core.gwt.xml") != null) {
                            return new Path(entry);
                        }
                    } finally {
                        jarFile.close();
                    }
                }
            }
            // not found
            return null;
        }
    });
}

From source file:org.apache.felix.webconsole.internal.core.InstallAction.java

private String getSymbolicName(File bundleFile) {
    JarFile jar = null;// w  w w . j a  v  a2  s. c  o m
    try {
        jar = new JarFile(bundleFile);
        Manifest m = jar.getManifest();
        if (m != null) {
            return m.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
        }
    } catch (IOException ioe) {
        getLog().log(LogService.LOG_WARNING, "Cannot extract symbolic name of bundle file " + bundleFile, ioe);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    }

    // fall back to "not found"
    return null;
}

From source file:io.stallion.plugins.PluginRegistry.java

private void doLoadJarPlugins(String targetPath) throws Exception {
    String jarFolderPath = targetPath + "/jars";
    Log.fine("Loading jars at {0}", jarFolderPath);
    File jarFolder = new File(jarFolderPath);
    if (!jarFolder.exists() || !jarFolder.isDirectory()) {
        Log.fine("No jar folder exists at {0}. No jar plugins will be loaded.", jarFolderPath);
        return;//from   w  w w  . j  ava 2 s.c  o m
    }
    File[] files = jarFolder.listFiles();
    ArrayList<URL> urls = new ArrayList<URL>();
    for (int i = 0; i < files.length; i++) {
        if (files[i].getName().endsWith(".jar")) {
            //urls.add(files[i].toURL());
            Log.fine("Loading plugin jar {0}", files[i].toURI());
            urls.add(files[i].toURI().toURL());
        }
    }

    String pluginBooterClass = "";

    for (URL jarUrl : urls) {
        // Add jars to the class loader
        getClassLoader().addURL(jarUrl);
    }

    for (URL jarUrl : urls) {
        // Load the booter class
        Manifest m = new JarFile(jarUrl.getFile()).getManifest();
        Log.finer("Found manifest for jar {0}", jarUrl);
        if (!StringUtils.isEmpty(m.getMainAttributes().getValue("pluginBooterClass"))) {
            pluginBooterClass = m.getMainAttributes().getValue("pluginBooterClass");
        }
        if (empty(pluginBooterClass)) {
            continue;
        }
        Log.fine("Load plugin class {0} from jar={1}", pluginBooterClass, jarUrl);
        Class booterClass = getClassLoader().loadClass(pluginBooterClass);
        Log.finer("Booter class was loaded from: {0} ",
                booterClass.getProtectionDomain().getCodeSource().getLocation());
        StallionJavaPlugin booter = (StallionJavaPlugin) booterClass.newInstance();
        loadPluginFromBooter(booter);
        DynamicSettings.instance().initGroup(booter.getPluginName());
    }
}

From source file:com.vecna.taglib.processor.JspAnnotationsProcessor.java

/**
 * Scan a classloader for classes under the given package.
 * @param pkg package name/*w w w .j a va2 s  . c  o  m*/
 * @param loader classloader
 * @param lookInsideJars whether to consider classes inside jars or only "unpacked" class files
 * @return matching class names (will not attemp to actually load these classes)
 */
private Collection<String> scanClasspath(String pkg, ClassLoader loader, boolean lookInsideJars) {
    Collection<String> classes = Lists.newArrayList();

    Enumeration<URL> resources;
    String packageDir = pkg.replace(PACKAGE_SEPARATOR, JAR_PATH_SEPARATOR) + JAR_PATH_SEPARATOR;

    try {
        resources = loader.getResources(packageDir);
    } catch (IOException e) {
        s_log.warn("couldn't scan package", e);
        return classes;
    }

    while (resources.hasMoreElements()) {
        URL resource = resources.nextElement();
        String path = resource.getPath();
        s_log.debug("processing path {}", path);

        if (path.startsWith(FILE_URL_PREFIX)) {
            if (lookInsideJars) {
                String jarFilePath = StringUtils.substringBetween(path, FILE_URL_PREFIX,
                        NESTED_FILE_URL_SEPARATOR);
                try {
                    JarFile jarFile = new JarFile(jarFilePath);
                    Enumeration<JarEntry> entries = jarFile.entries();
                    while (entries.hasMoreElements()) {
                        String entryName = entries.nextElement().getName();
                        if (entryName.startsWith(packageDir) && entryName.endsWith(CLASS_NAME_SUFFIX)) {
                            String potentialClassName = entryName.substring(packageDir.length(),
                                    entryName.length() - CLASS_NAME_SUFFIX.length());
                            if (!potentialClassName.contains(JAR_PATH_SEPARATOR)) {
                                classes.add(pkg + PACKAGE_SEPARATOR + potentialClassName);
                            }
                        }
                    }
                } catch (IOException e) {
                    s_log.warn("couldn't open jar file", e);
                }
            }
        } else {
            File dir = new File(path);
            if (dir.exists() && dir.isDirectory()) {
                String[] files = dir.list();
                for (String file : files) {
                    s_log.debug("file {}", file);
                    if (file.endsWith(CLASS_NAME_SUFFIX)) {
                        classes.add(pkg + PACKAGE_SEPARATOR + StringUtils.removeEnd(file, CLASS_NAME_SUFFIX));
                    }
                }
            }
        }
    }
    return classes;
}

From source file:com.android.build.gradle.integration.application.ExternalBuildPluginTest.java

@Test
public void testBuild() throws ProcessException, IOException, ParserConfigurationException, SAXException {
    FileUtils.write(mProject.getBuildFile(),
            "" + "apply from: \"../commonHeader.gradle\"\n" + "buildscript {\n "
                    + "  apply from: \"../commonBuildScript.gradle\"\n" + "}\n" + "\n"
                    + "apply plugin: 'base'\n" + "apply plugin: 'com.android.external.build'\n" + "\n"
                    + "externalBuild {\n" + "  executionRoot = $/" + mProject.getTestDir().getAbsolutePath()
                    + "/$\n" + "  buildManifestPath = $/" + manifestFile.getAbsolutePath() + "/$\n" + "}\n");

    mProject.executor().withInstantRun(23, ColdswapMode.AUTO).withPackaging(mPackaging).run("clean", "process");

    InstantRunBuildContext instantRunBuildContext = loadFromBuildInfo();
    assertThat(instantRunBuildContext.getPreviousBuilds()).hasSize(1);
    assertThat(instantRunBuildContext.getLastBuild()).isNotNull();
    assertThat(instantRunBuildContext.getLastBuild().getArtifacts()).hasSize(1);
    InstantRunBuildContext.Build fullBuild = instantRunBuildContext.getLastBuild();
    assertThat(fullBuild.getVerifierStatus().get()).isEqualTo(InstantRunVerifierStatus.INITIAL_BUILD);
    assertThat(fullBuild.getArtifacts()).hasSize(1);
    InstantRunBuildContext.Artifact artifact = fullBuild.getArtifacts().get(0);
    assertThat(artifact.getType()).isEqualTo(InstantRunBuildContext.FileType.MAIN);
    assertThat(artifact.getLocation().exists()).isTrue();

    ApkSubject apkSubject = expect.about(ApkSubject.FACTORY).that(artifact.getLocation());
    apkSubject.contains("instant-run.zip");
    assertThat(apkSubject.hasMainDexFile());

    // now perform a hot swap test.
    File mainClasses = new File(mProject.getTestDir(), "jars/main/classes.jar");
    assertThat(mainClasses.exists()).isTrue();

    File originalFile = new File(mainClasses.getParentFile(), "original_classes.jar");
    assertThat(mainClasses.renameTo(originalFile)).isTrue();

    try (JarFile inputJar = new JarFile(originalFile);
            JarOutputStream jarOutputFile = new JarOutputStream(new BufferedOutputStream(
                    new FileOutputStream(new File(mainClasses.getParentFile(), "classes.jar"))))) {
        Enumeration<JarEntry> entries = inputJar.entries();
        while (entries.hasMoreElements()) {
            JarEntry element = entries.nextElement();
            try (InputStream inputStream = new BufferedInputStream(inputJar.getInputStream(element))) {
                if (!element.isDirectory()) {
                    jarOutputFile.putNextEntry(new ZipEntry(element.getName()));
                    try {
                        if (element.getName().contains("MainActivity.class")) {
                            // perform hot swap change
                            byte[] classBytes = new byte[(int) element.getSize()];
                            ByteStreams.readFully(inputStream, classBytes);
                            classBytes = hotswapChange(classBytes);
                            jarOutputFile.write(classBytes);
                        } else {
                            ByteStreams.copy(inputStream, jarOutputFile);
                        }//  ww  w  .  java  2  s .  c  o  m
                    } finally {
                        jarOutputFile.closeEntry();
                    }
                }
            }
        }
    }

    mProject.executor().withInstantRun(23, ColdswapMode.AUTO).withPackaging(mPackaging).run("process");

    instantRunBuildContext = loadFromBuildInfo();
    assertThat(instantRunBuildContext.getPreviousBuilds()).hasSize(2);
    InstantRunBuildContext.Build lastBuild = instantRunBuildContext.getLastBuild();
    assertThat(lastBuild).isNotNull();
    assertThat(lastBuild.getVerifierStatus().isPresent());
    assertThat(lastBuild.getVerifierStatus().get()).isEqualTo(InstantRunVerifierStatus.COMPATIBLE);
    assertThat(lastBuild.getArtifacts()).hasSize(1);
    artifact = lastBuild.getArtifacts().get(0);
    assertThat(artifact.getType()).isEqualTo(InstantRunBuildContext.FileType.RELOAD_DEX);
    assertThat(artifact.getLocation()).isNotNull();
    File dexFile = artifact.getLocation();
    assertThat(dexFile.exists()).isTrue();
    DexFileSubject reloadDex = expect.about(DexFileSubject.FACTORY).that(dexFile);
    reloadDex.hasClass("Lcom/android/tools/fd/runtime/AppPatchesLoaderImpl;").that();
    reloadDex.hasClass("Lcom/example/jedo/blazeapp/MainActivity$override;").that();
}

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

/**
 * Sign a JAR file outputting the signed JAR to a different file.
 *
 * @param jarFile// w  w w.j  a v  a2 s . c o m
 *            JAR file to sign
 * @param signedJarFile
 *            Output file for signed JAR
 * @param privateKey
 *            Private key to sign with
 * @param certificateChain
 *            Certificate chain for private key
 * @param signatureType
 *            Signature type
 * @param signatureName
 *            Signature name
 * @param signer
 *            Signer
 * @param digestType
 *            Digest type
 * @param tsaUrl
 *            TSA URL
 * @throws IOException
 *             If an I/O problem occurs while signing the JAR file
 * @throws CryptoException
 *             If a crypto problem occurs while signing the JAR file
 */
public static void sign(File jarFile, File signedJarFile, PrivateKey privateKey,
        X509Certificate[] certificateChain, SignatureType signatureType, String signatureName, String signer,
        DigestType digestType, String tsaUrl, Provider provider) throws IOException, CryptoException {

    JarFile jar = null;
    JarOutputStream jos = null;

    try {
        // Replace illegal characters in signature name
        signatureName = convertSignatureName(signatureName);

        // Create Jar File accessor for JAR to be signed
        jar = new JarFile(jarFile);

        // Write manifest content to here
        StringBuilder sbManifest = new StringBuilder();

        // Write out main attributes to manifest
        String manifestMainAttrs = getManifestMainAttrs(jar, signer);
        sbManifest.append(manifestMainAttrs);

        // Write out all entries' attributes to manifest
        String entryManifestAttrs = getManifestEntriesAttrs(jar);

        if (entryManifestAttrs.length() > 0) {
            // Only output if there are any
            sbManifest.append(entryManifestAttrs);
            sbManifest.append(CRLF);
        }

        // Write signature file to here
        StringBuilder sbSf = new StringBuilder();

        // Write out digests to manifest and signature file

        // Sign each JAR entry...
        for (Enumeration<?> jarEntries = jar.entries(); jarEntries.hasMoreElements();) {
            JarEntry jarEntry = (JarEntry) jarEntries.nextElement();

            if (!jarEntry.isDirectory()) // Ignore directories
            {
                if (!ignoreJarEntry(jarEntry)) // Ignore some entries (existing signature files)
                {
                    // Get the digest of the entry as manifest attributes
                    String manifestEntry = getDigestManifestAttrs(jar, jarEntry, digestType);

                    // Add it to the manifest string buffer
                    sbManifest.append(manifestEntry);

                    // Get the digest of manifest entries created above
                    byte[] mdSf = DigestUtil.getMessageDigest(manifestEntry.getBytes(), digestType);
                    byte[] mdSf64 = Base64.encode(mdSf);
                    String mdSf64Str = new String(mdSf64);

                    // Write this digest as entries in signature file
                    sbSf.append(createAttributeText(NAME_ATTR, jarEntry.getName()));
                    sbSf.append(CRLF);
                    sbSf.append(createAttributeText(MessageFormat.format(DIGEST_ATTR, digestType.jce()),
                            mdSf64Str));
                    sbSf.append(CRLF);
                    sbSf.append(CRLF);
                }
            }
        }

        // Manifest file complete - get base 64 encoded digest of its content for inclusion in signature file
        byte[] manifest = sbManifest.toString().getBytes();

        byte[] digestMf = DigestUtil.getMessageDigest(manifest, digestType);
        String digestMfStr = new String(Base64.encode(digestMf));

        // Get base 64 encoded digest of manifest's main attributes for inclusion in signature file
        byte[] mainfestMainAttrs = manifestMainAttrs.getBytes();

        byte[] digestMfMainAttrs = DigestUtil.getMessageDigest(mainfestMainAttrs, digestType);
        String digestMfMainAttrsStr = new String(Base64.encode(digestMfMainAttrs));

        // Write out Manifest Digest, Created By and Signature Version to start of signature file
        sbSf.insert(0, CRLF);
        sbSf.insert(0, CRLF);
        sbSf.insert(0,
                createAttributeText(MessageFormat.format(DIGEST_MANIFEST_ATTR, digestType.jce()), digestMfStr));
        sbSf.insert(0, CRLF);
        sbSf.insert(0,
                createAttributeText(
                        MessageFormat.format(DIGEST_MANIFEST_MAIN_ATTRIBUTES_ATTR, digestType.jce()),
                        digestMfMainAttrsStr));
        sbSf.insert(0, CRLF);
        sbSf.insert(0, createAttributeText(CREATED_BY_ATTR, signer));
        sbSf.insert(0, CRLF);
        sbSf.insert(0, createAttributeText(SIGNATURE_VERSION_ATTR, SIGNATURE_VERSION));

        // Signature file complete
        byte[] sf = sbSf.toString().getBytes();

        // Create output stream to write signed JAR
        jos = new JarOutputStream(new FileOutputStream(signedJarFile));

        // Write JAR files from JAR to be signed to signed JAR
        writeJarEntries(jar, jos, signatureName);

        // Write manifest to signed JAR
        writeManifest(manifest, jos);

        // Write signature file to signed JAR
        writeSignatureFile(sf, signatureName, jos);

        // Create signature block and write it out to signed JAR
        byte[] sigBlock = createSignatureBlock(sf, privateKey, certificateChain, signatureType, tsaUrl,
                provider);
        writeSignatureBlock(sigBlock, signatureType, signatureName, jos);
    } finally {
        IOUtils.closeQuietly(jar);
        IOUtils.closeQuietly(jos);
    }
}

From source file:cn.homecredit.web.listener.MyOsgiHost.java

protected String getVersion(URL url) {
    if ("jar".equals(url.getProtocol())) {
        try {//  w  w  w .j av  a2s  . c  o  m
            JarFile jarFile = new JarFile(new File(URLUtil.normalizeToFileProtocol(url).toURI()));
            Manifest manifest = jarFile.getManifest();
            if (manifest != null) {
                String version = manifest.getMainAttributes().getValue("Bundle-Version");
                if (StringUtils.isNotBlank(version)) {
                    return getVersionFromString(version);
                }
            } else {
                //try to get the version from the file name
                return getVersionFromString(jarFile.getName());
            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Unable to extract version from [#0], defaulting to '1.0.0'", url.toExternalForm());
            }
        }
    }
    return "1.0.0";
}

From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

@Test
public void testMdlModuleDefault() throws IOException {
    compile("modules/def/CeylonClass.ceylon");

    File carFile = getModuleArchive("default", null);
    assertTrue(carFile.exists());/*from  w w w . ja v  a 2  s  .  co m*/

    JarFile car = new JarFile(carFile);

    ZipEntry moduleClass = car
            .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/def/CeylonClass.class");
    assertNotNull(moduleClass);
    car.close();
}