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  
32      public static Set<ClassRealm> getContextRealms( ClassWorld world )
33      {
34          Set<ClassRealm> realms = new LinkedHashSet<ClassRealm>();
35  
36          for ( ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); classLoader != null; classLoader =
37              classLoader.getParent() )
38          {
39              if ( classLoader instanceof ClassRealm )
40              {
41                  realms.add( (ClassRealm) classLoader );
42  
43                  Queue<ClassRealm> queue = new LinkedList<ClassRealm>();
44                  queue.add( (ClassRealm) classLoader );
45  
46                  while ( !queue.isEmpty() )
47                  {
48                      ClassRealm realm = queue.remove();
49  
50                      Collection<ClassRealm> importRealms = realm.getImportRealms();
51                      for ( ClassRealm importRealm : importRealms )
52                      {
53                          if ( realms.add( importRealm ) )
54                          {
55                              queue.add( importRealm );
56                          }
57                      }
58  
59                      ClassRealm parentRealm = realm.getParentRealm();
60                      if ( parentRealm != null && realms.add( parentRealm ) )
61                      {
62                          queue.add( parentRealm );
63                      }
64                  }
65              }
66          }
67  
68          if ( world != null )
69          {
70              for ( Iterator<ClassRealm> it = realms.iterator(); it.hasNext(); )
71              {
72                  ClassRealm realm = it.next();
73                  if ( realm.getWorld() != world )
74                  {
75                      it.remove();
76                  }
77              }
78          }
79  
80          return realms;
81      }
82  
83  }