1 /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
19 package com
.sun
.star
.lib
.util
;
22 import java
.io
.UnsupportedEncodingException
;
24 import java
.net
.URISyntaxException
;
26 import java
.net
.URLEncoder
;
29 * Maps Java URL representations to File representations, on any Java version.
31 * This used to be used to do URL to File mapping in pre-Java1.4 days, but since
32 * we now require Java 1.5, it is largely unnecessary.
36 public final class UrlToFileMapper
{
39 * Maps Java URL representations to File representations.
41 * @param url some URL, possibly null.
42 * @return a corresponding File, or null on failure.
44 public static File
mapUrlToFile(URL url
) {
49 // where encodedUrl is url.toString(), but since that may contain
50 // unsafe characters (e.g., space, " "), it is encoded, as otherwise
51 // the URI constructor might throw java.net.URISyntaxException (in
52 // Java 1.5, URL.toURI might be used instead).
53 String encodedUrl
= encode(url
.toString());
54 URI uri
= new URI(encodedUrl
);
57 } catch (IllegalArgumentException e
) {
60 } catch (URISyntaxException ex
) {
61 throw new RuntimeException(ex
); // should never happen
66 private static String
encode(String url
) {
67 StringBuffer buf
= new StringBuffer(url
.length());
68 for (int i
= 0; i
< url
.length(); ++i
) {
69 char c
= url
.charAt(i
);
70 // The RFC 2732 <uric> characters: !$&'()*+,-./:;=?@[]_~ plus digits
71 // and letters; additionally, do not encode % again.
72 if (c
>= 'a' && c
<= 'z' || c
>= '?' && c
<= '['
73 || c
>= '$' && c
<= ';' || c
== '!' || c
== '=' || c
== ']'
74 || c
== '_' || c
== '~')
77 } else if (c
== ' ') {
81 String enc
= URLEncoder
.encode(Character
.toString(c
), "UTF-8");
83 } catch (UnsupportedEncodingException e
) {
84 throw new RuntimeException(e
); // should never happen
88 return buf
.toString();
91 private UrlToFileMapper() {}
94 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */