KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > widget > screen > ScreenRenderer


1 /*
2  * $Id: ScreenRenderer.java 6519 2006-01-17 08:17:22Z jonesde $
3  *
4  * Copyright (c) 2004 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */

24 package org.ofbiz.widget.screen;
25
26 import java.io.IOException JavaDoc;
27 import java.io.Writer JavaDoc;
28 import java.util.Enumeration JavaDoc;
29 import java.util.LinkedList JavaDoc;
30 import java.util.List JavaDoc;
31 import java.util.Locale JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.Set JavaDoc;
34
35 import javax.servlet.ServletContext JavaDoc;
36 import javax.servlet.http.HttpServletRequest JavaDoc;
37 import javax.servlet.http.HttpServletResponse JavaDoc;
38 import javax.servlet.http.HttpSession JavaDoc;
39 import javax.xml.parsers.ParserConfigurationException JavaDoc;
40
41 import javolution.util.FastMap;
42 import javolution.util.FastSet;
43
44 import org.ofbiz.base.util.Debug;
45 import org.ofbiz.base.util.GeneralException;
46 import org.ofbiz.base.util.UtilDateTime;
47 import org.ofbiz.base.util.UtilFormatOut;
48 import org.ofbiz.base.util.UtilHttp;
49 import org.ofbiz.base.util.UtilMisc;
50 import org.ofbiz.base.util.UtilValidate;
51 import org.ofbiz.base.util.collections.MapStack;
52 import org.ofbiz.entity.GenericDelegator;
53 import org.ofbiz.entity.GenericEntity;
54 import org.ofbiz.entity.GenericValue;
55 import org.ofbiz.security.Security;
56 import org.ofbiz.service.DispatchContext;
57 import org.ofbiz.service.LocalDispatcher;
58 import org.ofbiz.webapp.control.LoginWorker;
59 import org.ofbiz.widget.html.HtmlFormRenderer;
60 import org.xml.sax.SAXException JavaDoc;
61
62 import freemarker.ext.beans.BeansWrapper;
63 import freemarker.ext.jsp.TaglibFactory;
64 import freemarker.ext.servlet.HttpRequestHashModel;
65 import freemarker.ext.servlet.HttpSessionHashModel;
66
67 /**
68  * Widget Library - Screen model class
69  *
70  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
71  * @version $Rev: 6519 $
72  * @since 3.1
73  */

74 public class ScreenRenderer {
75
76     public static final String JavaDoc module = ScreenRenderer.class.getName();
77     
78     protected Writer JavaDoc writer;
79     protected MapStack context;
80     protected ScreenStringRenderer screenStringRenderer;
81     
82     public ScreenRenderer(Writer JavaDoc writer, MapStack context, ScreenStringRenderer screenStringRenderer) {
83         this.writer = writer;
84         this.context = context;
85         if (this.context == null) this.context = MapStack.create();
86         this.screenStringRenderer = screenStringRenderer;
87     }
88     
89     /**
90      * Renders the named screen using the render environment configured when this ScreenRenderer was created.
91      *
92      * @param combinedName A combination of the resource name/location for the screen XML file and the name of the screen within that file, separated by a puund sign ("#"). This is the same format that is used in the view-map elements on the controller.xml file.
93      * @throws IOException
94      * @throws SAXException
95      * @throws ParserConfigurationException
96      */

97     public String JavaDoc render(String JavaDoc combinedName) throws GeneralException, IOException JavaDoc, SAXException JavaDoc, ParserConfigurationException JavaDoc {
98         String JavaDoc resourceName = ScreenFactory.getResourceNameFromCombined(combinedName);
99         String JavaDoc screenName = ScreenFactory.getScreenNameFromCombined(combinedName);
100         this.render(resourceName, screenName);
101         return "";
102     }
103
104     /**
105      * Renders the named screen using the render environment configured when this ScreenRenderer was created.
106      *
107      * @param resourceName The name/location of the resource to use, can use "component://[component-name]/" and "ofbiz://" and other special OFBiz style URLs
108      * @param screenName The name of the screen within the XML file specified by the resourceName.
109      * @throws IOException
110      * @throws SAXException
111      * @throws ParserConfigurationException
112      */

113     public String JavaDoc render(String JavaDoc resourceName, String JavaDoc screenName) throws GeneralException, IOException JavaDoc, SAXException JavaDoc, ParserConfigurationException JavaDoc {
114         ModelScreen modelScreen = ScreenFactory.getScreenFromLocation(resourceName, screenName);
115         modelScreen.renderScreenString(writer, context, screenStringRenderer);
116         return "";
117     }
118
119     public ScreenStringRenderer getScreenStringRenderer() {
120         return this.screenStringRenderer;
121     }
122
123     public void populateBasicContext(Map JavaDoc parameters, GenericDelegator delegator, LocalDispatcher dispatcher, Security security, Locale JavaDoc locale, GenericValue userLogin) {
124         // ========== setup values that should always be in a screen context
125
// include an object to more easily render screens
126
context.put("screens", this);
127
128         // make a reference for high level variables, a global context
129
context.put("globalContext", context.standAloneStack());
130
131         // make sure the "nullField" object is in there for entity ops; note this is nullField and not null because as null causes problems in FreeMarker and such...
132
context.put("nullField", GenericEntity.NULL_FIELD);
133
134         // get all locale information
135
context.put("availableLocales", UtilMisc.availableLocales());
136
137         context.put("parameters", parameters);
138         context.put("delegator", delegator);
139         context.put("dispatcher", dispatcher);
140         context.put("security", security);
141         context.put("locale", locale);
142         context.put("userLogin", userLogin);
143     }
144     
145     /**
146      * This method populates the context for this ScreenRenderer based on the HTTP Request and Respone objects and the ServletContext.
147      * It leverages various conventions used in other places, namely the ControlServlet and so on, of OFBiz to get the different resources needed.
148      *
149      * @param request
150      * @param response
151      * @param servletContext
152      */

153     public void populateContextForRequest(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, ServletContext JavaDoc servletContext) {
154         HttpSession JavaDoc session = request.getSession();
155
156         // attribute names to skip for session and application attributes; these are all handled as special cases, duplicating results and causing undesired messages
157
Set JavaDoc attrNamesToSkip = FastSet.newInstance();
158         attrNamesToSkip.add("delegator");
159         attrNamesToSkip.add("dispatcher");
160         attrNamesToSkip.add("security");
161         attrNamesToSkip.add("webSiteId");
162
163         Map JavaDoc parameterMap = UtilHttp.getParameterMap(request);
164         // go through all request attributes and for each name that is not already in the parameters Map add the attribute value
165
Enumeration JavaDoc requestAttrNames = request.getAttributeNames();
166         while (requestAttrNames.hasMoreElements()) {
167             String JavaDoc attrName = (String JavaDoc) requestAttrNames.nextElement();
168             Object JavaDoc attrValue = request.getAttribute(attrName);
169
170             // NOTE: this is being set to false by default now
171
//this change came after the realization that it is common to want a request attribute to override a request parameter, but I can't think of even ONE reason why a request parameter should override a request attribute...
172
final boolean preserveRequestParameters = false;
173             if (preserveRequestParameters) {
174                 Object JavaDoc param = parameterMap.get(attrName);
175                 if (param == null) {
176                     parameterMap.put(attrName, attrValue);
177                 } else if (param instanceof String JavaDoc && ((String JavaDoc) param).length() == 0) {
178                     // also put the attribute value in if the parameter is empty
179
parameterMap.put(attrName, attrValue);
180                 } else {
181                     // do nothing, just log something
182
Debug.logInfo("Found request attribute that conflicts with parameter name, leaving request parameter in place for name: " + attrName, module);
183                 }
184             } else {
185                 parameterMap.put(attrName, attrValue);
186             }
187         }
188
189         // do the same for session attributes, for convenience
190
Enumeration JavaDoc sessionAttrNames = session.getAttributeNames();
191         while (sessionAttrNames.hasMoreElements()) {
192             String JavaDoc attrName = (String JavaDoc) sessionAttrNames.nextElement();
193             if (attrNamesToSkip.contains(attrName)) continue;
194             Object JavaDoc attrValue = session.getAttribute(attrName);
195             Object JavaDoc param = parameterMap.get(attrName);
196             if (param == null) {
197                 parameterMap.put(attrName, attrValue);
198             } else if (param instanceof String JavaDoc && ((String JavaDoc) param).length() == 0) {
199                 // also put the attribute value in if the parameter is empty
200
parameterMap.put(attrName, attrValue);
201             } else {
202                 // do nothing, just log something
203
Debug.logInfo("Found session attribute that conflicts with parameter name, leaving request parameter in place for name: " + attrName, module);
204             }
205         }
206
207         // do the same for servlet context (application) attribute, for convenience
208
Enumeration JavaDoc applicationAttrNames = servletContext.getAttributeNames();
209         while (applicationAttrNames.hasMoreElements()) {
210             String JavaDoc attrName = (String JavaDoc) applicationAttrNames.nextElement();
211             if (attrNamesToSkip.contains(attrName)) continue;
212             Object JavaDoc param = parameterMap.get(attrName);
213             Object JavaDoc attrValue = servletContext.getAttribute(attrName);
214             if (Debug.verboseOn()) Debug.logVerbose("Getting parameter from application attrbute with name [" + attrName + "] and value [" + attrValue + "]", module);
215             if (param == null) {
216                 parameterMap.put(attrName, attrValue);
217             } else if (param instanceof String JavaDoc && ((String JavaDoc) param).length() == 0) {
218                 // also put the attribute value in if the parameter is empty
219
parameterMap.put(attrName, attrValue);
220             } else {
221                 // do nothing, just log something
222
Debug.logInfo("Found servlet context (application) attribute that conflicts with parameter name, leaving request parameter in place for name: " + attrName, module);
223             }
224         }
225
226         GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
227         
228         this.populateBasicContext(parameterMap, (GenericDelegator) request.getAttribute("delegator"),
229                 (LocalDispatcher) request.getAttribute("dispatcher"), (Security) request.getAttribute("security"),
230                 UtilHttp.getLocale(request), userLogin);
231
232         context.put("autoUserLogin", session.getAttribute("autoUserLogin"));
233         context.put("person", session.getAttribute("person"));
234         context.put("partyGroup", session.getAttribute("partyGroup"));
235
236         // some things also seem to require this, so here it is:
237
request.setAttribute("userLogin", userLogin);
238
239         // ========== setup values that are specific to OFBiz webapps
240

241         // this is the object used to render forms from their definitions
242
context.put("formStringRenderer", new HtmlFormRenderer(request, response));
243
244         context.put("request", request);
245         context.put("response", response);
246         context.put("session", session);
247         context.put("application", servletContext);
248         if (servletContext != null) {
249             String JavaDoc rootDir = (String JavaDoc) context.get("rootDir");
250             String JavaDoc webSiteId = (String JavaDoc) context.get("webSiteId");
251             String JavaDoc https = (String JavaDoc) context.get("https");
252             if (UtilValidate.isEmpty(rootDir)) {
253                 rootDir = servletContext.getRealPath("/");
254                 context.put("rootDir", rootDir);
255             }
256             if (UtilValidate.isEmpty(webSiteId)) {
257                 webSiteId = (String JavaDoc) servletContext.getAttribute("webSiteId");
258                 context.put("webSiteId", webSiteId);
259             }
260             if (UtilValidate.isEmpty(https)) {
261                 https = (String JavaDoc) servletContext.getAttribute("https");
262                 context.put("https", https);
263             }
264         }
265
266         // these ones are FreeMarker specific and will only work in FTL templates, mainly here for backward compatibility
267
BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
268         context.put("sessionAttributes", new HttpSessionHashModel(session, wrapper));
269         context.put("requestAttributes", new HttpRequestHashModel(request, wrapper));
270         TaglibFactory JspTaglibs = new TaglibFactory(servletContext);
271         context.put("JspTaglibs", JspTaglibs);
272         context.put("requestParameters", UtilHttp.getParameterMap(request));
273
274         // this is a dummy object to stand-in for the JPublish page object for backward compatibility
275
context.put("page", FastMap.newInstance());
276
277         // some information from/about the ControlServlet environment
278
context.put("controlPath", request.getAttribute("_CONTROL_PATH_"));
279         context.put("contextRoot", request.getAttribute("_CONTEXT_ROOT_"));
280         context.put("serverRoot", request.getAttribute("_SERVER_ROOT_URL_"));
281         context.put("checkLoginUrl", LoginWorker.makeLoginUrl(request, "checkLogin"));
282         String JavaDoc externalLoginKey = LoginWorker.getExternalLoginKey(request);
283         String JavaDoc externalKeyParam = externalLoginKey == null ? "" : "&externalLoginKey=" + externalLoginKey;
284         context.put("externalLoginKey", externalLoginKey);
285         context.put("externalKeyParam", externalKeyParam);
286
287         // setup message lists
288
List JavaDoc eventMessageList = (List JavaDoc) request.getAttribute("eventMessageList");
289         if (eventMessageList == null) eventMessageList = new LinkedList JavaDoc();
290         List JavaDoc errorMessageList = (List JavaDoc) request.getAttribute("errorMessageList");
291         if (errorMessageList == null) errorMessageList = new LinkedList JavaDoc();
292
293         if (request.getAttribute("_EVENT_MESSAGE_") != null) {
294             eventMessageList.add(UtilFormatOut.replaceString((String JavaDoc) request.getAttribute("_EVENT_MESSAGE_"), "\n", "<br/>"));
295             request.removeAttribute("_EVENT_MESSAGE_");
296         }
297         if (request.getAttribute("_EVENT_MESSAGE_LIST_") != null) {
298             eventMessageList.addAll((List JavaDoc) request.getAttribute("_EVENT_MESSAGE_LIST_"));
299             request.removeAttribute("_EVENT_MESSAGE_LIST_");
300         }
301         if (request.getAttribute("_ERROR_MESSAGE_") != null) {
302             errorMessageList.add(UtilFormatOut.replaceString((String JavaDoc) request.getAttribute("_ERROR_MESSAGE_"), "\n", "<br/>"));
303             request.removeAttribute("_ERROR_MESSAGE_");
304         }
305         if (session.getAttribute("_ERROR_MESSAGE_") != null) {
306             errorMessageList.add(UtilFormatOut.replaceString((String JavaDoc) session.getAttribute("_ERROR_MESSAGE_"), "\n", "<br/>"));
307             session.removeAttribute("_ERROR_MESSAGE_");
308         }
309         if (request.getAttribute("_ERROR_MESSAGE_LIST_") != null) {
310             errorMessageList.addAll((List JavaDoc) request.getAttribute("_ERROR_MESSAGE_LIST_"));
311             request.removeAttribute("_ERROR_MESSAGE_LIST_");
312         }
313         context.put("eventMessageList", eventMessageList);
314         context.put("errorMessageList", errorMessageList);
315
316         if (request.getAttribute("serviceValidationException") != null) {
317             context.put("serviceValidationException", request.getAttribute("serviceValidationException"));
318             request.removeAttribute("serviceValidationException");
319         }
320
321         // if there was an error message, this is an error
322
if (errorMessageList.size() > 0) {
323             context.put("isError", Boolean.TRUE);
324         } else {
325             context.put("isError", Boolean.FALSE);
326         }
327         // if a parameter was passed saying this is an error, it is an error
328
if ("true".equals((String JavaDoc) parameterMap.get("isError"))) {
329             context.put("isError", Boolean.TRUE);
330         }
331         context.put("nowTimestamp", UtilDateTime.nowTimestamp());
332
333         // to preserve these values, push the MapStack
334
context.push();
335     }
336
337     public Map JavaDoc getContext() {
338         return context;
339     }
340     
341     public void populateContextForService(DispatchContext dctx, Map JavaDoc serviceContext) {
342         this.populateBasicContext(serviceContext, dctx.getDelegator(), dctx.getDispatcher(), dctx.getSecurity(),
343                 (Locale JavaDoc) serviceContext.get("locale"), (GenericValue) serviceContext.get("userLogin"));
344     }
345 }
346
Popular Tags