    001// Licensed under the Apache License, Version 2.0 (the "License");
    002// you may not use this file except in compliance with the License.
    003// You may obtain a copy of the License at
    004//
    005// http://www.apache.org/licenses/LICENSE-2.0
    006//
    007// Unless required by applicable law or agreed to in writing, software
    008// distributed under the License is distributed on an "AS IS" BASIS,
    009// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    010// See the License for the specific language governing permissions and
    011// limitations under the License.
    012package org.apache.tapestry5.http.internal;
    013
    014import javax.servlet.http.HttpServletRequest;
    015
    016import org.apache.tapestry5.commons.internal.util.TapestryException;
    017import org.apache.tapestry5.commons.services.TypeCoercer;
    018import org.apache.tapestry5.commons.util.CoercionNotFoundException;
    019import org.apache.tapestry5.http.services.HttpRequestBodyConverter;
    020
    021final public class TypeCoercerHttpRequestBodyConverter implements HttpRequestBodyConverter
    022{
    023
    024    final private TypeCoercer typeCoercer;
    025
    026    public TypeCoercerHttpRequestBodyConverter(TypeCoercer typeCoercer)
    027    {
    028        super();
    029        this.typeCoercer = typeCoercer;
    030    }
    031
    032    @Override
    033    public <T> T convert(HttpServletRequest request, Class<T> type)
    034    {
    035        T value;
    036        try
    037        {
    038            value = typeCoercer.coerce(request, type);
    039        } catch (CoercionNotFoundException e)
    040        {
    041            throw new TapestryException(
    042                    String.format("Couldn't find a coercion from InputStream to %s "
    043                            + " since no %s converted it", type.getName(), HttpRequestBodyConverter.class.getSimpleName())
    044                    , e);
    045        }
    046        return value;
    047    }
    048
    049}