Example usage for java.util.jar JarFile entries

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

Introduction

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

Prototype

public Enumeration<JarEntry> entries() 

Source Link

Document

Returns an enumeration of the jar file entries.

Usage

From source file:org.corpus_tools.salt.util.VisJsVisualizer.java

private File createOutputResources(URI outputFileUri)
        throws SaltParameterException, SecurityException, FileNotFoundException, IOException {
    File outputFolder = null;//w  ww. ja  v  a2  s  .c o  m
    if (outputFileUri == null) {
        throw new SaltParameterException("Cannot store salt-vis, because the passed output uri is empty. ");
    }
    outputFolder = new File(outputFileUri.path());
    if (!outputFolder.exists()) {
        if (!outputFolder.mkdirs()) {
            throw new SaltException("Can't create folder " + outputFolder.getAbsolutePath());
        }
    }

    File cssFolderOut = new File(outputFolder, CSS_FOLDER_OUT);
    if (!cssFolderOut.exists()) {
        if (!cssFolderOut.mkdir()) {
            throw new SaltException("Can't create folder " + cssFolderOut.getAbsolutePath());
        }
    }

    File jsFolderOut = new File(outputFolder, JS_FOLDER_OUT);
    if (!jsFolderOut.exists()) {
        if (!jsFolderOut.mkdir()) {
            throw new SaltException("Can't create folder " + jsFolderOut.getAbsolutePath());
        }
    }

    File imgFolderOut = new File(outputFolder, IMG_FOLDER_OUT);
    if (!imgFolderOut.exists()) {
        if (!imgFolderOut.mkdirs()) {
            throw new SaltException("Can't create folder " + imgFolderOut.getAbsolutePath());
        }
    }

    copyResourceFile(
            getClass().getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + CSS_FILE),
            outputFolder.getPath(), CSS_FOLDER_OUT, CSS_FILE);

    copyResourceFile(
            getClass().getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + JS_FILE),
            outputFolder.getPath(), JS_FOLDER_OUT, JS_FILE);

    copyResourceFile(
            getClass()
                    .getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + JQUERY_FILE),
            outputFolder.getPath(), JS_FOLDER_OUT, JQUERY_FILE);

    ClassLoader classLoader = getClass().getClassLoader();
    CodeSource srcCode = VisJsVisualizer.class.getProtectionDomain().getCodeSource();
    URL codeSourceUrl = srcCode.getLocation();
    File codeSourseFile = new File(codeSourceUrl.getPath());

    if (codeSourseFile.isDirectory()) {
        File imgFolder = new File(classLoader.getResource(RESOURCE_FOLDER_IMG_NETWORK).getFile());
        File[] imgFiles = imgFolder.listFiles();
        if (imgFiles != null) {
            for (File imgFile : imgFiles) {
                InputStream inputStream = getClass()
                        .getResourceAsStream(System.getProperty("file.separator") + RESOURCE_FOLDER_IMG_NETWORK
                                + System.getProperty("file.separator") + imgFile.getName());
                copyResourceFile(inputStream, outputFolder.getPath(), IMG_FOLDER_OUT, imgFile.getName());
            }
        }
    } else if (codeSourseFile.getName().endsWith("jar")) {
        JarFile jarFile = new JarFile(codeSourseFile);
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (entry.getName().startsWith(RESOURCE_FOLDER_IMG_NETWORK) && !entry.isDirectory()) {

                copyResourceFile(jarFile.getInputStream(entry), outputFolder.getPath(), IMG_FOLDER_OUT,
                        entry.getName().replaceFirst(RESOURCE_FOLDER_IMG_NETWORK, ""));
            }

        }
        jarFile.close();

    }

    return outputFolder;
}

From source file:com.twosigma.beaker.autocomplete.ClasspathScanner.java

