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.
012
013package org.apache.tapestry5.internal.services;
014
015import org.apache.tapestry5.ContentType;
016import org.apache.tapestry5.SymbolConstants;
017import org.apache.tapestry5.internal.InternalConstants;
018import org.apache.tapestry5.ioc.annotations.Symbol;
019import org.apache.tapestry5.json.JSONArray;
020import org.apache.tapestry5.services.ComponentEventResultProcessor;
021import org.apache.tapestry5.services.Response;
022
023import java.io.IOException;
024import java.io.PrintWriter;
025
026public class JSONArrayEventResultProcessor implements ComponentEventResultProcessor<JSONArray>
027{
028    private final Response response;
029
030    private final boolean compactJSON;
031
032    private final ContentType contentType;
033
034    public JSONArrayEventResultProcessor(Response response,
035
036                                         @Symbol(SymbolConstants.CHARSET)
037                                         String outputEncoding,
038
039                                         @Symbol(SymbolConstants.COMPACT_JSON)
040                                         boolean compactJSON)
041    {
042        this.response = response;
043        this.compactJSON = compactJSON;
044
045        contentType = new ContentType(InternalConstants.JSON_MIME_TYPE).withCharset(outputEncoding);
046    }
047
048    public void processResultValue(JSONArray value) throws IOException
049    {
050        PrintWriter pw = response.getPrintWriter(contentType.toString());
051
052        value.print(pw, compactJSON);
053
054        pw.close();
055    }
056}