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