1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 package com.sun.star.lib.util;
24 
25 import java.io.File;
26 import java.lang.reflect.Constructor;
27 import java.lang.reflect.InvocationTargetException;
28 import java.lang.reflect.Method;
29 import java.net.URL;
30 import java.net.URLDecoder;
31 import java.net.URLEncoder;
32 
33 /**
34  * Maps Java URL representations to File representations, on any Java version.
35  *
36  * @since UDK 3.2.8
37  */
38 public final class UrlToFileMapper {
39 
40     // java.net.URLEncoder.encode(String, String) and java.net.URI are only
41     // available since Java 1.4:
42     private static Method urlEncoderEncode;
43     private static Constructor uriConstructor;
44     private static Constructor fileConstructor;
45     static {
46         try {
47             urlEncoderEncode = URLEncoder.class.getMethod(
48                 "encode", new Class[] { String.class, String.class });
49             Class uriClass = Class.forName("java.net.URI");
50             uriConstructor = uriClass.getConstructor(
51                 new Class[] { String.class });
52             fileConstructor = File.class.getConstructor(
53                 new Class[] { uriClass });
54         } catch (ClassNotFoundException e) {
55         } catch (NoSuchMethodException e) {
56         }
57     }
58 
59     /**
60      * Maps Java URL representations to File representations.
61      *
62      * @param url some URL, possibly null.
63      * @return a corresponding File, or null on failure.
64      */
mapUrlToFile(URL url)65     public static File mapUrlToFile(URL url) {
66         if (url == null) {
67             return null;
68         } else if (fileConstructor == null) {
69             // If java.net.URI is not available, hope that the following works
70             // well:  First, check that the given URL has a certain form.
71             // Second, use the URLDecoder to decode the URL path (taking care
72             // not to change any plus signs to spaces), hoping that the used
73             // default encoding is the proper one for file URLs.  Third, create
74             // a File from the decoded path.
75             return url.getProtocol().equalsIgnoreCase("file")
76                 && url.getAuthority() == null && url.getQuery() == null
77                 && url.getRef() == null
78                 ? new File(URLDecoder.decode(
79                                StringHelper.replace(url.getPath(), '+', "%2B")))
80                 : null;
81         } else {
82             // If java.net.URI is avaliable, do
83             //   URI uri = new URI(encodedUrl);
84             //   try {
85             //       return new File(uri);
86             //   } catch (IllegalArgumentException e) {
87             //       return null;
88             //   }
89             // where encodedUrl is url.toString(), but since that may contain
90             // unsafe characters (e.g., space, " "), it is encoded, as otherwise
91             // the URI constructor might throw java.net.URISyntaxException (in
92             // Java 1.5, URL.toURI might be used instead).
93             String encodedUrl = encode(url.toString());
94             try {
95                 Object uri = uriConstructor.newInstance(
96                     new Object[] { encodedUrl });
97                 try {
98                     return (File) fileConstructor.newInstance(
99                         new Object[] { uri });
100                 } catch (InvocationTargetException e) {
101                     if (e.getTargetException() instanceof
102                         IllegalArgumentException) {
103                         return null;
104                     } else {
105                         throw e;
106                     }
107                 }
108             } catch (InstantiationException e) {
109                 throw new RuntimeException("This cannot happen: " + e);
110             } catch (IllegalAccessException e) {
111                 throw new RuntimeException("This cannot happen: " + e);
112             } catch (InvocationTargetException e) {
113                 if (e.getTargetException() instanceof Error) {
114                     throw (Error) e.getTargetException();
115                 } else if (e.getTargetException() instanceof RuntimeException) {
116                     throw (RuntimeException) e.getTargetException();
117                 } else {
118                     throw new RuntimeException("This cannot happen: " + e);
119                 }
120             }
121         }
122     }
123 
124 
125 
encode(String url)126     private static String encode(String url) {
127         StringBuffer buf = new StringBuffer();
128         for (int i = 0; i < url.length(); ++i) {
129             char c = url.charAt(i);
130             // The RFC 2732 <uric> characters: !$&'()*+,-./:;=?@[]_~ plus digits
131             // and letters; additionally, do not encode % again.
132             if (c >= 'a' && c <= 'z' || c >= '?' && c <= '['
133                 || c >= '$' && c <= ';' || c == '!' || c == '=' || c == ']'
134                 || c == '_' || c == '~')
135             {
136                 buf.append(c);
137             } else if (c == ' ') {
138                 buf.append("%20");
139             } else {
140                 String enc;
141                 try {
142                     enc = (String) urlEncoderEncode.invoke(
143                         null,
144                         new Object[] {Character.toString(c), "UTF-8" });
145                 } catch (IllegalAccessException e) {
146                     throw new RuntimeException("This cannot happen: " + e);
147                 } catch (InvocationTargetException e) {
148                     throw new RuntimeException("This cannot happen: " + e);
149                 }
150                 buf.append(enc);
151             }
152         }
153         return buf.toString();
154     }
155 
UrlToFileMapper()156     private UrlToFileMapper() {}
157 }
158