001: package simpleorm.simplewebapp.context;
002:
003: import simpleorm.simplewebapp.core.WPage;
004: import simpleorm.simplewebapp.core.WException;
005:
006: import javax.servlet.http.HttpServletRequest;
007: import javax.servlet.http.HttpServletResponse;
008: import java.io.PrintWriter;
009: import java.io.OutputStream;
010: import java.util.List;
011: import java.util.Map;
012: import java.util.Iterator;
013: import java.util.LinkedHashMap;
014:
015: import org.apache.commons.fileupload.servlet.ServletFileUpload;
016: import org.apache.commons.fileupload.disk.DiskFileItemFactory;
017: import org.apache.commons.fileupload.FileItem;
018:
019: /**
020: * Non-JSP servelet.
021: */
022: public class WPageContextServlet extends WPageContext {
023:
024: private HttpServletRequest request;
025: private HttpServletResponse response;
026:
027: /** Map of parameters, only used if multipart file upload. */
028: Map<String, String> parameters;
029:
030: /**
031: * Redirects to a new page, typically after a successful CRUD form.
032: */
033: public @Override
034: void redirect(String absoluteUrl) {
035: try {
036: String contexted = absoluteUrl; // addContextToUrl(url);
037: String encoded = getPrivateResponse().encodeRedirectURL(
038: contexted);
039: getPrivateResponse().sendRedirect(encoded);
040: } catch (Exception ex) {
041: throw new WException(ex);
042: }
043: }
044:
045: /**
046: * Currently not used, but should be used to make submitted crud go back to the correct place.
047: */
048: public String getRefererUrl() {
049: //dumpHeaders();
050: return getPrivateRequest().getHeader("referer");
051: }
052:
053: // private void dumpHeaders() {
054: // Enumeration hs = getRequest().getHeaderNames();
055: // while (hs.hasMoreElements()) {
056: // String elem = (String) hs.nextElement();
057: // System.err.println("#### Headers " + elem + ":" + getPrivateRequest().getHeader(elem));
058: // }
059: // }
060:
061: public WPageContextServlet(WPage page, HttpServletRequest request,
062: HttpServletResponse response) {
063: super (page);
064: this .request = request;
065: this .response = response;
066: }
067:
068: /** From request, or parameter map for file upload. */
069: public String getParameter(String key) {
070: if (parameters != null)
071: return parameters.get(key);
072: return getPrivateRequest().getParameter(key);
073: }
074:
075: @Override
076: String getContextPath() {
077: return getPrivateRequest().getContextPath();
078: }
079:
080: /**
081: * Add context and session id to urls iff appropriate.
082: */
083: public @Override
084: String encodeContextUrl(String url) {
085: return getPrivateResponse().encodeRedirectURL(
086: addContextToUrl(url));
087: }
088:
089: @Override
090: String getCharacterEncoding() {
091: return getPrivateResponse().getCharacterEncoding();
092: }
093:
094: /**
095: * Ie. the username of the current logged in user.
096: */
097: public @Override
098: String getRemoteUser() {
099: return getPrivateRequest().getRemoteUser();
100: }
101:
102: public @Override
103: boolean isUserInRole(String role) {
104: return getPrivateRequest().isUserInRole(role);
105: }
106:
107: private PrintWriter getOut() throws Exception {
108: return response.getWriter();
109: }
110:
111: public @Override
112: void println(String msg) {
113: try {
114: getOut().print(msg);
115: getOut().println("<BR>");
116: } catch (Exception ex) {
117: throw new WException(ex);
118: }
119: }
120:
121: /**
122: * Interface to Apache Commons File upload.
123: * Returns a list of Files to open, or null if not "MultipartContent" post, eg. a get request.
124: * Non files fields are moved to a map where they are got by getParameter() as normal.
125: * Multipart content is incompatible with normal field request processing.<p>
126: *
127: * NOTE that this must be called in onInitialize, ie. before retrieveParameters is called, so
128: * that it can set up the parameters map from the special MultipartContent format.
129: */
130: public @Override
131: List<FileItem> parseUploadFileItems() throws Exception {
132: HttpServletRequest request = getPrivateRequest();
133: // Check that we have a file upload request
134: boolean isMultipart = ServletFileUpload
135: .isMultipartContent(request);
136: if (!isMultipart)
137: return null;
138:
139: DiskFileItemFactory factory = new DiskFileItemFactory();
140: factory.setSizeThreshold(100000); // Twice max size, so always in memory. default 10240
141: //factory.setRepository(yourTempDirectory); // if file based enabled then be sure to use Reaper.
142:
143: ServletFileUpload upload = new ServletFileUpload(factory);
144: upload.setSizeMax(50000); // default -1
145:
146: // Parse the request
147: List<FileItem> items = upload.parseRequest(request);
148:
149: // Move fields so that they can be got by getParameter.
150: if (parameters != null)
151: throw new WException(
152: "Upload files can only be called once.");
153: parameters = new LinkedHashMap();
154: Iterator iter = items.iterator();
155: while (iter.hasNext()) {
156: FileItem item = (FileItem) iter.next();
157: if (item.isFormField()) {
158: String name = item.getFieldName();
159: String value = item.getString();
160: parameters.put(name, value);
161: iter.remove();
162: }
163: }
164: return items;
165: }
166:
167: /** The returned stream replaces the normal rendoring, and its header is set to be a downloadable file. */
168: public @Override
169: OutputStream openDownloadStream(String fileName) throws Exception {
170: HttpServletResponse response = getPrivateResponse();
171: response.setContentType("application/x-download");
172: response.setHeader("Content-Disposition",
173: "attachment; filename=" + fileName);
174:
175: page.getPageStructure().setSuppressRender(true); // no normal rendering.
176: OutputStream outputStream = response.getOutputStream();
177: return outputStream;
178: }
179:
180: /**
181: * Keep this private, we do not want webserver data leaking out
182: * into the rest of the web bean.
183: * Not actually private because they are used for unusual cases such as WUploadPage.
184: */
185: public HttpServletRequest getPrivateRequest() {
186: return request;
187: }
188:
189: public HttpServletResponse getPrivateResponse() {
190: return response;
191: }
192: }
|