Example usage for java.util.jar JarEntry getName

List of usage examples for java.util.jar JarEntry getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the entry.

Usage

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  . j  av a  2  s .com
                    } 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:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfigurator.java

@Override
public void configure(ProjectServiceConfiguration configuration) {

    // Get a reference to our template WAR, and make sure it exists.
    File jenkinsTemplateWar = new File(warTemplateFile);

    if (!jenkinsTemplateWar.exists() || !jenkinsTemplateWar.isFile()) {
        String message = "The given Jenkins template WAR [" + jenkinsTemplateWar
                + "] either did not exist or was not a file!";
        LOG.error(message);/*  w w  w . j  ava 2 s .  co m*/
        throw new IllegalStateException(message);
    }

    String pathProperty = perOrg ? configuration.getOrganizationIdentifier()
            : configuration.getProjectIdentifier();

    String deployedUrl = configuration.getProperties().get(ProjectServiceConfiguration.PROFILE_BASE_URL)
            + jenkinsPath + pathProperty + "/jenkins/";
    deployedUrl.replace("//", "/");
    URL deployedJenkinsUrl;
    try {
        deployedJenkinsUrl = new URL(deployedUrl);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    String webappName = deployedJenkinsUrl.getPath();
    if (webappName.startsWith("/")) {
        webappName = webappName.substring(1);
    }
    if (webappName.endsWith("/")) {
        webappName = webappName.substring(0, webappName.length() - 1);
    }
    webappName = webappName.replace("/", "#");
    webappName = webappName + ".war";

    // Calculate our final filename.

    String deployLocation = targetWebappsDir + webappName;

    File jenkinsDeployFile = new File(deployLocation);

    if (jenkinsDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + jenkinsDeployFile.getAbsolutePath()
                + "] a file or directory with that name already existed! Continuing with provisioning.";
        LOG.info(message);
        return;
    }

    try {
        // Get a reference to our template war
        JarFile jenkinsTemplateWarJar = new JarFile(jenkinsTemplateWar);

        // Extract our web.xml from this war
        JarEntry webXmlEntry = jenkinsTemplateWarJar.getJarEntry(webXmlFilename);
        String webXmlContents = IOUtils.toString(jenkinsTemplateWarJar.getInputStream(webXmlEntry));

        // Update the web.xml to contain the correct JENKINS_HOME value
        String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration);

        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // Put the web.xml back into the war
        File updatedJenkinsWar = File.createTempFile("jenkins", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedJenkinsWar),
                jenkinsTemplateWarJar.getManifest());

        // Loop through our existing zipfile and add in all of the entries to it except for our web.xml
        JarEntry curEntry = null;
        Enumeration<JarEntry> entries = jenkinsTemplateWarJar.entries();
        while (entries.hasMoreElements()) {
            curEntry = entries.nextElement();

            // If this is the manifest, skip it.
            if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                continue;
            }

            if (curEntry.getName().equals(webXmlEntry.getName())) {
                JarEntry newEntry = new JarEntry(curEntry.getName());
                jarOutStream.putNextEntry(newEntry);

                // Substitute our edited entry content.
                IOUtils.write(updatedXml, jarOutStream);
            } else {
                jarOutStream.putNextEntry(curEntry);
                IOUtils.copy(jenkinsTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

        // Clean up our resources.
        jarOutStream.close();

        // Move the war into its deployment location so that it can be picked up and deployed by the app server.
        FileUtils.moveFile(updatedJenkinsWar, jenkinsDeployFile);
    } catch (IOException ioe) {
        // Log this exception and rethrow wrapped in a RuntimeException
        LOG.error(ioe.getMessage());
        throw new RuntimeException(ioe);
    }
}

From source file:com.infosupport.ellison.core.archive.ApplicationArchive.java

/**
 * Extracts a single {@link JarEntry} into the {@code destination} directory.
 * <p/>//  w w w  .j  a v  a2 s .  c  om
 * If {@code jarEntry} represents a directory, then a new directory is created in {@code destination}. If it is a
 * file, its {@link InputStream} is opened, and its contents are then written in {@code destination}.
 *
 * @param destination
 *     the destination directory to unpack {@code jarEntry} into. This is the "root" directory where the entire
 *     archive is unpacked into, as each {@code JarEntry}'s name points to whatever directory it should in fact be
 *     in. See {@link File#File(java.io.File, String)} to see how this is achieved.
 * @param jar
 *     the archive from which the {@code jarEntry} originates
 * @param jarEntry
 *     the {@code JarEntry} to unpack
 *
 * @throws IOException
 *     if any IO error occurred while trying to unpack a file
 */
protected void unpackJarEntry(File destination, JarFile jar, JarEntry jarEntry) throws IOException {
    byte[] ioBuffer = new byte[Constants.UNPACK_BUFFER_SIZE];
    if (jarEntry.isDirectory()) {
        File newDir = new File(destination, jarEntry.getName());
        boolean dirCreated = newDir.mkdir();
        if (dirCreated) {
            newDir.deleteOnExit();
        }
    } else {
        File outFile = new File(destination, jarEntry.getName());
        outFile.deleteOnExit();

        try (InputStream jarEntryInputStream = jar.getInputStream(jarEntry);
                OutputStream jarEntryOutputStream = new FileOutputStream(outFile)) {
            for (int readBytes = jarEntryInputStream
                    .read(ioBuffer); readBytes != -1; readBytes = jarEntryInputStream.read(ioBuffer)) {
                jarEntryOutputStream.write(ioBuffer, 0, readBytes);
            }
        }
    }
}

From source file:hotbeans.support.JarFileHotBeanModuleLoader.java

/**
 * Extracts all the files in the module jar file, including nested jar files. The reason for extracting the complete
 * contents of the jar file (and not just the nested jar files) is to make sure the module jar file isn't locked, and
 * thus may be deleted./*w  w  w  . j a  v a 2 s . c  o  m*/
 */
private void extractLibs() throws IOException {
    if (logger.isDebugEnabled())
        logger.debug("Extracting module jar file '" + moduleJarFile + "'.");

    JarFile jarFile = new JarFile(this.moduleJarFile);
    Enumeration entries = jarFile.entries();
    JarEntry entry;
    String entryName;
    File extractedFile = null;
    FileOutputStream extractedFileOutputStream;

    while (entries.hasMoreElements()) {
        entry = (JarEntry) entries.nextElement();
        if ((entry != null) && (!entry.isDirectory())) {
            entryName = entry.getName();
            if (entryName != null) {
                // if( logger.isDebugEnabled() ) logger.debug("Extracting '" + entryName + "'.");

                // Copy nested jar file to temp dir
                extractedFile = new File(this.tempDir, entryName);
                extractedFile.getParentFile().mkdirs();

                extractedFileOutputStream = new FileOutputStream(extractedFile);
                FileCopyUtils.copy(jarFile.getInputStream(entry), extractedFileOutputStream);
                extractedFileOutputStream = null;

                if ((entryName.startsWith(LIB_PATH)) && (entryName.toLowerCase().endsWith(".jar"))) {
                    // Register nested jar file in "class path"
                    super.addURL(extractedFile.toURI().toURL());
                }
            }
        }
    }

    jarFile.close();
    jarFile = null;

    super.addURL(tempDir.toURI().toURL()); // Add temp dir as class path (note that this must be added after all the
                                           // files have been extracted)

    if (logger.isDebugEnabled())
        logger.debug("Done extracting module jar file '" + moduleJarFile + "'.");
}

From source file:org.apache.sling.osgi.obr.Repository.java

File spoolModified(InputStream ins) throws IOException {
    JarInputStream jis = new JarInputStream(ins);

    // immediately handle the manifest
    JarOutputStream jos;// ww  w  .j a v a 2s.  co  m
    Manifest manifest = jis.getManifest();
    if (manifest == null) {
        throw new IOException("Missing Manifest !");
    }

    String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
    if (symbolicName == null || symbolicName.length() == 0) {
        throw new IOException("Missing Symbolic Name in Manifest !");
    }

    String version = manifest.getMainAttributes().getValue("Bundle-Version");
    Version v = Version.parseVersion(version);
    if (v.getQualifier().indexOf("SNAPSHOT") >= 0) {
        String tStamp;
        synchronized (DATE_FORMAT) {
            tStamp = DATE_FORMAT.format(new Date());
        }
        version = v.getMajor() + "." + v.getMinor() + "." + v.getMicro() + "."
                + v.getQualifier().replaceAll("SNAPSHOT", tStamp);
        manifest.getMainAttributes().putValue("Bundle-Version", version);
    }

    File bundle = new File(this.repoLocation, symbolicName + "-" + v + ".jar");
    OutputStream out = null;
    try {
        out = new FileOutputStream(bundle);
        jos = new JarOutputStream(out, manifest);

        jos.setMethod(JarOutputStream.DEFLATED);
        jos.setLevel(Deflater.BEST_COMPRESSION);

        JarEntry entryIn = jis.getNextJarEntry();
        while (entryIn != null) {
            JarEntry entryOut = new JarEntry(entryIn.getName());
            entryOut.setTime(entryIn.getTime());
            entryOut.setComment(entryIn.getComment());
            jos.putNextEntry(entryOut);
            if (!entryIn.isDirectory()) {
                spool(jis, jos);
            }
            jos.closeEntry();
            jis.closeEntry();
            entryIn = jis.getNextJarEntry();
        }

        // close the JAR file now to force writing
        jos.close();

    } finally {
        IOUtils.closeQuietly(out);
    }

    return bundle;
}

From source file:org.drools.guvnor.server.RepositoryModuleService.java

private JarInputStream typesForModel(List<String> res, AssetItem asset) throws IOException {
    if (!asset.isBinary()) {
        return null;
    }/*from w  w  w. j  a v a 2  s.c o m*/
    if (asset.getBinaryContentAttachment() == null) {
        return null;
    }

    JarInputStream jis;
    jis = new JarInputStream(asset.getBinaryContentAttachment());
    JarEntry entry = null;
    while ((entry = jis.getNextJarEntry()) != null) {
        if (!entry.isDirectory()) {
            if (entry.getName().endsWith(".class") && !entry.getName().endsWith("package-info.class")) {
                res.add(ModelContentHandler.convertPathToName(entry.getName()));
            }
        }
    }
    return jis;
}

From source file:org.sakaiproject.kernel1.Activator.java

/**
 * {@inheritDoc}/*from  ww  w  .j  a  v  a  2s  .  c  o  m*/
 * 
 * @see org.sakaiproject.kernel.api.ComponentActivator#activate(org.sakaiproject.kernel.api.Kernel)
 */
public void activate(Kernel kernel) throws ComponentActivatorException {

    this.kernel = kernel;
    // here I want to create my services and register them
    // I could use Guice or Spring to do this, but I am going to do manual IoC
    // to keep it really simple
    InternalDateServiceImpl internalDateService = new InternalDateServiceImpl();
    HelloWorldService helloWorldService = new HelloWorldServiceImpl(internalDateService);

    org.sakaiproject.component.api.ComponentManager cm = null;

    long start = System.currentTimeMillis();
    try {
        LOG.info("START---------------------- Loading kernel 1");
        cm = ComponentManager.getInstance();
    } catch (Throwable t) {
        LOG.error("Failed to Startup ", t);
    }
    LOG.info("END------------------------ Loaded kernel 1 in  " + (System.currentTimeMillis() - start) + "ms");

    Properties localProperties = new Properties();
    try {
        InputStream is = ResourceLoader.openResource(K1_PROPERTIES, this.getClass().getClassLoader());
        localProperties.load(is);
    } catch (IOException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }

    /**
     * plagerized from k2 bootstrap module **
     */

    for (Entry<Object, Object> o : localProperties.entrySet()) {
        String k = o.getKey().toString();

        if (k.startsWith("+")) {
            String p = properties.getProperty(k.substring(1));
            if (p != null) {
                properties.put(k.substring(1), p + o.getValue());
            } else {
                properties.put(o.getKey(), o.getValue());
            }
        } else {
            properties.put(o.getKey(), o.getValue());
        }
    }
    LOG.info("Loaded " + localProperties.size() + " properties from " + K1_PROPERTIES);

    /**
     * plagerized from the ComponentLoaderService
     */

    ArtifactResolverService artifactResolverService = new Maven2ArtifactResolver();

    List<URL> locations = new ArrayList<URL>();
    String[] locs = StringUtils.split(properties.getProperty(K1_COMPONENT_LOCATION), ';');
    if (locs != null) {
        for (String location : locs) {
            location = location.trim();
            if (location.startsWith("maven-repo")) {
                Artifact dep = DependencyImpl.fromString(location);
                URL u = null;
                try {
                    u = artifactResolverService.resolve(null, dep);
                } catch (ComponentSpecificationException e) {
                    LOG.error("Can't resolve " + K1_COMPONENT_LOCATION + " property in file " + K1_PROPERTIES);
                    e.printStackTrace();
                }
                LOG.info("added k1 api bundle:" + u);
                locations.add(u);
            } else if (location.endsWith(".jar")) {
                if (location.indexOf("://") < 0) {
                    File f = new File(location);
                    if (!f.exists()) {
                        LOG.warn("Jar file " + f.getAbsolutePath() + " does not exist, will be ignored ");
                    } else {
                        try {
                            location = "file://" + f.getCanonicalPath();
                            locations.add(new URL(location));
                            LOG.info("added k1 api bundle:" + location);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                } else {
                    LOG.info("added api bundle:" + location);
                    try {
                        locations.add(new URL(location));
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            } else {
                LOG.info("Locating api bundle in " + location);
                for (File f : FileUtil.findAll(location, ".jar")) {
                    String path = null;
                    try {
                        path = f.getCanonicalPath();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (path.indexOf("://") < 0) {
                        path = "file://" + path;
                    }
                    LOG.info("    added api bundle:" + path);
                    try {
                        locations.add(new URL(path));
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    LOG.info("    bundle contains " + locations.size() + " uri's");

    // find all the instances
    URLClassLoader uclassloader = new URLClassLoader(locations.toArray(new URL[0]), null);

    /**
     * end plagerism.... for now
     */
    JarFile jar = null;
    for (URL url : locations) {
        try {
            jar = new JarFile(new File(url.toURI()));

            Enumeration<JarEntry> entries = jar.entries();

            for (; entries.hasMoreElements();) {
                JarEntry entry = entries.nextElement();
                if (entry != null && entry.getName().endsWith(".class")) {
                    ifcClassNames.add(entry.getName().replaceAll("/", "."));
                }
            }

            jar.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // thats it. my service is ready to go, so lets register it
    // get the service manager
    ServiceManager serviceManager = kernel.getServiceManager();

    List<Class> ifcClasses = new ArrayList<Class>();
    String className = null;
    for (Iterator<String> i = ifcClassNames.iterator(); i.hasNext();) {
        try {
            className = i.next();
            ifcClasses.add(Class.forName(className));
        } catch (ClassNotFoundException e) {
            LOG.error("Can't find '" + className + "' in the classpath");
            i.remove(); // / with a sharp stick
            e.printStackTrace();
        }
    }

    for (Class clazz : ifcClasses) {
        ServiceSpec serviceSpec = new ServiceSpec(clazz);

        // register the service
        try {
            serviceManager.registerService(serviceSpec, cm.get(clazz));
        } catch (ServiceManagerException e) {
            // oops something happened, re-throw as an activation issue
            throw new ComponentActivatorException("Failed to register service ", e);
        }

    }

    // just for fun.. resolve the JCRService and get a reference to the
    // respository.
    LOG.info("Getting JCR =============================");
    JCRService service = serviceManager.getService(new ServiceSpec(JCRService.class));
    Repository repo = service.getRepository();
    for (String k : repo.getDescriptorKeys()) {
        LOG.info("  JCR Repo Key " + k + "::" + repo.getDescriptor(k));
    }
    LOG.info("Logged In OK-=============================");

    // create a ServiceSpecification for the class I want to register,
    // the class here MUST be a class that was exported (see component.xml)
    // otherwise
    // nothing else will be able to see it. The service manager might enforce
    // this if I get
    // arround to it.
    ServiceSpec serviceSpec = new ServiceSpec(HelloWorldService.class);

    // register the service
    try {
        serviceManager.registerService(serviceSpec, helloWorldService);
    } catch (ServiceManagerException e) {
        // oops something happened, re-throw as an activation issue
        throw new ComponentActivatorException("Failed to register service ", e);
    }

}

From source file:com.jeeframework.util.resource.ResolverUtil.java

/**
 * Finds matching classes within a jar files that contains a folder structure
 * matching the package structure.  If the File is not a JarFile or does not exist a warning
 * will be logged, but no error will be raised.
 *
 * @param test a Test used to filter the classes that are discovered
 * @param parent the parent package under which classes must be in order to be considered
 * @param jarfile the jar file to be examined for classes
 *//*w ww. j  a v a  2  s.  co m*/
private void loadImplementationsInJar(Test test, String parent, File jarfile) {

    try {
        JarEntry entry;
        JarInputStream jarStream = new JarInputStream(new FileInputStream(jarfile));

        while ((entry = jarStream.getNextJarEntry()) != null) {
            String name = entry.getName();
            if (!entry.isDirectory() && name.startsWith(parent) && name.endsWith(".class")) {
                addIfMatching(test, name);
            }
        }
    } catch (IOException ioe) {
        log.error("Could not search jar file '" + jarfile + "' for classes matching criteria: " + test
                + " due to an IOException", ioe);
    }
}

From source file:cn.webwheel.DefaultMain.java

/**
 * Find action method under certain package recursively.
 * <p>//from   www.j  av  a  2 s .c o  m
 * Action method must be marked by {@link Action}(may be through parent class).<br/>
 * Url will be the package path under rootpkg.<br/>
 * <b>example</b><br/>
 * action class:
 * <p><blockquote><pre>
 *     package com.my.app.web.user;
 *     public class insert {
 *        {@code @}Action
 *         public Object act() {...}
 *     }
 * </pre></blockquote><p>
 * This action method will be mapped to url: /user/insert.act
 * @see #map(String)
 * @see Action
 * @param rootpkg action class package
 */
@SuppressWarnings("deprecation")
final protected void autoMap(String rootpkg) {
    DefaultAction.defPagePkg = rootpkg;
    try {
        Enumeration<URL> enm = getClass().getClassLoader().getResources(rootpkg.replace('.', '/'));
        while (enm.hasMoreElements()) {
            URL url = enm.nextElement();
            if (url.getProtocol().equals("file")) {
                autoMap(rootpkg.replace('.', '/'), rootpkg, new File(URLDecoder.decode(url.getFile())));
            } else if (url.getProtocol().equals("jar")) {
                String file = URLDecoder.decode(url.getFile());
                String root = file.substring(file.lastIndexOf('!') + 2);
                file = file.substring(0, file.length() - root.length() - 2);
                URL jarurl = new URL(file);
                if (jarurl.getProtocol().equals("file")) {
                    JarFile jarFile = new JarFile(URLDecoder.decode(jarurl.getFile()));
                    try {
                        Enumeration<JarEntry> entries = jarFile.entries();
                        while (entries.hasMoreElements()) {
                            JarEntry entry = entries.nextElement();
                            String name = entry.getName();
                            if (!name.endsWith(".class"))
                                continue;
                            if (!name.startsWith(root + '/'))
                                continue;
                            name = name.substring(0, name.length() - 6);
                            name = name.replace('/', '.');
                            int i = name.lastIndexOf('.');
                            autoMap(root, name.substring(0, i), name.substring(i + 1));
                        }
                    } finally {
                        jarFile.close();
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.drools.guvnor.server.contenthandler.soa.JarFileContentHandler.java

private String getClassesFromJar(AssetItem assetItem) throws IOException {
    Map<String, String> nonCollidingImports = new HashMap<String, String>();
    String assetPackageName = assetItem.getModuleName();

    //Setup class-loader to check for class visibility
    JarInputStream cljis = new JarInputStream(assetItem.getBinaryContentAttachment());
    List<JarInputStream> jarInputStreams = new ArrayList<JarInputStream>();
    jarInputStreams.add(cljis);/*from  w ww.j  av a2s  .  co m*/
    ClassLoaderBuilder clb = new ClassLoaderBuilder(jarInputStreams);
    ClassLoader cl = clb.buildClassLoader();

    //Reset stream to read classes
    JarInputStream jis = new JarInputStream(assetItem.getBinaryContentAttachment());
    JarEntry entry = null;

    //Get Class names from JAR, only the first occurrence of a given Class leaf name will be inserted. Thus 
    //"org.apache.commons.lang.NumberUtils" will be imported but "org.apache.commons.lang.math.NumberUtils"
    //will not, assuming it follows later in the JAR structure.
    while ((entry = jis.getNextJarEntry()) != null) {
        if (!entry.isDirectory()) {
            if (entry.getName().endsWith(".class") && entry.getName().indexOf('$') == -1
                    && !entry.getName().endsWith("package-info.class")) {
                String fullyQualifiedName = convertPathToName(entry.getName());
                if (isClassVisible(cl, fullyQualifiedName, assetPackageName)) {
                    String leafName = getLeafName(fullyQualifiedName);
                    if (!nonCollidingImports.containsKey(leafName)) {
                        nonCollidingImports.put(leafName, fullyQualifiedName);
                    }
                }
            }
        }
    }

    //Build list of classes
    StringBuffer classes = new StringBuffer();
    for (String value : nonCollidingImports.values()) {
        classes.append(value + "\n");
    }

    return classes.toString();
}