KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > za > org > coefficient > core > BaseCoefficientContext


1 /*
2  * Coefficient - facilitates project based collaboration
3  * Copyright (C) 2003, Dylan Etkin, CSIR icomtek
4  * PO Box 395
5  * Pretoria 0001, RSA
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  */

19
20 package za.org.coefficient.core;
21
22 import java.beans.IndexedPropertyDescriptor JavaDoc;
23 import java.beans.PropertyDescriptor JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.lang.reflect.Method JavaDoc;
26
27 import java.util.ArrayList JavaDoc;
28 import java.util.Date JavaDoc;
29 import java.util.HashMap JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.Map JavaDoc;
32
33 import java.beans.Introspector JavaDoc;
34 import java.beans.PropertyDescriptor JavaDoc;
35
36 import org.apache.commons.fileupload.FileUploadException;
37 import org.apache.commons.httpclient.Cookie;
38
39 import za.org.coefficient.authentication.CoefficientUser;
40 import za.org.coefficient.exception.ConfigurationException;
41 import za.org.coefficient.html.Page;
42 import za.org.coefficient.interfaces.CoefficientContext;
43 import za.org.coefficient.util.common.BaseMultipartRequest;
44 import za.org.coefficient.util.common.MultipartRequest;
45 import za.org.coefficient.util.common.UploadedFile;
46
47 /**
48  * <p>Project: coefficient</p>
49  * <p>Description: </p>
50  * <p>Copyright: Copyright (c) 2003</p>
51  * <p>Company: CSIR</p>
52  * @author tfogwill
53  */

