01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * 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.wicket.util.lang;
18:
19: import java.util.Locale;
20:
21: import org.apache.wicket.IClusterable;
22: import org.apache.wicket.IConverterLocator;
23: import org.apache.wicket.util.convert.IConverter;
24:
25: /**
26: * @author jcompagner
27: */
28: public class PropertyResolverConverter implements IClusterable {
29: private static final long serialVersionUID = 1L;
30:
31: private final IConverterLocator converterSupplier;
32: private final Locale locale;
33:
34: /**
35: * Construct.
36: *
37: * @param converterSupplier
38: * @param locale
39: */
40: public PropertyResolverConverter(
41: IConverterLocator converterSupplier, Locale locale) {
42: this .converterSupplier = converterSupplier;
43: this .locale = locale;
44: }
45:
46: /**
47: * @param object
48: * @param clz
49: * @return The converted object
50: */
51: public Object convert(Object object, Class/*<?>*/clz) {
52: if (object == null) {
53: return null;
54: }
55: if (clz.isAssignableFrom(object.getClass())) {
56: return object;
57: }
58: IConverter converter = converterSupplier.getConverter(clz);
59: if (object instanceof String) {
60: return converter.convertToObject((String) object, locale);
61: } else if (clz == String.class) {
62: return converter.convertToString(object, locale);
63: } else {
64: try {
65: return Objects.convertValue(object, clz);
66: } catch (RuntimeException ex) {
67: // ignore that try it the other way
68: }
69: // go through string to convert to the right object.
70: String tmp = converter.convertToString(object, locale);
71: return converter.convertToObject(tmp, locale);
72: }
73: }
74: }
|