1 package org.codehaus.mojo.javacc;
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.net.MalformedURLException;
24 import java.net.URL;
25 import java.nio.ByteBuffer;
26 import java.nio.charset.Charset;
27
28
29
30
31
32
33
34 class UrlUtils
35 {
36
37
38
39
40 private static final Charset UTF8 = Charset.forName( "UTF-8" );
41
42
43
44
45 private static final String JAR = "jar:";
46
47
48
49
50 private static final String FILE = "file:";
51
52
53
54
55 private static final String JAR_FILE = JAR + FILE;
56
57
58
59
60
61
62
63
64
65
66
67 public static File getResourceRoot( URL url, String resource )
68 {
69 String path = null;
70 if ( url != null )
71 {
72 String spec = url.toExternalForm();
73 if ( ( JAR_FILE ).regionMatches( true, 0, spec, 0, JAR_FILE.length() ) )
74 {
75 URL jar;
76 try
77 {
78 jar = new URL( spec.substring( JAR.length(), spec.lastIndexOf( "!/" ) ) );
79 }
80 catch ( MalformedURLException e )
81 {
82 throw new IllegalArgumentException( "Invalid JAR URL: " + url + ", " + e.getMessage() );
83 }
84 path = decodeUrl( jar.getPath() );
85 }
86 else if ( FILE.regionMatches( true, 0, spec, 0, FILE.length() ) )
87 {
88 path = decodeUrl( url.getPath() );
89 path = path.substring( 0, path.length() - resource.length() );
90 }
91 else
92 {
93 throw new IllegalArgumentException( "Invalid class path URL: " + url );
94 }
95 }
96 return ( path != null ) ? new File( path ) : null;
97 }
98
99
100
101
102
103
104
105
106
107
108
109 public static String decodeUrl( String url )
110 {
111 String decoded = url;
112 if ( url != null && url.indexOf( '%' ) >= 0 )
113 {
114 int n = url.length();
115 StringBuffer buffer = new StringBuffer();
116 ByteBuffer bytes = ByteBuffer.allocate( n );
117 for ( int i = 0; i < n; )
118 {
119 if ( url.charAt( i ) == '%' )
120 {
121 try
122 {
123 do
124 {
125 byte octet = (byte) Integer.parseInt( url.substring( i + 1, i + 3 ), 16 );
126 bytes.put( octet );
127 i += 3;
128 }
129 while ( i < n && url.charAt( i ) == '%' );
130 continue;
131 }
132 catch ( RuntimeException e )
133 {
134
135 }
136 finally
137 {
138 if ( bytes.position() > 0 )
139 {
140 bytes.flip();
141 buffer.append( UTF8.decode( bytes ).toString() );
142 bytes.clear();
143 }
144 }
145 }
146 buffer.append( url.charAt( i++ ) );
147 }
148 decoded = buffer.toString();
149 }
150 return decoded;
151 }
152
153 }