View Javadoc

1   package org.codehaus.mojo.javascript.compress;
2   
3   /*
4    * Copyright 2001-2005 The Apache Software 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.net.MalformedURLException;
20  import java.net.URL;
21  import java.net.URLClassLoader;
22  import java.util.Collection;
23  import java.util.Iterator;
24  
25  import org.apache.maven.artifact.Artifact;
26  
27  /**
28   * @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
29   */
30  public class IsolatedClassLoader
31      extends URLClassLoader
32  {
33  
34      public IsolatedClassLoader( Artifact artifact, ClassLoader parent )
35      {
36          super( getArtifactURLs( artifact ), parent );
37      }
38  
39      public IsolatedClassLoader( Collection artifacts, ClassLoader parent )
40      {
41          super( getArtifactURLs( artifacts ), parent );
42      }
43  
44      private static URL[] getArtifactURLs( Collection artifacts )
45      {
46          URL[] urls = new URL[artifacts.size()];
47          try
48          {
49              int i = 0;
50              for ( Iterator iterator = artifacts.iterator(); iterator.hasNext(); )
51              {
52                  Artifact artifact = (Artifact) iterator.next();
53                  urls[i++] = artifact.getFile().toURL();
54              }
55          }
56          catch ( MalformedURLException e )
57          {
58              return null;
59          }
60          return urls;
61      }
62  
63      private static URL[] getArtifactURLs( Artifact artifact )
64      {
65          URL url;
66          try
67          {
68              url = artifact.getFile().toURL();
69              return new URL[] { url };
70          }
71          catch ( MalformedURLException e )
72          {
73              return null;
74          }
75      }
76  
77      public Class loadClass( String name )
78          throws ClassNotFoundException
79      {
80          Class c = findLoadedClass( name );
81          if ( c == null )
82          {
83              try
84              {
85                  return findClass( name );
86              }
87              catch ( ClassNotFoundException e )
88              {
89                  return super.loadClass( name );
90              }
91          }
92          return super.loadClass( name );
93      }
94  
95  }