001// Copyright 2007, 2008, 2010 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.internal.services;
016
017import java.io.IOException;
018import java.io.PrintWriter;
019
020import org.apache.tapestry5.ContentType;
021import org.apache.tapestry5.SymbolConstants;
022import org.apache.tapestry5.internal.InternalConstants;
023import org.apache.tapestry5.ioc.annotations.Symbol;
024import org.apache.tapestry5.json.JSONObject;
025import org.apache.tapestry5.services.ComponentEventResultProcessor;
026import org.apache.tapestry5.services.Response;
027
028/**
029 * Implementation of {@link ComponentEventResultProcessor} for {@link org.apache.tapestry5.json.JSONObject}, allowing a
030 * component event handler to return a JSONObject that will be sent directly to the client as the reply. This is often
031 * used with custom components that need a custom JSON response.
032 */
033public class JSONObjectEventResultProcessor implements ComponentEventResultProcessor<JSONObject>
034{
035    private final Response response;
036
037    private final String outputEncoding;
038
039    private final boolean compactJSON;
040
041    public JSONObjectEventResultProcessor(Response response,
042
043    @Symbol(SymbolConstants.CHARSET)
044    String outputEncoding,
045
046    @Symbol(SymbolConstants.COMPACT_JSON)
047    boolean compactJSON)
048    {
049        this.response = response;
050        this.outputEncoding = outputEncoding;
051        this.compactJSON = compactJSON;
052    }
053
054    public void processResultValue(JSONObject value) throws IOException
055    {
056        ContentType contentType = new ContentType(InternalConstants.JSON_MIME_TYPE, outputEncoding);
057
058        PrintWriter pw = response.getPrintWriter(contentType.toString());
059
060        value.print(pw, compactJSON);
061
062        pw.close();
063    }
064}