    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.io.PrintWriter;
    016
    017import org.apache.tapestry5.http.ContentType;
    018import org.apache.tapestry5.http.TapestryHttpSymbolConstants;
    019import org.apache.tapestry5.http.services.Response;
    020import org.apache.tapestry5.internal.InternalConstants;
    021import org.apache.tapestry5.ioc.annotations.Symbol;
    022import org.apache.tapestry5.jacksondatabind.services.ObjectMapperSource;
    023import org.apache.tapestry5.services.ComponentEventResultProcessor;
    024import org.apache.tapestry5.services.rest.MappedEntityManager;
    025
    026import com.fasterxml.jackson.databind.ObjectMapper;
    027
    028/**
    029 * Handles mapped entity class instances using Jackson Databind
    030 * when they're returned by event handler methods. It uses the {@link ObjectMapper}
    031 * instance provided by {@link ObjectMapperSource}.
    032 *
    033 * @see MappedEntityManager
    034 * @see ObjectMapperSource
    035 * @since 5.8.0
    036 */
    037public class JacksonComponentEventResultProcessor<T> implements ComponentEventResultProcessor<T> {
    038
    039    private final Response response;
    040
    041    private final ContentType contentType;
    042
    043    private final ObjectMapperSource objectMapperSource;
    044
    045    private final Class<T> entityClass;
    046
    047    public JacksonComponentEventResultProcessor(Class<T> entityClass, Response response,
    048                @Symbol(TapestryHttpSymbolConstants.CHARSET) String outputEncoding,
    049                ObjectMapperSource objectMapperSource)
    050    {
    051        this.response = response;
    052        this.objectMapperSource = objectMapperSource;
    053        this.entityClass = entityClass;
    054        contentType = new ContentType(InternalConstants.JSON_MIME_TYPE).withCharset(outputEncoding);
    055    }
    056
    057    public void processResultValue(T object) throws IOException {
    058        PrintWriter pw = response.getPrintWriter(contentType.toString());
    059        pw.write(objectMapperSource.get(entityClass).writeValueAsString(object));
    060        pw.close();
    061    }
    062}