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.rest.jackson.internal;
013
014import java.io.IOException;
015import java.util.Set;
016
017import javax.servlet.http.HttpServletRequest;
018
019import org.apache.tapestry5.commons.internal.util.TapestryException;
020import org.apache.tapestry5.http.services.HttpRequestBodyConverter;
021import org.apache.tapestry5.jacksondatabind.services.ObjectMapperSource;
022import org.apache.tapestry5.services.rest.MappedEntityManager;
023
024public class JacksonHttpRequestBodyConverter implements HttpRequestBodyConverter {
025    
026    final private Set<Class<?>> entities;
027    
028    final private ObjectMapperSource objectMapperSource;
029    
030    public JacksonHttpRequestBodyConverter(MappedEntityManager mappedEntityManager,
031            ObjectMapperSource objectMapperSource)
032    {
033        this.entities = mappedEntityManager.getEntities();
034        this.objectMapperSource = objectMapperSource;
035    }
036
037    @Override
038    public <T> T convert(HttpServletRequest request, Class<T> type) {
039        
040        T value = null;
041        if (entities.contains(type))
042        {
043            try {
044                value = objectMapperSource.get(type).readValue(request.getReader(), type);
045            } catch (IOException e) {
046                throw new TapestryException("Exception while converting HTTP request body into " + type.getName(), e);
047            }
048        }
049        
050        return value;
051    }
052
053}