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