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.io.File;
20  import java.net.URL;
21  
22  import org.apache.maven.artifact.Artifact;
23  import org.apache.maven.artifact.DefaultArtifact;
24  import org.apache.maven.artifact.factory.ArtifactFactory;
25  import org.codehaus.plexus.PlexusTestCase;
26  
27  import junit.framework.TestCase;
28  
29  /**
30   * @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
31   */
32  public class IsolatedClassLoaderTest
33      extends PlexusTestCase
34  {
35  
36      private ArtifactFactory artifactFactory;
37  
38      protected void setUp()
39          throws Exception
40      {
41          super.setUp();
42          artifactFactory = (ArtifactFactory) lookup( ArtifactFactory.class.getName() );
43      }
44  
45      /**
46       * Ensure a class can be loaded in isolation based on an artifact
47       */
48      public void testLoadClassInIsolation()
49          throws Exception
50      {
51          // Create an artifact for junit.jar
52          Artifact artifact =
53              artifactFactory.createArtifact( "junit", "junit", "3.8.2", DefaultArtifact.SCOPE_TEST,
54                  "jar" );
55          // locate junit.jar based on current loader class
56          URL url = getClass().getClassLoader().getResource( "junit/framework/TestCase.class" );
57          String path = url.toString();
58          assertTrue( "junit TestCase class is not loaded from a jar", path.startsWith( "jar:" ) );
59          int i = path.indexOf( '!' );
60          url = new URL( path.substring( 4, i ) );
61  
62          // setup the isolated classloader
63          artifact.setFile( new File( url.getFile() ) );
64          ClassLoader cl = new IsolatedClassLoader( artifact, this.getClassLoader() );
65  
66          Class isolated = cl.loadClass( "junit.framework.TestCase" );
67          assertNotNull( "failed to load TestCase class in isolation", isolated );
68          assertTrue( "TestCase loaded, but not in isolation", isolated != TestCase.class );
69      }
70  }