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