1 /**
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.xbean.propertyeditor;
18
19 import java.io.File;
20 import java.net.MalformedURLException;
21 import java.net.URL;
22
23 /**
24 * A property editor for URL typed properties.
25 *
26 * @version $Rev: 6680 $
27 */
28 public class URLEditor extends AbstractConverter {
29 public URLEditor() {
30 super(URL.class);
31 }
32
33 /**
34 * Convert the text value of the property into a URL object instance.
35 *
36 * @return a URL object constructed from the property text value.
37 */
38 protected Object toObjectImpl(String text) {
39 try {
40 // try to create directly from the text property.
41 URL url = new URL(text);
42 // this parsed correctly, but if this is a file object,
43 // we need to make sure this gets converted into the proper
44 // absolute directory form.
45 try {
46 if (url.getProtocol().equals("file")) {
47 // ok, this is a file URL, so get the file string portion,
48 // convert that to a file object, then go through the URI()/URL()
49 // conversion sequence to get a fully valid URL().
50 return new File(url.getFile()).toURI().toURL();
51 }
52 } catch (Exception e) {
53 // any error here is returned as a property editor exception.
54 throw new PropertyEditorException(e);
55 }
56
57 return url;
58 } catch (MalformedURLException e) {
59 // this is a format error, but it could have been specified as a local
60 // file name. so try to create a file object and make a URL from that.
61 }
62
63 try {
64 // The file class has direct support for returning as a URL, but the Javadoc
65 // for File.toURL() recommends converting the File object to a URI first
66 // so that untranslatable characters get handled correctly.
67 return new File(text).toURI().toURL();
68 } catch (MalformedURLException e) {
69 // any error here is returned as a property editor exception.
70 throw new PropertyEditorException(e);
71 }
72 }
73 }