Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2002-2003,2009 The Apache Software Foundation.
   * 
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   * 
   *      http://www.apache.org/licenses/LICENSE-2.0
   * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package cn.wensiqun.utils;
 
 
 import java.io.File;
 import java.net.URL;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 
Use with ClassFinder to filter the Urls to be scanned, example:
 UrlSet urlSet = new UrlSet(classLoader);
 urlSet = urlSet.exclude(ClassLoader.getSystemClassLoader().getParent());
 urlSet = urlSet.excludeJavaExtDirs();
 urlSet = urlSet.excludeJavaEndorsedDirs();
 urlSet = urlSet.excludeJavaHome();
 urlSet = urlSet.excludePaths(System.getProperty("sun.boot.class.path", ""));
 urlSet = urlSet.exclude(".*?/JavaVM.framework/.*");
 urlSet = urlSet.exclude(".*?/activemq-(core|ra)-[\\d.]+.jar(!/)?");
 

Author(s):
David Blevins
Version:
$Rev: 1331373 $ $Date: 2012-04-27 14:12:03 +0200 (Fri, 27 Apr 2012) $
 
 public class UrlSet {
     private static final Log LOG = LogFactory.getLog(UrlSet.class);
     private final Map<String,URLurls;
     private Set<Stringprotocols;
     
 
     public UrlSet(ClassLoaderInterface classLoaderthrows IOException {
         this(getUrls(classLoader));
     }
 
     public UrlSet(ClassLoaderInterface classLoaderSet<Stringprotocolsthrows IOException {
         this(getUrls(classLoaderprotocols));
         this. = protocols;
     }
 
     public UrlSet(URL... urls){
         this(Arrays.asList(urls));
     }
    
Ignores all URLs that are not "jar" or "file"

Parameters:
urls
 
     public UrlSet(Collection<URLurls){
         this. = new HashMap<String,URL>();
         for (URL location : urls) {
             try {
 //                if (location.getProtocol().equals("file")) {
 //                    try {
 //                        // See if it's actually a jar
 //                        URL jarUrl = new URL("jar", "", location.toExternalForm() + "!/");
 //                        JarURLConnection juc = (JarURLConnection) jarUrl.openConnection();
 //                        juc.getJarFile();
 //                        location = jarUrl;
 //                    } catch (IOException e) {
 //                    }
 //                    this.urls.put(location.toExternalForm(), location);
 //                }
                 this..put(location.toExternalForm(), location);
             } catch (Exception e) {
                 e.printStackTrace();
             }
         }
     }
 
     private UrlSet(Map<StringURLurls) {
        this. = urls;
    }
    public UrlSet include(UrlSet urlSet){
        Map<StringURLurls = new HashMap<StringURL>(this.);
        urls.putAll(urlSet.urls);
        return new UrlSet(urls);
    }
    public UrlSet exclude(UrlSet urlSet) {
        Map<StringURLurls = new HashMap<StringURL>(this.);
        Map<StringURLparentUrls = urlSet.urls;
        for (String url : parentUrls.keySet()) {
            urls.remove(url);
        }
        return new UrlSet(urls);
    }
    public UrlSet exclude(ClassLoaderInterface parentthrows IOException {
        return exclude(new UrlSet(parentthis.));
    }
    public UrlSet exclude(File filethrows MalformedURLException {
        return exclude(relative(file));
    }
    public UrlSet exclude(String patternthrows MalformedURLException {
        return exclude(matching(pattern));
    }

    
Calls excludePaths(System.getProperty("java.ext.dirs"))

    public UrlSet excludeJavaExtDirs() throws MalformedURLException {
        return excludePaths(System.getProperty("java.ext.dirs"""));
    }

    
Calls excludePaths(System.getProperty("java.endorsed.dirs"))

        return excludePaths(System.getProperty("java.endorsed.dirs"""));
    }
    public UrlSet excludeJavaHome() throws MalformedURLException {
        String path = System.getProperty("java.home");
        if (path != null) {
            File java = new File(path);
            if (path.matches("/System/Library/Frameworks/JavaVM.framework/Versions/[^/]+/Home")){
                java = java.getParentFile();
            }
            return exclude(java);
        } else {
            return this;
        }
    }
    public UrlSet excludePaths(String pathStringthrows MalformedURLException {
        String[] paths = pathString.split(.);
        UrlSet urlSet = this;
        for (String path : paths) {
            if (StringUtils.isNotEmpty(path)) {
                File file = new File(path);
                urlSet = urlSet.exclude(file);
            }
        }
        return urlSet;
    }
    public UrlSet matching(String pattern) {
        Map<StringURLurls = new HashMap<StringURL>();
        for (Map.Entry<StringURLentry : this..entrySet()) {
            String url = entry.getKey();
            if (url.matches(pattern)){
                urls.put(urlentry.getValue());
            }
        }
        return new UrlSet(urls);
    }

    
Try to find a classes directory inside a war file add its normalized url to this set
    public UrlSet includeClassesUrl(ClassLoaderInterface classLoaderInterfacethrows IOException {
        Enumeration<URLrootUrlEnumeration = classLoaderInterface.getResources("");
        while (rootUrlEnumeration.hasMoreElements()) {
            URL url = rootUrlEnumeration.nextElement();
            String externalForm = StringUtils.removeEnd(url.toExternalForm(), "/");
            if (externalForm.endsWith(".war/WEB-INF/classes")) {
                //if it is inside a war file, get the url to the file
                externalForm = StringUtils.substringBefore(externalForm"/WEB-INF/classes");
                URL warUrl = new URL(externalForm);
                URL normalizedUrl = URLUtil.normalizeToFileProtocol(warUrl);
                URL finalUrl = (URL) ObjectUtils.defaultIfNull(normalizedUrlwarUrl);
                Map<StringURLnewUrls = new HashMap<StringURL>(this.);
                if ("jar".equals(finalUrl.getProtocol()) || "file".equals(finalUrl.getProtocol())) {
                    newUrls.put(finalUrl.toExternalForm(), finalUrl);
                }
                return new UrlSet(newUrls);
            }
        }
        return this;
    }
    public UrlSet relative(File filethrows MalformedURLException {
        String urlPath = file.toURL().toExternalForm();
        Map<StringURLurls = new HashMap<StringURL>();
        for (Map.Entry<StringURLentry : this..entrySet()) {
            String url = entry.getKey();
            if (url.startsWith(urlPath) || url.startsWith("jar:"+urlPath)){
                urls.put(urlentry.getValue());
            }
        }
        return new UrlSet(urls);
    }
    public List<URLgetUrls() {
        return new ArrayList<URL>(.values());
    }
    private static List<URLgetUrls(ClassLoaderInterface classLoaderthrows IOException {
        List<URLlist = new ArrayList<URL>();
        //find jars
        ArrayList<URLurls = Collections.list(classLoader.getResources("META-INF"));
        for (URL url : urls) {
            if ("jar".equalsIgnoreCase(url.getProtocol())) {
                String externalForm = url.toExternalForm();
                //build a URL pointing to the jar, instead of the META-INF dir
                url = new URL(StringUtils.substringBefore(externalForm"META-INF"));
                list.add(url);
            } else if (.isDebugEnabled())
                .debug("Ignoring URL [" + url.toExternalForm() + "] because it is not a jar");
        }
        //usually the "classes" dir
        list.addAll(Collections.list(classLoader.getResources("")));
        return list;
    }
    private static List<URLgetUrls(ClassLoaderInterface classLoaderSet<Stringprotocolsthrows IOException {
        if (protocols == null) {
            return getUrls(classLoader);
        }
        List<URLlist = new ArrayList<URL>();
        //find jars
        ArrayList<URLurls = Collections.list(classLoader.getResources("META-INF"));
        for (URL url : urls) {
            if (protocols.contains(url.getProtocol())) {
                String externalForm = url.toExternalForm();
                //build a URL pointing to the jar, instead of the META-INF dir
                url = new URL(StringUtils.substringBefore(externalForm"META-INF"));
                list.add(url);
            } else if (.isDebugEnabled())
                .debug("Ignoring URL [" + url.toExternalForm() + "] because it is not a valid protocol");
        }
        // Usually the "classes" dir.
        ArrayList<URLclassesList = Collections.list(classLoader.getResources(""));
        for (URL url : classesList) {
            if (URLUtil.isJBossUrl(url)) {
                list.addAll(URLUtil.getAllJBossPhysicalUrls(url));
            } else {
                list.add(url);
            }
        }
        return list;
    }
New to GrepCode? Check out our FAQ X