private boolean findClasses(File root, File file, boolean includeJars) {
    if (file != null && file.isDirectory()) {
        File[] lf = file.listFiles();
        if (lf != null)
            for (File child : lf) {
                if (!findClasses(root, child, includeJars)) {
                    return false;
                }/*  w  ww. j a  v a  2  s .co m*/
            }
    } else {
        if (file.getName().toLowerCase().endsWith(".jar") && includeJars) {
            JarFile jar = null;
            try {
                jar = new JarFile(file);
            } catch (Exception ex) {
            }
            if (jar != null) {
                try {
                    Manifest mf = jar.getManifest();
                    if (mf != null) {
                        String cp = mf.getMainAttributes().getValue("Class-Path");
                        if (StringUtils.isNotEmpty(cp)) {
                            for (String fn : cp.split(" ")) {
                                File child = new File(
                                        file.getParent() + System.getProperty("file.separator") + fn);
                                if (child.getAbsolutePath().equals(jar.getName())) {
                                    continue; //skip bad jars, that contain references to themselves in MANIFEST.MF
                                }
                                if (child.exists()) {
                                    if (!findClasses(root, child, includeJars)) {
                                        return false;
                                    }
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                }

                Enumeration<JarEntry> entries = jar.entries();
                while (entries.hasMoreElements()) {
                    JarEntry entry = entries.nextElement();
                    String name = entry.getName();
                    int extIndex = name.lastIndexOf(".class");
                    if (extIndex > 0 && !name.contains("$")) {
                        String cname = name.substring(0, extIndex).replace("/", ".");
                        int pIndex = cname.lastIndexOf('.');
                        if (pIndex > 0) {
                            String pname = cname.substring(0, pIndex);
                            cname = cname.substring(pIndex + 1);
                            if (!packages.containsKey(pname))
                                packages.put(pname, new ArrayList<String>());
                            packages.get(pname).add(cname);
                        }
                    }
                }
            }
        } else if (file.getName().toLowerCase().endsWith(".class")) {
            String cname = createClassName(root, file);
            if (!cname.contains("$")) {
                int pIndex = cname.lastIndexOf('.');
                if (pIndex > 0) {
                    String pname = cname.substring(0, pIndex + 1);
                    cname = cname.substring(pIndex);
                    if (!packages.containsKey(pname))
                        packages.put(pname, new ArrayList<String>());
                    packages.get(pname).add(cname);
                }
            }
        } else {
            examineFile(root, file);
        }
    }

    return true;
}

From source file:catalina.startup.ContextConfig.java

/**
 * Scan the JAR file at the specified resource path for TLDs in the
 * <code>META-INF</code> subdirectory, and scan them for application
 * event listeners that need to be registered.
 *
 * @param resourcePath Resource path of the JAR file to scan
 *
 * @exception Exception if an exception occurs while scanning this JAR
 */// w w w  .ja v a 2s .  c om
private void tldScanJar(String resourcePath) throws Exception {

    if (debug >= 1) {
        log(" Scanning JAR at resource path '" + resourcePath + "'");
    }

    JarFile jarFile = null;
    String name = null;
    InputStream inputStream = null;
    try {
        URL url = context.getServletContext().getResource(resourcePath);
        if (url == null) {
            throw new IllegalArgumentException(sm.getString("contextConfig.tldResourcePath", resourcePath));
        }
        url = new URL("jar:" + url.toString() + "!/");
        JarURLConnection conn = (JarURLConnection) url.openConnection();
        conn.setUseCaches(false);
        jarFile = conn.getJarFile();
        Enumeration entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            name = entry.getName();
            if (!name.startsWith("META-INF/")) {
                continue;
            }
            if (!name.endsWith(".tld")) {
                continue;
            }
            if (debug >= 2) {
                log("  Processing TLD at '" + name + "'");
            }
            inputStream = jarFile.getInputStream(entry);
            tldScanStream(inputStream);
            inputStream.close();
            inputStream = null;
            name = null;
        }
        // FIXME - Closing the JAR file messes up the class loader???
        //            jarFile.close();
    } catch (Exception e) {
        if (name == null) {
            throw new ServletException(sm.getString("contextConfig.tldJarException", resourcePath), e);
        } else {
            throw new ServletException(sm.getString("contextConfig.tldEntryException", name, resourcePath), e);
        }
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Throwable t) {
                ;
            }
            inputStream = null;
        }
        if (jarFile != null) {
            // FIXME - Closing the JAR file messes up the class loader???
            //                try {
            //                    jarFile.close();
            //                } catch (Throwable t) {
            //                    ;
            //                }
            jarFile = null;
        }
    }

}

From source file:com.jivesoftware.os.upena.deployable.UpenaMain.java

private void injectUI(String upenaVersion, AWSClientFactory awsClientFactory, ObjectMapper storeMapper,
        ObjectMapper mapper, JDIAPI jvmapi, AmzaService amzaService, PathToRepo localPathToRepo,
        RepositoryProvider repositoryProvider, HostKey hostKey, UpenaRingHost ringHost,
        UpenaSSLConfig upenaSSLConfig, int port, SessionStore sessionStore, UbaService ubaService,
        UpenaHealth upenaHealth, UpenaStore upenaStore, UpenaConfigStore upenaConfigStore,
        UpenaJerseyEndpoints jerseyEndpoints, String humanReadableUpenaClusterName,
        DiscoveredRoutes discoveredRoutes) throws SoySyntaxException, IOException {

    SoyFileSet.Builder soyFileSetBuilder = new SoyFileSet.Builder();

    LOG.info("Add....");

    URL dirURL = UpenaMain.class.getClassLoader().getResource("resources/soy/");
    if (dirURL != null && dirURL.getProtocol().equals("jar")) {
        String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!"));
        JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            String name = entries.nextElement().getName();
            if (name.endsWith(".soy") && name.startsWith("resources/soy/")) {
                String soyName = name.substring(name.lastIndexOf('/') + 1);
                LOG.info("/" + name + " " + soyName);
                soyFileSetBuilder.add(this.getClass().getResource("/" + name), soyName);
            }//w w w .  j  a v a2  s .  c om
        }
    } else {
        List<String> soyFiles = IOUtils.readLines(this.getClass().getResourceAsStream("resources/soy/"),
                StandardCharsets.UTF_8);
        for (String soyFile : soyFiles) {
            LOG.info("Adding {}", soyFile);
            soyFileSetBuilder.add(this.getClass().getResource("/resources/soy/" + soyFile), soyFile);
        }
    }

    SoyFileSet sfs = soyFileSetBuilder.build();
    SoyTofu tofu = sfs.compileToTofu();
    SoyRenderer renderer = new SoyRenderer(tofu, new SoyDataUtils());
    SoyService soyService = new SoyService(upenaVersion, renderer,
            //new HeaderRegion("soy.upena.chrome.headerRegion", renderer),
            new MenuRegion("soy.upena.chrome.menuRegion", renderer),
            new HomeRegion("soy.upena.page.homeRegion", renderer, hostKey, upenaStore, ubaService),
            humanReadableUpenaClusterName, hostKey, upenaStore);

    AuthPluginRegion authRegion = new AuthPluginRegion("soy.upena.page.authPluginRegion", renderer);
    OktaMFAAuthPluginRegion oktaMFAAuthRegion = new OktaMFAAuthPluginRegion(
            "soy.upena.page.oktaMFAAuthPluginRegion", renderer);
    jerseyEndpoints.addInjectable(OktaMFAAuthPluginRegion.class, oktaMFAAuthRegion);

    UnauthorizedPluginRegion unauthorizedRegion = new UnauthorizedPluginRegion(
            "soy.upena.page.unauthorizedPluginRegion", renderer);

    PluginHandle auth = new PluginHandle("login", null, "Login", "/ui/auth/login", AuthPluginEndpoints.class,
            authRegion, null, "read");

    HealthPluginRegion healthPluginRegion = new HealthPluginRegion(mapper, System.currentTimeMillis(), ringHost,
            "soy.upena.page.healthPluginRegion", "soy.upena.page.instanceHealthPluginRegion",
            "soy.upena.page.healthPopup", renderer, upenaHealth, upenaStore);
    ReleasesPluginRegion releasesPluginRegion = new ReleasesPluginRegion(mapper, repositoryProvider,
            "soy.upena.page.releasesPluginRegion", "soy.upena.page.releasesPluginRegionList", renderer,
            upenaStore);
    HostsPluginRegion hostsPluginRegion = new HostsPluginRegion("soy.upena.page.hostsPluginRegion",
            "soy.upena.page.removeHostPluginRegion", renderer, upenaStore);
    InstancesPluginRegion instancesPluginRegion = new InstancesPluginRegion(
            "soy.upena.page.instancesPluginRegion", "soy.upena.page.instancesPluginRegionList", renderer,
            upenaHealth, upenaStore, hostKey, healthPluginRegion, awsClientFactory);

    PluginHandle health = new PluginHandle("fire", null, "Health", "/ui/health", HealthPluginEndpoints.class,
            healthPluginRegion, null, "read");

    PluginHandle topology = new PluginHandle("th", null, "Topology", "/ui/topology",
            TopologyPluginEndpoints.class,
            new TopologyPluginRegion(mapper, "soy.upena.page.topologyPluginRegion",
                    "soy.upena.page.connectionsHealth", renderer, upenaHealth, amzaService, upenaSSLConfig,
                    upenaStore, healthPluginRegion, hostsPluginRegion, releasesPluginRegion,
                    instancesPluginRegion, discoveredRoutes),
            null, "read");

    PluginHandle connectivity = new PluginHandle("transfer", null, "Connectivity", "/ui/connectivity",
            ConnectivityPluginEndpoints.class,
            new ConnectivityPluginRegion(mapper, "soy.upena.page.connectivityPluginRegion",
                    "soy.upena.page.connectionsHealth", "soy.upena.page.connectionOverview", renderer,
                    upenaHealth, amzaService, upenaSSLConfig, upenaStore, healthPluginRegion, discoveredRoutes),
            null, "read");

    PluginHandle changes = new PluginHandle("road", null, "Changes", "/ui/changeLog",
            ChangeLogPluginEndpoints.class,
            new ChangeLogPluginRegion("soy.upena.page.changeLogPluginRegion", renderer, upenaStore), null,
            "read");

    PluginHandle instances = new PluginHandle("star", null, "Instances", "/ui/instances",
            InstancesPluginEndpoints.class, instancesPluginRegion, null, "read");

    PluginHandle config = new PluginHandle("cog", null, "Config", "/ui/config", ConfigPluginEndpoints.class,
            new ConfigPluginRegion(mapper, "soy.upena.page.configPluginRegion", renderer, upenaSSLConfig,
                    upenaStore, upenaConfigStore),
            null, "read");

    PluginHandle repo = new PluginHandle("hdd", null, "Repository", "/ui/repo", RepoPluginEndpoints.class,
            new RepoPluginRegion("soy.upena.page.repoPluginRegion", renderer, upenaStore, localPathToRepo),
            null, "read");

    PluginHandle projects = new PluginHandle("folder-open", null, "Projects", "/ui/projects",
            ProjectsPluginEndpoints.class,
            new ProjectsPluginRegion("soy.upena.page.projectsPluginRegion", "soy.upena.page.projectBuildOutput",
                    "soy.upena.page.projectBuildOutputTail", renderer, upenaStore, localPathToRepo),
            null, "read");

    PluginHandle users = new PluginHandle("user", null, "Users", "/ui/users", UsersPluginEndpoints.class,
            new UsersPluginRegion("soy.upena.page.usersPluginRegion", renderer, upenaStore), null, "read");

    PluginHandle permissions = new PluginHandle("lock", null, "Permission", "/ui/permissions",
            PermissionsPluginEndpoints.class,
            new PermissionsPluginRegion("soy.upena.page.permissionsPluginRegion", renderer, upenaStore), null,
            "read");

    PluginHandle clusters = new PluginHandle("cloud", null, "Clusters", "/ui/clusters",
            ClustersPluginEndpoints.class,
            new ClustersPluginRegion("soy.upena.page.clustersPluginRegion", renderer, upenaStore), null,
            "read");

    PluginHandle hosts = new PluginHandle("tasks", null, "Hosts", "/ui/hosts", HostsPluginEndpoints.class,
            hostsPluginRegion, null, "read");

    PluginHandle services = new PluginHandle("tint", null, "Services", "/ui/services",
            ServicesPluginEndpoints.class,
            new ServicesPluginRegion(mapper, "soy.upena.page.servicesPluginRegion", renderer, upenaStore), null,
            "read");

    PluginHandle releases = new PluginHandle("send", null, "Releases", "/ui/releases",
            ReleasesPluginEndpoints.class, releasesPluginRegion, null, "read");

    PluginHandle modules = new PluginHandle("wrench", null, "Modules", "/ui/modules",
            ModulesPluginEndpoints.class, new ModulesPluginRegion(mapper, repositoryProvider,
                    "soy.upena.page.modulesPluginRegion", renderer, upenaStore),
            null, "read");

    PluginHandle proxy = new PluginHandle("random", null, "Proxies", "/ui/proxy", ProxyPluginEndpoints.class,
            new ProxyPluginRegion("soy.upena.page.proxyPluginRegion", renderer), null, "read", "debug");

    PluginHandle ring = new PluginHandle("leaf", null, "Upena", "/ui/ring", UpenaRingPluginEndpoints.class,
            new UpenaRingPluginRegion(storeMapper, "soy.upena.page.upenaRingPluginRegion", renderer,
                    amzaService, upenaStore, upenaConfigStore),
            null, "read", "debug");

    PluginHandle loadBalancer = new PluginHandle("scale", null, "Load Balancer", "/ui/loadbalancers",
            LoadBalancersPluginEndpoints.class,
            new LoadBalancersPluginRegion("soy.upena.page.loadBalancersPluginRegion", renderer, upenaStore,
                    awsClientFactory),
            null, "read", "debug");

    ServicesCallDepthStack servicesCallDepthStack = new ServicesCallDepthStack();
    PerfService perfService = new PerfService(servicesCallDepthStack);

    PluginHandle profiler = new PluginHandle("hourglass", null, "Profiler", "/ui/profiler",
            ProfilerPluginEndpoints.class, new ProfilerPluginRegion("soy.upena.page.profilerPluginRegion",
                    renderer, new VisualizeProfile(new NameUtils(), servicesCallDepthStack)),
            null, "read", "debug");

    PluginHandle jvm = null;
    PluginHandle breakpointDumper = null;
    if (jvmapi != null) {
        jvm = new PluginHandle("camera", null, "JVM", "/ui/jvm", JVMPluginEndpoints.class,
                new JVMPluginRegion("soy.upena.page.jvmPluginRegion", renderer, upenaStore, jvmapi), null,
                "read", "debug");

        breakpointDumper = new PluginHandle("record", null, "Breakpoint Dumper", "/ui/breakpoint",
                BreakpointDumperPluginEndpoints.class,
                new BreakpointDumperPluginRegion("soy.upena.page.breakpointDumperPluginRegion", renderer,
                        upenaStore, jvmapi),
                null, "read", "debug");
    }

    PluginHandle aws = null;
    aws = new PluginHandle("globe", null, "AWS", "/ui/aws", AWSPluginEndpoints.class,
            new AWSPluginRegion("soy.upena.page.awsPluginRegion", renderer, awsClientFactory), null, "read",
            "debug");

    PluginHandle monkey = new PluginHandle("flash", null, "Chaos", "/ui/chaos", MonkeyPluginEndpoints.class,
            new MonkeyPluginRegion("soy.upena.page.monkeyPluginRegion", renderer, upenaStore), null, "read",
            "debug");

    PluginHandle api = new PluginHandle("play-circle", null, "API", "/ui/api", ApiPluginEndpoints.class, null,
            null, "read", "debug");

    PluginHandle thrown = new PluginHandle("equalizer", null, "Thrown", "/ui/thrown",
            ThrownPluginEndpoints.class,
            new ThrownPluginRegion(hostKey, "soy.upena.page.thrownPluginRegion", renderer, upenaStore), null,
            "read", "debug");

    PluginHandle probe = new PluginHandle("hand-right", null, "Deployable", "/ui/deployable",
            ManagedDeployablePluginEndpoints.class, new ManagedDeployablePluginRegion(sessionStore, hostKey,
                    "soy.upena.page.deployablePluginRegion", renderer, upenaStore, upenaSSLConfig, port),
            null, "read", "debug");

    List<PluginHandle> plugins = new ArrayList<>();
    plugins.add(auth);
    plugins.add(new PluginHandle(null, null, "API", null, null, null, "separator", "read"));
    plugins.add(api);
    plugins.add(new PluginHandle(null, null, "Build", null, null, null, "separator", "read"));
    plugins.add(repo);
    plugins.add(projects);
    plugins.add(modules);
    plugins.add(new PluginHandle(null, null, "Config", null, null, null, "separator", "read"));
    plugins.add(aws);
    plugins.add(changes);
    plugins.add(config);
    plugins.add(clusters);
    plugins.add(hosts);
    plugins.add(services);
    plugins.add(releases);
    plugins.add(instances);
    plugins.add(loadBalancer);
    plugins.add(new PluginHandle(null, null, "Health", null, null, null, "separator", "read"));
    plugins.add(health);
    plugins.add(connectivity);
    plugins.add(topology);
    plugins.add(new PluginHandle(null, null, "Tools", null, null, null, "separator", "read", "debug"));
    plugins.add(monkey);
    plugins.add(proxy);
    if (jvm != null) {
        plugins.add(jvm);
        plugins.add(thrown);
        plugins.add(breakpointDumper);
    }
    plugins.add(profiler);
    plugins.add(ring);
    plugins.add(users);
    plugins.add(permissions);

    jerseyEndpoints.addInjectable(SessionStore.class, sessionStore);
    jerseyEndpoints.addInjectable(UpenaSSLConfig.class, upenaSSLConfig);
    jerseyEndpoints.addInjectable(SoyService.class, soyService);
    jerseyEndpoints.addEndpoint(AsyncLookupEndpoints.class);
    jerseyEndpoints.addInjectable(AsyncLookupService.class, new AsyncLookupService(upenaSSLConfig, upenaStore));

    jerseyEndpoints.addEndpoint(PerfServiceEndpoints.class);
    jerseyEndpoints.addInjectable(PerfService.class, perfService);

    for (PluginHandle plugin : plugins) {
        soyService.registerPlugin(plugin);
        if (plugin.separator == null) {
            jerseyEndpoints.addEndpoint(plugin.endpointsClass);
            if (plugin.region != null) {
                jerseyEndpoints.addInjectable(plugin.region.getClass(), plugin.region);
            }
        }
    }

    jerseyEndpoints.addEndpoint(probe.endpointsClass);
    jerseyEndpoints.addInjectable(probe.region.getClass(), probe.region);

    jerseyEndpoints.addInjectable(UnauthorizedPluginRegion.class, unauthorizedRegion);
    //jerseyEndpoints.addEndpoint(UpenaPropagatorEndpoints.class);
}

