001// Copyright 2006, 2007 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007//     http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry5.commons.internal.services;
016
017import org.apache.tapestry5.commons.services.Coercion;
018
019/**
020 * Combines two coercions to create a coercion through an intermediate type.
021 *
022 * @param <S> The source (input) type
023 * @param <I> The intermediate type
024 * @param <T> The target (output) type
025 */
026public class CompoundCoercion<S, I, T> implements Coercion<S, T>
027{
028    private final Coercion<S, I> op1;
029
030    private final Coercion<I, T> op2;
031
032    public CompoundCoercion(Coercion<S, I> op1, Coercion<I, T> op2)
033    {
034        this.op1 = op1;
035        this.op2 = op2;
036    }
037
038    @Override
039    public T coerce(S input)
040    {
041        // Run the input through the first operation (S --> I), then run the result of that through
042        // the second operation (I --> T).
043
044        I intermediate = op1.coerce(input);
045
046        return op2.coerce(intermediate);
047    }
048
049    @Override
050    public String toString()
051    {
052        return String.format("%s, %s", op1, op2);
053    }
054}