2 * This file is part of the LibreOffice project.
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 * This file incorporates work covered by the following license notice:
10 * Licensed to the Apache Software Foundation (ASF) under one or more
11 * contributor license agreements. See the NOTICE file distributed
12 * with this work for additional information regarding copyright
13 * ownership. The ASF licenses this file to you under the Apache
14 * License, Version 2.0 (the "License"); you may not use this file
15 * except in compliance with the License. You may obtain a copy of
16 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18 package com
.sun
.star
.lib
.util
;
21 import java
.io
.UnsupportedEncodingException
;
23 import java
.net
.URISyntaxException
;
25 import java
.net
.URLEncoder
;
28 * Maps Java URL representations to File representations, on any Java version.
30 * This used to be used to do URL to File mapping in pre-Java1.4 days, but since
31 * we now require Java 1.5, it is largely unnecessary.
35 public final class UrlToFileMapper
{
38 * Maps Java URL representations to File representations.
40 * @param url some URL, possibly null.
41 * @return a corresponding File, or null on failure.
43 public static File
mapUrlToFile(URL url
) {
48 // where encodedUrl is url.toString(), but since that may contain
49 // unsafe characters (e.g., space, " "), it is encoded, as otherwise
50 // the URI constructor might throw java.net.URISyntaxException (in
51 // Java 1.5, URL.toURI might be used instead).
52 String encodedUrl
= encode(url
.toString());
53 URI uri
= new URI(encodedUrl
);
56 } catch (IllegalArgumentException e
) {
59 } catch (URISyntaxException ex
) {
60 throw new RuntimeException(ex
); // should never happen
65 private static String
encode(String url
) {
66 StringBuffer buf
= new StringBuffer(url
.length());
67 for (int i
= 0; i
< url
.length(); ++i
) {
68 char c
= url
.charAt(i
);
69 // The RFC 2732 <uric> characters: !$&'()*+,-./:;=?@[]_~ plus digits
70 // and letters; additionally, do not encode % again.
71 if (c
>= 'a' && c
<= 'z' || c
>= '?' && c
<= '['
72 || c
>= '$' && c
<= ';' || c
== '!' || c
== '=' || c
== ']'
73 || c
== '_' || c
== '~')
76 } else if (c
== ' ') {
80 String enc
= URLEncoder
.encode(Character
.toString(c
), "UTF-8");
82 } catch (UnsupportedEncodingException e
) {
83 throw new RuntimeException(e
); // should never happen
87 return buf
.toString();
90 private UrlToFileMapper() {}