1 /*
2 * Copyright 2011 Chris Pheby
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.jadira.bindings.core.general.binding;
17
18 import org.jadira.bindings.core.api.Binding;
19 import org.jadira.bindings.core.api.FromUnmarshaller;
20 import org.jadira.bindings.core.api.ToMarshaller;
21
22 /**
23 * Binding that supports a to contract, and from contract. This binding reverses the interpretation
24 * of the binding it wraps so that the source and target relationships are reversed.
25 * @param <S> Source type for the conversion
26 * @param <T> Target type
27 */
28 public class InverseCompositeBinding<S, T> implements Binding<S, T> {
29
30 private final ToMarshaller<T, S> marshal;
31
32 private final FromUnmarshaller<T, S> unmarshal;
33
34 /**
35 * Create a binding that reverses the interpretation of the supplied binding
36 * @param binding The binding to reverse
37 */
38 public InverseCompositeBinding(Binding<T, S> binding) {
39
40 if (binding == null) {
41 throw new IllegalStateException("Binding may not be null");
42 }
43
44 this.unmarshal = binding;
45 this.marshal = binding;
46 }
47
48 /**
49 * Create a binding that reverses the interpretation of the supplied Marshaller and Unmarshaller
50 * @param marshal The Marshaller to be interpreted as an Unmarshaller
51 * @param unmarshal The Unmarshaller to be interpreted as an Marshaller
52 */
53 public InverseCompositeBinding(ToMarshaller<T, S> marshal, FromUnmarshaller<T, S> unmarshal) {
54
55 if (unmarshal == null) {
56 throw new IllegalStateException("Unmarshaller may not be null");
57 }
58 if (marshal == null) {
59 throw new IllegalStateException("Marshaller may not be null");
60 }
61
62 this.unmarshal = unmarshal;
63 this.marshal = marshal;
64 }
65
66 /**
67 * {@inheritDoc}
68 */
69 /* @Override */
70 public T marshal(S object) {
71 return unmarshal.unmarshal(object);
72 }
73
74 /**
75 * {@inheritDoc}
76 */
77 /* @Override */
78 public S unmarshal(T input) {
79 return marshal.marshal(input);
80 }
81
82 /**
83 * {@inheritDoc}
84 */
85 /* @Override */
86 public Class<S> getBoundClass() {
87 return marshal.getTargetClass();
88 }
89
90 /**
91 * {@inheritDoc}
92 */
93 /* @Override */
94 public Class<T> getTargetClass() {
95 return marshal.getBoundClass();
96 }
97 }