View Javadoc
1   package org.codehaus.plexus;
2   
3   /*
4    * Copyright 2001-2009 Codehaus Foundation.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *      http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  import java.util.Collection;
20  import java.util.Iterator;
21  import java.util.LinkedHashSet;
22  import java.util.LinkedList;
23  import java.util.Queue;
24  import java.util.Set;
25  
26  import org.codehaus.plexus.classworlds.ClassWorld;
27  import org.codehaus.plexus.classworlds.realm.ClassRealm;
28  
29  public class ClassRealmUtil {
30  
31      public static Set<ClassRealm> getContextRealms(ClassWorld world) {
32          Set<ClassRealm> realms = new LinkedHashSet<ClassRealm>();
33  
34          for (ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
35                  classLoader != null;
36                  classLoader = classLoader.getParent()) {
37              if (classLoader instanceof ClassRealm) {
38                  realms.add((ClassRealm) classLoader);
39  
40                  Queue<ClassRealm> queue = new LinkedList<ClassRealm>();
41                  queue.add((ClassRealm) classLoader);
42  
43                  while (!queue.isEmpty()) {
44                      ClassRealm realm = queue.remove();
45  
46                      Collection<ClassRealm> importRealms = realm.getImportRealms();
47                      for (ClassRealm importRealm : importRealms) {
48                          if (realms.add(importRealm)) {
49                              queue.add(importRealm);
50                          }
51                      }
52  
53                      ClassRealm parentRealm = realm.getParentRealm();
54                      if (parentRealm != null && realms.add(parentRealm)) {
55                          queue.add(parentRealm);
56                      }
57                  }
58              }
59          }
60  
61          if (world != null) {
62              for (Iterator<ClassRealm> it = realms.iterator(); it.hasNext(); ) {
63                  ClassRealm realm = it.next();
64                  if (realm.getWorld() != world) {
65                      it.remove();
66                  }
67              }
68          }
69  
70          return realms;
71      }
72  }