1 package info.magnolia.cms.util; 2 3 import java.io.ByteArrayOutputStream ; 4 import java.io.IOException ; 5 import java.io.PrintWriter ; 6 import java.io.StringWriter ; 7 import java.io.UnsupportedEncodingException ; 8 import java.util.Locale ; 9 10 import javax.servlet.ServletException ; 11 import javax.servlet.ServletOutputStream ; 12 import javax.servlet.http.HttpServletRequest ; 13 import javax.servlet.http.HttpServletResponse ; 14 import javax.servlet.http.HttpServletResponseWrapper ; 15 16 import org.apache.commons.lang.StringUtils; 17 import org.apache.taglibs.standard.resources.Resources; 18 19 20 32 33 44 public final class JSPIncludeUtil { 45 46 public static final String DEFAULT_ENCODING = "UTF-8"; 48 51 private JSPIncludeUtil() { 52 } 54 55 56 private static class ImportResponseWrapper extends HttpServletResponseWrapper { 57 58 59 private StringWriter sw = new StringWriter (); 60 61 62 protected ByteArrayOutputStream bos = new ByteArrayOutputStream (); 63 64 65 private ServletOutputStream sos = new ServletOutputStream () { 66 67 public void write(int b) throws IOException { 68 bos.write(b); 69 } 70 }; 71 72 73 private boolean isWriterUsed; 74 75 76 private boolean isStreamUsed; 77 78 79 private int status = 200; 80 81 82 public ImportResponseWrapper(HttpServletResponse response) { 83 super(response); 84 } 85 86 89 public PrintWriter getWriter() { 90 if (isStreamUsed) { 91 throw new IllegalStateException (Resources.getMessage("IMPORT_ILLEGAL_STREAM")); } 93 isWriterUsed = true; 94 return new PrintWriter (sw); 95 } 96 97 100 public ServletOutputStream getOutputStream() { 101 if (isWriterUsed) { 102 throw new IllegalStateException (Resources.getMessage("IMPORT_ILLEGAL_WRITER")); } 104 isStreamUsed = true; 105 return sos; 106 } 107 108 111 public void setContentType(String x) { 112 } 114 115 116 public void setLocale(Locale x) { 117 } 119 120 public void setStatus(int status) { 121 this.status = status; 122 } 123 124 public int getStatus() { 125 return status; 126 } 127 128 132 public String getString() throws UnsupportedEncodingException { 135 if (isWriterUsed) { 136 return sw.toString(); 137 } 138 else if (isStreamUsed) { 139 return bos.toString(DEFAULT_ENCODING); 140 } 141 else { 142 return StringUtils.EMPTY; } 144 } 145 } 146 147 public static String get(String jsp, HttpServletRequest request, HttpServletResponse response) 148 throws ServletException , IOException { 149 ImportResponseWrapper wrappedResponse = new ImportResponseWrapper(response); 150 request.getRequestDispatcher(jsp).include(request, wrappedResponse); 151 return wrappedResponse.getString(); 152 } 153 } 154 | Popular Tags |