From source file:org.b3log.latke.ioc.ClassPathResolver.java

/**
 * scan the jar to get the URLS of the Classes.
 *
 * @param rootDirResource which is "Jar"
 * @param subPattern      subPattern/*from   w w w  .  j  a  v  a2  s  .  c om*/
 * @return the URLs of all the matched classes
 */
private static Collection<? extends URL> doFindPathMatchingJarResources(final URL rootDirResource,
        final String subPattern) {

    final Set<URL> result = new LinkedHashSet<URL>();

    JarFile jarFile = null;
    String jarFileUrl;
    String rootEntryPath = null;
    URLConnection con;
    boolean newJarFile = false;

    try {
        con = rootDirResource.openConnection();

        if (con instanceof JarURLConnection) {
            final JarURLConnection jarCon = (JarURLConnection) con;

            jarCon.setUseCaches(false);
            jarFile = jarCon.getJarFile();
            jarFileUrl = jarCon.getJarFileURL().toExternalForm();
            final JarEntry jarEntry = jarCon.getJarEntry();

            rootEntryPath = jarEntry != null ? jarEntry.getName() : "";
        } else {
            // No JarURLConnection -> need to resort to URL file parsing.
            // We'll assume URLs of the format "jar:path!/entry", with the
            // protocol
            // being arbitrary as long as following the entry format.
            // We'll also handle paths with and without leading "file:"
            // prefix.
            final String urlFile = rootDirResource.getFile();
            final int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);

            if (separatorIndex != -1) {
                jarFileUrl = urlFile.substring(0, separatorIndex);
                rootEntryPath = urlFile.substring(separatorIndex + JAR_URL_SEPARATOR.length());
                jarFile = getJarFile(jarFileUrl);
            } else {
                jarFile = new JarFile(urlFile);
                jarFileUrl = urlFile;
                rootEntryPath = "";
            }
            newJarFile = true;

        }

    } catch (final IOException e) {
        LOGGER.log(Level.ERROR, "reslove jar File error", e);
        return result;
    }
    try {
        if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
            // Root entry path must end with slash to allow for proper
            // matching.
            // The Sun JRE does not return a slash here, but BEA JRockit
            // does.
            rootEntryPath = rootEntryPath + "/";
        }
        for (final Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            final JarEntry entry = (JarEntry) entries.nextElement();
            final String entryPath = entry.getName();

            String relativePath = null;

            if (entryPath.startsWith(rootEntryPath)) {
                relativePath = entryPath.substring(rootEntryPath.length());

                if (AntPathMatcher.match(subPattern, relativePath)) {
                    if (relativePath.startsWith("/")) {
                        relativePath = relativePath.substring(1);
                    }
                    result.add(new URL(rootDirResource, relativePath));
                }
            }
        }
        return result;
    } catch (final IOException e) {
        LOGGER.log(Level.ERROR, "parse the JarFile error", e);
    } finally {
        // Close jar file, but only if freshly obtained -
        // not from JarURLConnection, which might cache the file reference.
        if (newJarFile) {
            try {
                jarFile.close();
            } catch (final IOException e) {
                LOGGER.log(Level.WARN, " occur error when closing jarFile", e);
            }
        }
    }
    return result;
}

