1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.beanutils.converters;
18
19 import java.io.File;
20
21 import org.apache.commons.beanutils.ConversionException;
22 import org.apache.commons.beanutils.Converter;
23
24 /**
25 * <p>Standard {@link Converter} implementation that converts an incoming
26 * String into a <code>java.io.FileL</code> object, optionally using a
27 * default value or throwing a {@link ConversionException} if a conversion
28 * error occurs.</p>
29 *
30 * @author James Strachan
31 * @version $Revision: 1.4 $ $Date: 2004/02/28 13:18:34 $
32 * @since 1.6
33 */
34 public final class FileConverter implements Converter {
35
36
37
38
39 /**
40 * The default value specified to our Constructor, if any.
41 */
42 private Object defaultValue = null;
43
44
45 /**
46 * Should we return the default value on conversion errors?
47 */
48 private boolean useDefault = true;
49
50
51
52
53
54 /**
55 * Create a {@link Converter} that will throw a {@link ConversionException}
56 * if a conversion error occurs.
57 */
58 public FileConverter() {
59
60 this.defaultValue = null;
61 this.useDefault = false;
62
63 }
64
65
66 /**
67 * Create a {@link Converter} that will return the specified default value
68 * if a conversion error occurs.
69 *
70 * @param defaultValue The default value to be returned
71 */
72 public FileConverter(Object defaultValue) {
73
74 this.defaultValue = defaultValue;
75 this.useDefault = true;
76
77 }
78
79
80
81
82
83
84 /**
85 * Convert the specified input object into an output object of the
86 * specified type.
87 *
88 * @param type Data type to which this value should be converted
89 * @param value The input value to be converted
90 *
91 * @exception ConversionException if conversion cannot be performed
92 * successfully
93 */
94 public Object convert(Class type, Object value) {
95
96 if (value == null) {
97 if (useDefault) {
98 return (defaultValue);
99 } else {
100 throw new ConversionException("No value specified");
101 }
102 }
103
104 if (value instanceof File) {
105 return (value);
106 }
107
108 return new File(value.toString());
109 }
110 }