1 package org.codehaus.mojo.exec;
2
3 /*
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
20 */
21
22 import java.io.File;
23 import java.io.UnsupportedEncodingException;
24 import java.net.MalformedURLException;
25 import java.net.URL;
26 import java.util.BitSet;
27
28 /**
29 * Utility for dealing with URLs in pre-JDK 1.4.
30 */
31 public final class UrlUtils {
32 private static final BitSet UNRESERVED = new BitSet(Byte.MAX_VALUE - Byte.MIN_VALUE + 1);
33
34 private static final int RADIX = 16;
35
36 private static final int MASK = 0xf;
37
38 private UrlUtils() {
39 }
40
41 private static final String ENCODING = "UTF-8";
42
43 static {
44 try {
45 byte[] bytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'():/"
46 .getBytes(ENCODING);
47 for (int i = 0; i < bytes.length; i++) {
48 UNRESERVED.set(bytes[i]);
49 }
50 } catch (UnsupportedEncodingException e) {
51 // can't happen as UTF-8 must be present
52 }
53 }
54
55 public static URL getURL(File file) throws MalformedURLException {
56 URL url = new URL(file.toURI().toASCIIString());
57 // encode any characters that do not comply with RFC 2396
58 // this is primarily to handle Windows where the user's home directory contains spaces
59 try {
60 byte[] bytes = url.toString().getBytes(ENCODING);
61 StringBuffer buf = new StringBuffer(bytes.length);
62 for (int i = 0; i < bytes.length; i++) {
63 byte b = bytes[i];
64 if (b > 0 && UNRESERVED.get(b)) {
65 buf.append((char) b);
66 } else {
67 buf.append('%');
68 buf.append(Character.forDigit(b >>> 4 & MASK, RADIX));
69 buf.append(Character.forDigit(b & MASK, RADIX));
70 }
71 }
72 return new URL(buf.toString());
73 } catch (UnsupportedEncodingException e) {
74 // should not happen as UTF-8 must be present
75 throw new RuntimeException(e);
76 }
77 }
78 }