01: /*
02: * Copyright 2002-2007 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.springframework.beans.propertyeditors;
18:
19: import java.beans.PropertyEditorSupport;
20: import java.io.ByteArrayInputStream;
21: import java.io.IOException;
22: import java.util.Map;
23: import java.util.Properties;
24:
25: /**
26: * Custom {@link java.beans.PropertyEditor} for {@link Properties} objects.
27: *
28: * <p>Handles conversion from content {@link String} to <code>Properties</code> object.
29: * Also handles {@link Map} to <code>Properties</code> conversion, for populating
30: * a <code>Properties</code> object via XML "map" entries.
31: *
32: * <p>The required format is defined in the standard <code>Properties</code>
33: * documentation. Each property must be on a new line.
34: *
35: * @author Rod Johnson
36: * @author Juergen Hoeller
37: * @see java.util.Properties#load
38: */
39: public class PropertiesEditor extends PropertyEditorSupport {
40:
41: /**
42: * Any of these characters, if they're first after whitespace or first
43: * on a line, mean that the line is a comment and should be ignored.
44: */
45: private final static String COMMENT_MARKERS = "#!";
46:
47: /**
48: * Convert {@link String} into {@link Properties}, considering it as
49: * properties content.
50: * @param text the text to be so converted
51: */
52: public void setAsText(String text) throws IllegalArgumentException {
53: Properties props = new Properties();
54: if (text != null) {
55: try {
56: // Must use the ISO-8859-1 encoding because Properties.load(stream) expects it.
57: props.load(new ByteArrayInputStream(text
58: .getBytes("ISO-8859-1")));
59: } catch (IOException ex) {
60: // Should never happen.
61: throw new IllegalArgumentException("Failed to parse ["
62: + text + "] into Properties: "
63: + ex.getMessage());
64: }
65: }
66: setValue(props);
67: }
68:
69: /**
70: * Take {@link Properties} as-is; convert {@link Map} into <code>Properties</code>.
71: */
72: public void setValue(Object value) {
73: if (!(value instanceof Properties) && value instanceof Map) {
74: Properties props = new Properties();
75: props.putAll((Map) value);
76: super.setValue(props);
77: } else {
78: super.setValue(value);
79: }
80: }
81:
82: }
|