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.util;
014
015import java.io.ByteArrayInputStream;
016import java.io.IOException;
017import java.io.InputStream;
018
019import org.apache.tapestry5.ContentType;
020import org.apache.tapestry5.StreamResponse;
021import org.apache.tapestry5.services.Response;
022
023public class TextStreamResponse implements StreamResponse
024{
025    private final ContentType contentType;
026
027    private final String text;
028
029    /**
030     * Constructor that defaults the character set to "utf-8".
031     */
032    public TextStreamResponse(String contentType, String text)
033    {
034        this(contentType, "UTF-8", text);
035    }
036
037    /**
038     * Constructor allowing the content type and character set to the specified.
039     * 
040     * @param contentType
041     *            type of content, often "text/xml"
042     * @param charset
043     *            character set of output, usually "UTF-8"
044     * @param text
045     *            text to be streamed in the response
046     * @see org.apache.tapestry5.SymbolConstants#CHARSET
047     */
048    public TextStreamResponse(String contentType, String charset, String text)
049    {
050        this(new ContentType(contentType).withCharset(charset), text);
051    }
052
053    public TextStreamResponse(ContentType contentType, String text)
054    {
055        assert contentType != null;
056        assert text != null;
057
058        this.contentType = contentType;
059        this.text = text;
060    }
061
062    public String getContentType()
063    {
064        return contentType.toString();
065    }
066
067    /**
068     * Converts the text to a byte array (as per the character set, which is usually "UTF-8"), and returns a stream for
069     * that byte array.
070     * 
071     * @return the text as a byte array stram
072     * @throws IOException
073     */
074    public InputStream getStream() throws IOException
075    {
076        byte[] textBytes = text.getBytes(contentType.getCharset());
077
078        return new ByteArrayInputStream(textBytes);
079    }
080
081    /**
082     * Does nothing; subclasses may override.
083     */
084    public void prepareResponse(Response response)
085    {
086
087    }
088}