01: /*
02: * Copyright 2004-2006 Fouad HAMDI.
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: package org.csvbeans.converters;
17:
18: import org.csvbeans.specs.SpecificationsFile;
19: import org.csvbeans.utils.MessagesBundle;
20:
21: /**
22: * Use this converter when your fields are wrapped between some characters.
23: *
24: * Define the wrapping string with the <code>stringWrapper</code> property.
25: *
26: * @author Fouad Hamdi
27: * @since 0.7
28: */
29: public class WrapperConverter implements Converter {
30: private String stringWrapper = "\"";
31:
32: public void addProperty(String name, String value) {
33: if (!"stringWrapper".equals(name)) {
34: throw new IllegalArgumentException(MessagesBundle
35: .getMessage("converter.wrapper.property"));
36: }
37: stringWrapper = value;
38: }
39:
40: public void init(SpecificationsFile specifications) {
41: }
42:
43: /**
44: * Return the object value between two string wrappers.
45: */
46: public String encode(Object object) throws ConverterException {
47: if (object == null)
48: return null;
49: return stringWrapper + object.toString() + stringWrapper;
50: }
51:
52: /**
53: * Decode the string value into a string without the wrappers.
54: */
55: public Object decode(String value) throws ConverterException {
56: if (value == null || "".equals(value))
57: return value;
58: if (!value.startsWith(stringWrapper)
59: || !value.endsWith(stringWrapper)) {
60: throw new ConverterException(MessagesBundle.getMessage(
61: "converter.wrapper.missing", new Object[] {
62: stringWrapper, value }));
63: }
64: return value.substring(stringWrapper.length(), value.length()
65: - stringWrapper.length());
66: }
67: }
|