1 // Copyright 2007, 2008 The Apache Software Foundation 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package org.apache.tapestry5.util; 16 17 import org.apache.tapestry5.ContentType; 18 import org.apache.tapestry5.StreamResponse; 19 import org.apache.tapestry5.ioc.internal.util.Defense; 20 import org.apache.tapestry5.services.Response; 21 22 import java.io.ByteArrayInputStream; 23 import java.io.IOException; 24 import java.io.InputStream; 25 26 public class TextStreamResponse implements StreamResponse 27 { 28 private final ContentType contentType; 29 30 private final String text; 31 32 /** 33 * Constructor that defaults the character set to "utf-8". 34 */ 35 public TextStreamResponse(String contentType, String text) 36 { 37 this(contentType, "UTF-8", text); 38 } 39 40 /** 41 * Constructor allowing the content type and character set to the specified. 42 * 43 * @param contentType type of content, often "text/xml" 44 * @param charset character set of output, usually "UTF-8" 45 * @param text text to be streamed in the response 46 * @see org.apache.tapestry5.SymbolConstants#CHARSET 47 */ 48 public TextStreamResponse(String contentType, String charset, String text) 49 { 50 this(new ContentType(Defense.notBlank(contentType, "contentType"), 51 Defense.notBlank(charset, "charset")), text); 52 } 53 54 public TextStreamResponse(ContentType contentType, String text) 55 { 56 Defense.notNull(contentType, "contentType"); 57 Defense.notNull(text, "text"); 58 59 this.contentType = contentType; 60 this.text = text; 61 } 62 63 public String getContentType() 64 { 65 return contentType.toString(); 66 } 67 68 /** 69 * Converts the text to a byte array (as per the character set, which is usually "UTF-8"), and returns a stream for 70 * that byte array. 71 * 72 * @return the text as a byte array stram 73 * @throws IOException 74 */ 75 public InputStream getStream() throws IOException 76 { 77 byte[] textBytes = text.getBytes(contentType.getCharset()); 78 79 return new ByteArrayInputStream(textBytes); 80 } 81 82 /** 83 * Does nothing; subclasses may override. 84 */ 85 public void prepareResponse(Response response) 86 { 87 88 } 89 }