From source file:com.twosigma.beakerx.autocomplete.ClasspathScanner.java

private boolean findClasses(File root, File file, boolean includeJars) {
    if (file != null && file.isDirectory()) {
        File[] lf = file.listFiles();
        if (lf != null)
            for (File child : lf) {
                if (!findClasses(root, child, includeJars)) {
                    return false;
                }//from   w ww .  ja  va  2  s .  c om
            }
    } else {
        if (file.getName().toLowerCase().endsWith(".jar") && includeJars) {
            JarFile jar = null;
            try {
                jar = new JarFile(file);
            } catch (Exception ex) {
            }
            if (jar != null) {
                try {
                    Manifest mf = jar.getManifest();
                    if (mf != null) {
                        String cp = mf.getMainAttributes().getValue("Class-Path");
                        if (StringUtils.isNotEmpty(cp)) {
                            for (String fn : cp.split(" ")) {
                                if (!fn.equals(".")) {
                                    File child = new File(
                                            file.getParent() + System.getProperty("file.separator") + fn);
                                    if (child.getAbsolutePath().equals(jar.getName())) {
                                        continue; //skip bad jars, that contain references to themselves in MANIFEST.MF
                                    }
                                    if (child.exists()) {
                                        if (!findClasses(root, child, includeJars)) {
                                            return false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                }

                Enumeration<JarEntry> entries = jar.entries();
                while (entries.hasMoreElements()) {
                    JarEntry entry = entries.nextElement();
                    String name = entry.getName();
                    int extIndex = name.lastIndexOf(".class");
                    if (extIndex > 0 && !name.contains("$")) {
                        String cname = name.substring(0, extIndex).replace("/", ".");
                        int pIndex = cname.lastIndexOf('.');
                        if (pIndex > 0) {
                            String pname = cname.substring(0, pIndex);
                            cname = cname.substring(pIndex + 1);
                            if (!packages.containsKey(pname))
                                packages.put(pname, new ArrayList<String>());
                            packages.get(pname).add(cname);
                        }
                    }
                }
            }
        } else if (file.getName().toLowerCase().endsWith(".class")) {
            String cname = createClassName(root, file);
            if (!cname.contains("$")) {
                int pIndex = cname.lastIndexOf('.');
                if (pIndex > 0) {
                    String pname = cname.substring(0, pIndex + 1);
                    cname = cname.substring(pIndex);
                    if (!packages.containsKey(pname))
                        packages.put(pname, new ArrayList<String>());
                    packages.get(pname).add(cname);
                }
            }
        } else {
            examineFile(root, file);
        }
    }

    return true;
}

From source file:org.springfield.lou.application.ApplicationManager.java

private void processRemoteWar(File warfile, String wantedname, String datestring) {
    // lets first check some vitals to check what it is
    String warfilename = warfile.getName();
    if (warfilename.startsWith("smt_") && warfilename.endsWith("app.war")) {
        // ok so filename checks out is smt_[name]app.war format
        String appname = warfilename.substring(4, warfilename.length() - 7);
        if (wantedname.equals(appname)) {
            // ok found file is the wanted file
            // format "29-Aug-2013-16:55"
            System.out.println("NEW VERSION OF " + appname + " FOUND INSTALLING");

            String writedir = "/springfield/lou/apps/" + appname + "/" + datestring;

            // make all the dirs we need
            File md = new File(writedir);
            md.mkdirs();// www.ja  v a  2  s  . com
            md = new File(writedir + "/war");
            md.mkdirs();
            md = new File(writedir + "/jar");
            md.mkdirs();
            md = new File(writedir + "/components");
            md.mkdirs();
            md = new File(writedir + "/css");
            md.mkdirs();
            md = new File(writedir + "/libs");
            md.mkdirs();

            try {
                JarFile war = new JarFile(warfile);

                // ok lets first find the jar file !
                JarEntry entry = war.getJarEntry("WEB-INF/lib/smt_" + appname + "app.jar");
                if (entry != null) {
                    byte[] bytes = readJarEntryToBytes(war.getInputStream(entry));
                    writeBytesToFile(bytes, writedir + "/jar/smt_" + appname + "app.jar");
                }
                // unpack all in eddie dir
                Enumeration<JarEntry> iter = war.entries();
                while (iter.hasMoreElements()) {
                    JarEntry lentry = iter.nextElement();
                    //System.out.println("LI="+lentry.getName());
                    String lname = lentry.getName();
                    if (!lname.endsWith("/")) {
                        int pos = lname.indexOf("/" + appname + "/");
                        if (pos != -1) {
                            String nname = lname.substring(pos + appname.length() + 2);
                            String dname = nname.substring(0, nname.lastIndexOf('/'));
                            File de = new File(writedir + "/" + dname);
                            de.mkdirs();
                            byte[] bytes = readJarEntryToBytes(war.getInputStream(lentry));
                            writeBytesToFile(bytes, writedir + "/" + nname);
                        }
                    }
                }
                war.close();
                File ren = new File("/springfield/lou/uploaddir/" + warfilename);
                File nen = new File(writedir + "/war/smt_" + appname + "app.war");
                ren.renameTo(nen);

                // lets tell set the available variable to tell the others we have it.

                FsNode unode = Fs
                        .getNode("/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring);
                if (unode != null) {
                    String warlist = unode.getProperty("waravailableat");
                    if (warlist == null || warlist.equals("")) {
                        Fs.setProperty(
                                "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring,
                                "waravailableat", LazyHomer.myip);
                    } else {
                        Fs.setProperty(
                                "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring,
                                "waravailableat", warlist + "," + LazyHomer.myip);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.springfield.lou.application.ApplicationManager.java

private void processUploadedWar(File warfile, String wantedname) {
    // lets first check some vitals to check what it is
    String warfilename = warfile.getName();
    if (warfilename.startsWith("smt_") && warfilename.endsWith("app.war")) {
        // ok so filename checks out is smt_[name]app.war format
        String appname = warfilename.substring(4, warfilename.length() - 7);
        if (wantedname.equals(appname)) {
            // ok found file is the wanted file
            // format "29-Aug-2013-16:55"
            System.out.println("NEW VERSION OF " + appname + " FOUND INSTALLING");
            Date now = new Date();
            SimpleDateFormat df = new SimpleDateFormat("d-MMM-yyyy-HH:mm");
            String datestring = df.format(now);
            String writedir = "/springfield/lou/apps/" + appname + "/" + datestring;

            // create the node
            Html5AvailableApplication vapp = getAvailableApplication(appname);
            String newbody = "<fsxml><properties></properties></fsxml>";

            ServiceInterface smithers = ServiceManager.getService("smithers");
            if (smithers == null)
                return;
            FsNode tnode = Fs.getNode("/domain/internal/service/lou/apps/" + appname);
            if (tnode == null) {
                smithers.put("/domain/internal/service/lou/apps/" + appname + "/properties", newbody,
                        "text/xml");
            }/*from   w  w w.  jav  a  2s  .  c om*/
            smithers.put(
                    "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring + "/properties",
                    newbody, "text/xml");

            // make all the dirs we need
            File md = new File(writedir);
            md.mkdirs();
            md = new File(writedir + "/war");
            md.mkdirs();
            md = new File(writedir + "/jar");
            md.mkdirs();
            md = new File(writedir + "/components");
            md.mkdirs();
            md = new File(writedir + "/css");
            md.mkdirs();
            md = new File(writedir + "/libs");
            md.mkdirs();

            try {
                JarFile war = new JarFile(warfile);

                // ok lets first find the jar file !
                JarEntry entry = war.getJarEntry("WEB-INF/lib/smt_" + appname + "app.jar");
                if (entry != null) {
                    byte[] bytes = readJarEntryToBytes(war.getInputStream(entry));
                    writeBytesToFile(bytes, writedir + "/jar/smt_" + appname + "app.jar");
                }
                // unpack all in eddie dir
                Enumeration<JarEntry> iter = war.entries();
                while (iter.hasMoreElements()) {
                    JarEntry lentry = iter.nextElement();
                    //System.out.println("LI="+lentry.getName());
                    String lname = lentry.getName();
                    if (!lname.endsWith("/")) {
                        int pos = lname.indexOf("/" + appname + "/");
                        if (pos != -1) {
                            String nname = lname.substring(pos + appname.length() + 2);
                            String dname = nname.substring(0, nname.lastIndexOf('/'));
                            File de = new File(writedir + "/" + dname);
                            de.mkdirs();
                            byte[] bytes = readJarEntryToBytes(war.getInputStream(lentry));
                            writeBytesToFile(bytes, writedir + "/" + nname);
                        }
                    }
                }
                war.close();
                File ren = new File("/springfield/lou/uploaddir/" + warfilename);
                File nen = new File(writedir + "/war/smt_" + appname + "app.war");
                //System.out.println("REN="+warfilename);
                //System.out.println("REN="+writedir+"/war/smt_"+appname+"app.war");
                ren.renameTo(nen);

                loadAvailableApps();
                // should we make in development or production based on autodeploy ?
                vapp = getAvailableApplication(appname);
                if (vapp != null) {
                    String mode = vapp.getAutoDeploy();
                    if (appname.equals("dashboard")) {
                        mode = "development/production";
                    }
                    System.out.println("APPNAME=" + appname + " mode=" + mode);
                    if (mode.equals("production")) {
                        makeProduction(appname, datestring);
                    } else if (mode.equals("development")) {
                        makeDevelopment(appname, datestring);
                    } else if (mode.equals("development/production")) {
                        makeDevelopment(appname, datestring);
                        makeProduction(appname, datestring);
                    }
                }

                /*
                Html5ApplicationInterface app = getApplication("/domain/webtv/html5application/dashboard");
                if (app!=null) {
                 DashboardApplication dapp = (DashboardApplication)app;
                 dapp.newApplicationFound(appname);
                }
                */

                // lets tell set the available variable to tell the others we have it.
                FsNode unode = Fs
                        .getNode("/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring);
                if (unode != null) {
                    String warlist = unode.getProperty("waravailableat");
                    if (warlist == null || warlist.equals("")) {
                        Fs.setProperty(
                                "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring,
                                "waravailableat", LazyHomer.myip);
                    } else {
                        System.out.println("BUG ? Already available war " + warlist + " a=" + appname);
                    }
                }
            } catch (Exception e) {
                System.out.println("VERSION NOT READY STILL UPLOADING? RETRY WILL HAPPEN SOON");
            }
        }
    }
}

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

private int countEntries(JarFile jar) {
    int count = 0;
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        count++;/*from  w  w w.j  av a  2s. c  o m*/
        entries.nextElement();
    }
    return count;
}

From source file:ca.weblite.xmlvm.XMLVM.java

/**
 * Finds all of the classes from a given collection of class names that reside in a 
 * given path.  It also copies the found classes into a specified destination directory.
 * @param p The path to search.//from  w  w  w  .  j av a 2 s  .c om
 * @param classNames The class names to search for.
 * @param found The class names that were found in that path.
 * @param destDir The directory where found classes will be copied to.
 * @throws IOException 
 */
public void findClassesInPath(Path p, Collection<String> classNames, Set<String> found, File destDir)
        throws IOException {
    for (String part : p.list()) {
        File f = new File(part);
        if (f.isDirectory()) {
            // We have a directory
            findClassesInPath(f, f, classNames, found, destDir);
        } else if (f.getName().endsWith(".jar")) {
            // We have a jar file
            JarFile jf = new JarFile(f);
            Enumeration<JarEntry> entries = jf.entries();

            Expand expand = (Expand) getProject().createTask("unzip");
            expand.setSrc(f);
            expand.setDest(destDir);
            boolean emptySet = true;

            while (entries.hasMoreElements()) {
                JarEntry nex = entries.nextElement();
                if (nex.getName().endsWith(".class")) {
                    String foundClassName = nex.getName().replaceAll("/", ".").replaceAll("\\.class$", "");
                    if (classNames.contains(foundClassName) && !found.contains(foundClassName)) {
                        found.add(foundClassName);
                        FilenameSelector sel = new FilenameSelector();
                        sel.setName(nex.getName());
                        ZipFileSet fs = new ZipFileSet();
                        fs.setFullpath(nex.getName());
                        expand.addFileset(fs);
                        emptySet = false;
                    }
                }
            }

            if (!emptySet) {
                expand.execute();
            }

        }
    }
}