54 public abstract class BaseCoefficientContext implements CoefficientContext {
55
56     public static final String JavaDoc CURRENT_PROJECT = "__current_project__";
57
58     public static final String JavaDoc LAST_NON_HELP_OP = "__last_non_help_op";
59     protected static final String JavaDoc URL_PREFIX = "index.html?module=";
60     
61     /** The page to handle this request */
62     protected Page page_;
63     /** URL to redirect to if set */
64     protected String JavaDoc redirectionURL = null;
65     protected String JavaDoc domain = null;
66     protected String JavaDoc requestURL = null;
67     protected boolean inWorkflowAction = false;
68     protected boolean invalidateSession = false;
69     private CoefficientUser tempUser = null;
70     private CoefficientUser workflowUser = null;
71
72     protected MultipartRequest multipartRequest;
73     protected Map JavaDoc session = new HashMap JavaDoc();
74     protected Map JavaDoc requestData = new HashMap JavaDoc();
75     protected Map JavaDoc requestAttributes = new HashMap JavaDoc();
76     protected Map JavaDoc fileUploadData = new HashMap JavaDoc();
77     protected Cookie[] serializableExistingCookies;
78     protected ArrayList JavaDoc serializableNewCookies = new ArrayList JavaDoc();
79     protected ArrayList JavaDoc removedSessionKeys = new ArrayList JavaDoc();
80     
81     /**
82      * Passthru method to set the error content on the internal Page object
83      *
84      * @param html a String containing the html content defining an error
85      * display
86      */

87     public void setError(String JavaDoc html) {
88         getPage().setError(html);
89     }
90
91     public boolean isError() {
92         return getPage().getErrors()
93             .trim()
94             .length() > 0;
95     }
96
97     public Page getPage() {
98         if (this.page_ == null){
99             try {
100                 createPageObject();
101             } catch (Exception JavaDoc e) {
102                 e.printStackTrace();
103                 throw new RuntimeException JavaDoc("Could not create Page object.", e);
104             }
105         }
106         return page_;
107     }
108
109     public String JavaDoc getTheme() {
110         String JavaDoc theme = (String JavaDoc)getSessionAttribute(Constants.CURRENT_THEME_STRING);
111         return theme;
112     }
113
114     public void setTheme(String JavaDoc theme) {
115         setSessionAttribute(Constants.CURRENT_THEME_STRING, theme);
116     }
117
118     /**
119      * This will forward to the module and perform its main method
120      */

121     public void setForward(String JavaDoc moduleName) throws ConfigurationException {
122         this.setForward(moduleName, null, null);
123     }
124
125     /**
126      * This will forward to the module and perform the method specified by
127      * op and will pass no other parameters
128      */

129     public void setForward(String JavaDoc moduleName, String JavaDoc opName)
130         throws ConfigurationException {
131         this.setForward(moduleName, opName, null);
132     }
133
134     /**
135      * This method is used to force a redirect after the current iteration
136      * of the interceptor chain has completed.
137      *
138      * @param moduleName is the module to forward control to, this must not
139      * be null
140      * @param opName is the operation that the forwarded module should perform
141      * if this value is null then it will use the MainMethod
142      * @param params is a hashmap containing key-value pairs that will be
143      * additional parameters included on the request line to the
144      * specified module. If null no additional parameters will
145      * be sent
146      *
147      * @exception configuationException is thrown if module name is empty
148      * or null
149      */

150     public void setForward(String JavaDoc moduleName, String JavaDoc opName, HashMap JavaDoc params)
151         throws ConfigurationException {
152         if ((moduleName == null) || (moduleName.trim()
153                                      .length() == 0)) {
154             throw new ConfigurationException(
155                                              "You can not forward without providing a module name");
156         }
157         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(URL_PREFIX);
158         sb.append(moduleName);
159         if ((opName != null) && (opName.trim()
160                                  .length() != 0)) {
161             sb.append("&op=")
162                 .append(opName);
163         }
164         if ((params != null) && (params.size() != 0)) {
165             for (Iterator JavaDoc it = params.keySet()
166                      .iterator(); it.hasNext();) {
167                 Object JavaDoc key = it.next();
168                 Object JavaDoc val = params.get(key);
169                 sb.append("&")
170                     .append(key)
171                     .append("=")
172                     .append(val);
173             }
174         }
175         redirectionURL = sb.toString();
176     }
177
178     /**
179      * Passthru method to set the module content on the internal Page object
180      *
181      * @param html a String containing the html content the module wants to
182      * display
183      * @param name is the result of the call to getModuleName on the module
184      * setting the content
185      */

186     public void setModuleContent(String JavaDoc html, String JavaDoc name) throws RuntimeException JavaDoc {
187         try {
188             getPage().setModuleContent(html, name);
189         } catch (Exception JavaDoc e) {
190             throw new RuntimeException JavaDoc();
191         }
192     }
193
194     /**
195      * force a specific theme - used primarily for printing
196      */

197     public void setModuleContent(String JavaDoc html, String JavaDoc name, String JavaDoc theme) throws RuntimeException JavaDoc {
198         try {
199             getPage().setModuleContent(html, name, theme);
200         } catch (Exception JavaDoc e) {
201             throw new RuntimeException JavaDoc();
202         }
203     }
204
205     public String JavaDoc clearModuleContent(String JavaDoc name) {
206         return getPage().clearModuleContent(name);
207     }
208
209     public void setCookie(Cookie cookie) {
210         serializableNewCookies.add(cookie);
211     }
212
213     public Cookie[] getCookies() {
214         return serializableExistingCookies;
215     }
216
217     public BaseMultipartRequest getMultipartRequest() throws FileUploadException {
218         if(this.multipartRequest == null) {
219             throw new RuntimeException JavaDoc("The current request doesn't contain a multipart/form-data or multipart/mixed stream");
220         }
221         return this.multipartRequest;
222     }
223
224     /**
225      * Passthru method to the request object.
226      *
227      * @param name a String containing the paramameter name.
228      * @return a String containing the parameter value.
229      *
230      *
231      * @see #getParameter(String,String) The getParameter() with a default value.
232      *
233      */

234     public String JavaDoc getParameter(String JavaDoc name) {
235
236         String JavaDoc value_str = null;
237         Object JavaDoc value = requestData.get(name);
238         if (value != null) {
239             if (value instanceof String JavaDoc[]) {
240                 value_str = ((String JavaDoc[])value)[0];
241             } else {
242                 value_str = value.toString();
243             }
244         }
245         if ((value_str == null) || value_str.trim() .equals("")) {
246             value = getRequestAttribute(name);
247             if (value != null) {
248                 if (value instanceof String JavaDoc[]) {
249                     value_str = ((String JavaDoc[])value)[0];
250                 } else {
251                     value_str = value.toString();
252                 }
253             }
254         }
255         return value_str;
256     }
257
258     /**
259      * Passthru method to the request object. If request
260      * is null, return an empty array of String.
261      *
262      * @param name a String containing the parameter name.
263      * @return an array of Strings with all values associated
264      *
265      */

266     public String JavaDoc[] getParameterValues(String JavaDoc name) {
267         return getParametersValues(name);
268     }
269
270     public String JavaDoc[] getParametersValues(String JavaDoc name) {
271         Object JavaDoc value = requestData.get(name);
272         if (value != null) {
273             if (value instanceof String JavaDoc[]) {
274                 return (String JavaDoc[])value;
275             } else {
276                 return new String JavaDoc[]{value.toString()};
277             }
278         } else {
279             return new String JavaDoc[0];
280         }
281     }
282
283     /**
284      * Uses bean introspection to set writable properties of bean from the
285      * parameters, where a (case-insensitive) name match between the bean
286      * property and the parameter is looked for
287      *
288      * @param bean an object
289      * @return if true then all properties were successfully set, else some
290      * were not
291      */

292     public boolean setProperties(Object JavaDoc bean) {
293         boolean complete = true;
294         try {
295             Class JavaDoc beanClass = bean.getClass();
296             Map JavaDoc params = new HashMap JavaDoc();
297             for (Iterator JavaDoc e = requestData.keySet().iterator(); e.hasNext();) {
298                 String JavaDoc name = (String JavaDoc) e.next();
299                 String JavaDoc value = getParameter(name);
300                 params.put(name, value);
301             }
302             PropertyDescriptor JavaDoc[] props =
303                 Introspector.getBeanInfo(beanClass).getPropertyDescriptors();
304
305             for (int i = 0; i < props.length; i++) {
306                 String JavaDoc propname = props[i].getName();
307                 Method JavaDoc setter = props[i].getWriteMethod();
308                 if ((setter != null) && (params.containsKey(propname))) {
309                     try {
310                         setProperty(bean, props[i]);
311                     } catch (Exception JavaDoc e) {
312                         e.printStackTrace();
313                         complete = false;
314                     }
315                 }
316             }
317         } catch (Exception JavaDoc e) {
318             // swallow all exceptions, just populate what you can
319
complete = false;
320         }
321         return complete;
322     }
323
324     public void setRequestAttribute(String JavaDoc name, Object JavaDoc value) {
325         requestAttributes.put(name, value);
326     }
327
328     public Object JavaDoc getRequestAttribute(String JavaDoc name) {
329         return requestAttributes.get(name);
330     }
331
332     public void setSessionAttribute(String JavaDoc name, Object JavaDoc value) {
333         session.put(name, value);
334     }
335
336     public Object JavaDoc getSessionAttribute(String JavaDoc name) {
337         return session.get(name);
338     }
339
340     public void removeRequestAttribute(String JavaDoc name) {
341         requestAttributes.remove(name);
342     }
343
344     public void removeSessionAttribute(String JavaDoc name) {
345         session.remove(name);
346         removedSessionKeys.add(name);
347     }
348     
349     /**
350      * Passthru method to the request object.
351      *
352      * @param name a String with the name of the parameter
353      * @param defaultValue if no parameter with that name is defined
354      * the return value is the defaultValue
355      * @return a String with the parameter value or
356      * the default value.
357      */

358     public String JavaDoc getParameter(String JavaDoc name, String JavaDoc defaultValue) {
359         String JavaDoc value = getParameter(name);
360
361         return (value != null) ? value : defaultValue;
362     }
363
364     public boolean getParameterAsBoolean(String JavaDoc name) {
365         String JavaDoc val = getParameter(name);
366         if("on".equals(val)) {
367             val = "true";
368         }
369         return Boolean.valueOf(val).booleanValue();
370     }
371
372     public Date JavaDoc getParameterAsDate(String JavaDoc name) {
373         Date JavaDoc retVal = null;
374         try {
375             java.text.SimpleDateFormat JavaDoc df =
376                 new java.text.SimpleDateFormat JavaDoc(Constants.SYSTEM_DATE_FORMAT);
377             df.setLenient(false);
378             retVal = df.parse(getParameter(name, ""));
379         } catch (java.text.ParseException JavaDoc e) {
380             // do nothing
381
}
382
383         return retVal;
384     }
385
386     public Double JavaDoc getParameterAsDouble(String JavaDoc name, double defaultValue) {
387         Double JavaDoc value = getParameterAsDouble(name);
388
389         return (value != null) ? value : new Double JavaDoc(defaultValue);
390     }
391
392     public Double JavaDoc getParameterAsDouble(String JavaDoc name) {
393         String JavaDoc value = getParameter(name);
394         try {
395             return (value != null) ? new Double JavaDoc(value) : null;
396         } catch (NumberFormatException JavaDoc e) {
397             return null;
398         }
399     }
400
401     public double getParameterAsDoublePrimitive(String JavaDoc name, double defaultValue) {
402         return getParameterAsDouble(name, defaultValue)
403             .doubleValue();
404     }
405
406     public int getParameterAsInt(String JavaDoc name, int defaultValue) {
407         return getParameterAsInteger(name, defaultValue)
408             .intValue();
409     }
410
411     public Integer JavaDoc getParameterAsInteger(String JavaDoc name, int defaultValue) {
412         Integer JavaDoc value = getParameterAsInteger(name);
413
414         return (value != null) ? value : new Integer JavaDoc(defaultValue);
415     }
416
417     public Integer JavaDoc getParameterAsInteger(String JavaDoc name) {
418         String JavaDoc value = getParameter(name);
419         try {
420             return (value != null) ? new Integer JavaDoc(value) : null;
421         } catch (NumberFormatException JavaDoc e) {
422             return null;
423         }
424     }
425
426     public Long JavaDoc getParameterAsLong(String JavaDoc name, long defaultValue) {
427         Long JavaDoc value = getParameterAsLong(name);
428
429         return (value != null) ? value : new Long JavaDoc(defaultValue);
430     }
431
432     public Long JavaDoc getParameterAsLong(String JavaDoc name) {
433         String JavaDoc value = getParameter(name);
434         try {
435             return (value != null) ? new Long JavaDoc(value) : null;
436         } catch (NumberFormatException JavaDoc e) {
437             return null;
438         }
439     }
440
441     public long getParameterAsLongPrimitive(String JavaDoc name, long defaultValue) {
442         return getParameterAsLong(name, defaultValue)
443             .longValue();
444     }
445
446     /**
447      * Method to the request values as longs.
448      * @param name a String containing the parameter name.
449      * @return an array of Longs with all values associated
450      *
451      */

452     public Long JavaDoc[] getParameterValuesLong(String JavaDoc name) {
453         String JavaDoc[] vals = getParameterValues(name);
454         if (vals != null) {
455             Long JavaDoc[] retVals = new Long JavaDoc[vals.length];
456             for (int i = 0; i < vals.length; i++) {
457                 try {
458                     retVals[i] = (vals[i] != null) ? new Long JavaDoc(vals[i]) : null;
459                 } catch (NumberFormatException JavaDoc e) {
460                     retVals[i] = null;
461                 }
462             }
463
464             return retVals;
465         } else {
466             return new Long JavaDoc[0];
467         }
468     }
469
470
471     public UploadedFile getUploadedFile(String JavaDoc name) throws FileUploadException {
472         return (getMultipartRequest()).getFileParameter(name);
473     }
474
475     public void setWorkflowUser(CoefficientUser workflowUser) {
476         this.workflowUser = workflowUser;
477     }
478
479     /**
480      * This is used to do anything that needs doing for a workflow action
481      * to succeed
482      */

483     public void beginWorkflowAction() {
484         if (!inWorkflowAction) {
485             tempUser = getCurrentUser();
486             if (workflowUser != null) {
487                 setSessionAttribute(Constants.USER_SESSION_STRING, workflowUser);
488             }
489             inWorkflowAction = true;
490         }
491     }
492     
493     /**
494      * This should reset the state if need be
495      */

496     public void endWorkflowAction() {
497         if (inWorkflowAction) {
498             setSessionAttribute(Constants.USER_SESSION_STRING, tempUser);
499             try {
500                 clearPage();
501             } catch (IOException JavaDoc ioex) {
502                 // just let it go
503
}
504             inWorkflowAction = false;
505         }
506     }
507
508     public String JavaDoc getLastNonHelpOp() {
509         return (String JavaDoc)getSessionAttribute(LAST_NON_HELP_OP);
510     }
511
512     public void setProject(Project project) {
513         this.session.put(CURRENT_PROJECT, project);
514     }
515
516     public Project getProject() {
517         return (Project)this.session.get(CURRENT_PROJECT);
518     }
519
520     public void invalidateSession() {
521         session.clear();
522         invalidateSession = true;
523     }
524
525     /**
526      * If a user is logged in this will return that user otherwise it will
527      * return null
528      *
529      * @return the logged in user or null if not logged in
530      */

531     public CoefficientUser getCurrentUser() {
532         return (CoefficientUser) getSessionAttribute(Constants.USER_SESSION_STRING);
533     }
534     
535     public String JavaDoc getRequestURL() {
536         return requestURL;
537     }
538
539     /**
540      * Set the property 'prop' in the bean to the value of the
541      * corresponding parameters. Supports all types supported by
542      * getXXX methods plus a few more that come for free because
543      * primitives have to be wrapped before being passed to invoke
544      * anyway.
545      *
546      * @param bean An Object.
547      * @param prop A PropertyDescriptor.
548      * @exception Exception a generic exception.
549      */

550     protected void setProperty(Object JavaDoc bean, PropertyDescriptor JavaDoc prop)
551         throws Exception JavaDoc {
552         if (prop instanceof IndexedPropertyDescriptor JavaDoc) {
553             throw new Exception JavaDoc(prop.getName()
554                                 + " is an indexed property (not supported)");
555         }
556
557         Method JavaDoc setter = prop.getWriteMethod();
558         if (setter == null) {
559             throw new Exception JavaDoc(prop.getName() + " is a read only property");
560         }
561
562         Class JavaDoc propclass = prop.getPropertyType();
563         Object JavaDoc[] args = { null };
564
565         if (propclass == String JavaDoc.class) {
566             args[0] = getParameter(prop.getName());
567         } else if ((propclass == Integer JavaDoc.class) || (propclass == Integer.TYPE)) {
568             args[0] = getParameterAsInteger(prop.getName());
569         } else if ((propclass == Long JavaDoc.class) || (propclass == Long.TYPE)) {
570             args[0] = getParameterAsLong(prop.getName());
571         } else if ((propclass == Boolean JavaDoc.class) || (propclass == Boolean.TYPE)) {
572             args[0] = new Boolean JavaDoc(getParameterAsBoolean(prop.getName()));
573         } else if ((propclass == Double JavaDoc.class) || (propclass == Double.TYPE)) {
574             args[0] = getParameterAsDouble(prop.getName());
575         } else if (propclass == String JavaDoc[].class) {
576             args[0] = getParameterValues(prop.getName());
577         } else if (propclass == Object JavaDoc.class) {
578             args[0] = getParameter(prop.getName());
579         } else if (propclass == Date JavaDoc.class) {
580             args[0] = getParameterAsDate(prop.getName());
581         } else if (propclass == java.util.Locale JavaDoc.class) {
582             args[0] = new java.util.Locale JavaDoc(getParameter(prop.getName()));
583         } else if (propclass == java.util.TimeZone JavaDoc.class) {
584             args[0] =
585                 java.util.TimeZone.getTimeZone(getParameter(prop.getName()));
586         } else {
587             throw new Exception JavaDoc("property " + prop.getName()
588                                 + " is of unsupported type " + propclass.toString());
589         }
590
591         setter.invoke(bean, args);
592     }
593
594     protected void clearPage() throws IOException JavaDoc {
595         createPageObject();
596         this.redirectionURL = null;
597     }
598
599     /*
600      * @see za.org.coefficient.core.BaseCoefficientContext#createPageObject()
601      */

602     protected void createPageObject() throws IOException JavaDoc{
603         this.page_ = new Page(this);
604     }
605
606     private String JavaDoc getCallerClassName() {
607         StackTraceElement JavaDoc[] ste = new Exception JavaDoc().getStackTrace();
608         if ((ste == null) || (ste.length < 3)) {
609             return null;
610         } else {
611             return ste[2].getClassName();
612         }
613     }
614     
615 }
616
Popular Tags