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