001 package org.codehaus.mojo.exec;
002
003 /*
004 * Licensed to the Apache Software Foundation (ASF) under one
005 * or more contributor license agreements. See the NOTICE file
006 * distributed with this work for additional information
007 * regarding copyright ownership. The ASF licenses this file
008 * to you under the Apache License, Version 2.0 (the
009 * "License"); you may not use this file except in compliance
010 * with the License. You may obtain a copy of the License at
011 *
012 * http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing,
015 * software distributed under the License is distributed on an
016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017 * KIND, either express or implied. See the License for the
018 * specific language governing permissions and limitations
019 * under the License.
020 */
021
022 import java.io.File;
023 import java.io.UnsupportedEncodingException;
024 import java.net.MalformedURLException;
025 import java.net.URL;
026 import java.util.BitSet;
027
028 /**
029 * Utility for dealing with URLs in pre-JDK 1.4.
030 */
031 public final class UrlUtils {
032 private static final BitSet UNRESERVED = new BitSet(Byte.MAX_VALUE - Byte.MIN_VALUE + 1);
033
034 private static final int RADIX = 16;
035
036 private static final int MASK = 0xf;
037
038 private UrlUtils() {
039 }
040
041 private static final String ENCODING = "UTF-8";
042
043 static {
044 try {
045 byte[] bytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'():/"
046 .getBytes(ENCODING);
047 for (int i = 0; i < bytes.length; i++) {
048 UNRESERVED.set(bytes[i]);
049 }
050 } catch (UnsupportedEncodingException e) {
051 // can't happen as UTF-8 must be present
052 }
053 }
054
055 public static URL getURL(File file) throws MalformedURLException {
056 URL url = new URL(file.toURI().toASCIIString());
057 // encode any characters that do not comply with RFC 2396
058 // this is primarily to handle Windows where the user's home directory contains spaces
059 try {
060 byte[] bytes = url.toString().getBytes(ENCODING);
061 StringBuffer buf = new StringBuffer(bytes.length);
062 for (int i = 0; i < bytes.length; i++) {
063 byte b = bytes[i];
064 if (b > 0 && UNRESERVED.get(b)) {
065 buf.append((char) b);
066 } else {
067 buf.append('%');
068 buf.append(Character.forDigit(b >>> 4 & MASK, RADIX));
069 buf.append(Character.forDigit(b & MASK, RADIX));
070 }
071 }
072 return new URL(buf.toString());
073 } catch (UnsupportedEncodingException e) {
074 // should not happen as UTF-8 must be present
075 throw new RuntimeException(e);
076 }
077 }
078 }