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
39
40
41 public final class TestUtil
42 {
43 private static final Logger LOGGER = Logger.getLogger( TestUtil.class );
44
45 private static final Map<String, File> BASES = new HashMap<String, File>();
46
47 private TestUtil()
48 {
49 }
50
51 public static File getResource( final String path )
52 throws URISyntaxException, IOException
53 {
54 URL resource = Thread.currentThread().getContextClassLoader().getResource( path );
55 if ( resource == null )
56 {
57 throw new IllegalStateException( "Cannot find classpath resource: " + path );
58 }
59
60 if ( resource.getProtocol().startsWith( "jar" ) )
61 {
62
63
64
65 String url = resource.toExternalForm();
66 int startIdx = url.lastIndexOf( ':' ) + 1;
67 int endIdx = url.indexOf( "!" );
68 url = url.substring( startIdx, endIdx );
69
70 File base = BASES.get( url );
71 if ( base == null )
72 {
73 File urlFile = new File( url );
74
75 base = new File( "target/tck-resources/" + urlFile.getName() );
76 base.getParentFile().mkdirs();
77
78 LOGGER.info( "unpacking test resources in jar: " + url );
79 JarFile jf = null;
80 try
81 {
82 jf = new JarFile( urlFile );
83
84 InputStream in = null;
85 OutputStream out = null;
86
87 for ( Enumeration<JarEntry> en = jf.entries(); en.hasMoreElements(); )
88 {
89 JarEntry je = en.nextElement();
90 File target = new File( base, je.getName() ).getAbsoluteFile();
91 if ( je.isDirectory() )
92 {
93 target.mkdirs();
94 }
95 else
96 {
97 target.getParentFile().mkdirs();
98
99 try
100 {
101 in = jf.getInputStream( je );
102 out = new FileOutputStream( target );
103
104 IOUtil.copy( in, out );
105 }
106 finally
107 {
108 IOUtil.close( in );
109 IOUtil.close( out );
110 }
111 }
112 }
113
114 BASES.put( url, base );
115 }
116 finally
117 {
118 if ( jf != null )
119 {
120 try
121 {
122 jf.close();
123 }
124 catch ( Exception e )
125 {
126
127 }
128 }
129 }
130 }
131
132 return new File( base, path );
133 }
134 else
135 {
136 return new File( resource.toURI().normalize() );
137 }
138 }
139
140 }