1 package org.apache.maven.wagon.tck.http.util;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.File;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.OutputStream;
27 import java.net.URISyntaxException;
28 import java.net.URL;
29 import java.util.Enumeration;
30 import java.util.HashMap;
31 import java.util.Map;
32 import java.util.jar.JarEntry;
33 import java.util.jar.JarFile;
34
35 import org.apache.log4j.Logger;
36 import org.codehaus.plexus.util.IOUtil;
37
38 public final class TestUtil
39 {
40 private static Logger logger = Logger.getLogger( TestUtil.class );
41
42 private static final Map<String, File> bases = new HashMap<String, File>();
43
44 private TestUtil()
45 {
46 }
47
48 public static File getResource( final String path )
49 throws URISyntaxException, IOException
50 {
51 URL resource = Thread.currentThread().getContextClassLoader().getResource( path );
52 if ( resource == null )
53 {
54 throw new IllegalStateException( "Cannot find classpath resource: " + path );
55 }
56
57 if ( resource.getProtocol().startsWith( "jar" ) )
58 {
59
60
61
62 String url = resource.toExternalForm();
63 int startIdx = url.lastIndexOf( ':' ) + 1;
64 int endIdx = url.indexOf( "!" );
65 url = url.substring( startIdx, endIdx );
66
67 File base = bases.get( url );
68 if ( base == null )
69 {
70 File urlFile = new File( url );
71
72 base = new File( "target/tck-resources/" + urlFile.getName() );
73 base.getParentFile().mkdirs();
74
75 logger.info( "unpacking test resources in jar: " + url );
76 JarFile jf = null;
77 try
78 {
79 jf = new JarFile( urlFile );
80
81 InputStream in = null;
82 OutputStream out = null;
83
84 for ( Enumeration<JarEntry> en = jf.entries(); en.hasMoreElements(); )
85 {
86 JarEntry je = en.nextElement();
87 File target = new File( base, je.getName() ).getAbsoluteFile();
88 if ( je.isDirectory() )
89 {
90 target.mkdirs();
91 }
92 else
93 {
94 target.getParentFile().mkdirs();
95
96 try
97 {
98 in = jf.getInputStream( je );
99 out = new FileOutputStream( target );
100
101 IOUtil.copy( in, out );
102 }
103 finally
104 {
105 IOUtil.close( in );
106 IOUtil.close( out );
107 }
108 }
109 }
110
111 bases.put( url, base );
112 }
113 finally
114 {
115 if ( jf != null )
116 {
117 try
118 {
119 jf.close();
120 }
121 catch ( Exception e )
122 {
123 }
124 }
125 }
126 }
127
128 return new File( base, path );
129 }
130 else
131 {
132 return new File( resource.toURI().normalize() );
133 }
134 }
135
136 }