View Javadoc

1   /*
2    * Copyright 2004 Ronald Blaschke.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
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.rblasch.convert.converters;
17  
18  import org.rblasch.convert.MetaConverter;
19  import org.rblasch.convert.type.Type;
20  
21  import java.util.Iterator;
22  import java.util.List;
23  
24  public final class ChainedConverter extends AbstractConverter {
25      private final List /*<MetaConverter>*/ converters;
26  
27      /***
28       * Initialize this chained converter.
29       *
30       * @param converters
31       */
32      public ChainedConverter(final List /*<MetaConverter>*/ converters) {
33          this.converters = converters;
34      }
35  
36      public Type getSourceType() {
37          return ((MetaConverter) converters.get(0)).getSourceType();
38      }
39  
40      public Type getDestinationType() {
41          return ((MetaConverter) converters.get(converters.size() - 1)).getDestinationType();
42      }
43  
44      public int getWeight() {
45          int totalWeight = 0;
46          for (final Iterator i = converters.iterator(); i.hasNext();) {
47              final MetaConverter mc = (MetaConverter) i.next();
48              totalWeight += mc.getWeight();
49          }
50          return totalWeight;
51      }
52  
53      /***
54       * Converts the given value to the destination types.
55       *
56       * @param obj Object of types <code>getSourceType()</code>, or <code>null</code>
57       * @return <code>null</code> iff value is <code>null</code>, object of types
58       *         <code>getDestinationType()</code>
59       * @throws org.apache.commons.convert.NoSuchConversionException
60       *          Given object not of types <code>getSourceType()</code>
61       * @throws org.apache.commons.convert.ConversionFailedException
62       *          Conversion failed; see exception message and cause for details
63       */
64      public Object convert(final Object obj) throws Exception {
65          Object tmp = obj;
66          for (final Iterator i = converters.iterator(); i.hasNext();) {
67              final MetaConverter c = (MetaConverter) i.next();
68              tmp = c.getConverter().convert(tmp);
69          }
70          return tmp;
71      }
72  }