View Javadoc
1   package org.apache.maven.surefire.util.internal;
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.net.MalformedURLException;
24  import java.net.URL;
25  import java.util.BitSet;
26  
27  import static org.apache.maven.surefire.util.internal.StringUtils.UTF_8;
28  
29  /**
30   * Utility for dealing with URLs in pre-JDK 1.4.
31   */
32  public final class UrlUtils
33  {
34      private static final BitSet UNRESERVED = new BitSet( Byte.MAX_VALUE - Byte.MIN_VALUE + 1 );
35  
36      private static final int RADIX = 16;
37  
38      private static final int MASK = 0xf;
39  
40      private UrlUtils()
41      {
42          throw new IllegalStateException( "no instantiable constructor" );
43      }
44  
45      static
46      {
47          byte[] bytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'():/".getBytes( UTF_8 );
48          for ( byte aByte : bytes )
49          {
50              UNRESERVED.set( aByte );
51          }
52      }
53  
54      public static URL toURL( File file )
55          throws MalformedURLException
56      {
57          // with JDK 1.4+, code would be: return new URL( file.toURI().toASCIIString() );
58          //noinspection deprecation
59          URL url = file.toURL();
60          // encode any characters that do not comply with RFC 2396
61          // this is primarily to handle Windows where the user's home directory contains spaces
62          byte[] bytes = url.toString().getBytes( UTF_8 );
63          StringBuilder buf = new StringBuilder( bytes.length );
64          for ( byte b : bytes )
65          {
66              if ( b > 0 && UNRESERVED.get( b ) )
67              {
68                  buf.append( (char) b );
69              }
70              else
71              {
72                  buf.append( '%' );
73                  buf.append( Character.forDigit( b >>> 4 & MASK, RADIX ) );
74                  buf.append( Character.forDigit( b & MASK, RADIX ) );
75              }
76          }
77          return new URL( buf.toString() );
78      }
79  }