KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > infoglue > cms > applications > workflowtool > util > InfoglueWorkflowBase


1 /* ===============================================================================
2  *
3  * Part of the InfoGlue Content Management Platform (www.infoglue.org)
4  *
5  * ===============================================================================
6  *
7  * Copyright (C)
8  *
9  * This program is free software; you can redistribute it and/or modify it under
10  * the terms of the GNU General Public License version 2, as published by the
11  * Free Software Foundation. See the file LICENSE.html for more information.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
19  * Place, Suite 330 / Boston, MA 02111-1307 / USA.
20  *
21  * ===============================================================================
22  */

23 package org.infoglue.cms.applications.workflowtool.util;
24
25 import java.util.Collections JavaDoc;
26 import java.util.Map JavaDoc;
27
28 import org.apache.log4j.Logger;
29 import org.exolab.castor.jdo.Database;
30 import org.infoglue.cms.util.workflow.DatabaseSession;
31
32 import com.opensymphony.module.propertyset.PropertySet;
33 import com.opensymphony.provider.BeanProvider;
34 import com.opensymphony.provider.bean.DefaultBeanProvider;
35 import com.opensymphony.workflow.WorkflowException;
36 //import com.opensymphony.workflow.util.ScriptVariableParser;
37

38 /**
39  * Base class containing logic used by both <code>InfoglueFunction</code> and <code>InfoglueCondition</code>.
40  * The main purpose of this class is to provide convenience methods for the parameters, arguments, and propertyset objects
41  * and to handle the <code>DatabaseSession</code> object.
42  */

43 public abstract class InfoglueWorkflowBase
44 {
45     /**
46      * The class logger.
47      */

48     private final static Logger logger = Logger.getLogger(InfoglueWorkflowBase.class.getName());
49     
50     /**
51      * The default encoding.
52      */

53     protected static final String JavaDoc UTF8_ENCODING = "utf-8";
54     
55     /**
56      * The prefix for all keys representing workflow specific information in the propertyset.
57      */

58     public static final String JavaDoc WORKFLOW_PROPERTYSET_PREFIX = "workflow_";
59     
60     /**
61      * The key used for storing the function status in the propertyset.
62      */

63     public static final String JavaDoc FUNCTION_STATUS_PROPERTYSET_KEY = WORKFLOW_PROPERTYSET_PREFIX + "status";
64
65     /**
66      * The prefix for all keys representing errors in the propertyset.
67      */

68     public static final String JavaDoc ERROR_PROPERTYSET_PREFIX = "error_";
69
70     /**
71      * The key used by the <code>DatabaseSession</code> in the <code>parameters</code>.
72      */

73     private static final String JavaDoc DB_PARAMETER = "db";
74     
75     /**
76      * The parameters (transient variables) of the current execution context.
77      */

78     private Map JavaDoc parameters;
79     
80     /**
81      * The arguments passed to the function.
82      */

83     private Map JavaDoc arguments;
84     
85     /**
86      * The propertyset associated with the current workflow.
87      */

88     private InfogluePropertySet propertySet;
89
90     /**
91      * The database associated with the current execution.
92      */

93     private DatabaseSession workflowDatabase;
94     
95     /**
96      * If <code>throwException</code> is used inside both <code>try</code> and <code>catch</catch>
97      * then it will be logged twice. To get ride of this, the lastException is tracked.
98      */

99     private Exception JavaDoc lastException;
100     
101     /**
102      * Default constructor.
103      */

104     public InfoglueWorkflowBase()
105     {
106         super();
107     }
108
109     /**
110      * Method used for initializing the object; will be called before any execution is performed.
111      * <p><strong>Note</strong>! You must call <code>super.initialize()</code> first.</p>
112      *
113      * @throws WorkflowException if an error occurs during the initialization.
114      */

115     protected void initialize() throws WorkflowException
116     {
117         workflowDatabase = (DatabaseSession) getParameter(DB_PARAMETER);
118     }
119     
120     /**
121      * Stores the execution context.
122      *
123      * @param transientVars the transient variables of the current execution context.
124      * @param args the arguments of the function.
125      * @param ps the propertyset associated with the current workflow.
126      */

127     protected void storeContext(final Map JavaDoc transientVars, final Map JavaDoc args, final PropertySet ps)
128     {
129         this.parameters = transientVars;
130         this.arguments = Collections.unmodifiableMap(args);
131         this.propertySet = new InfogluePropertySet(ps);
132     }
133     
134     /**
135      * The preferred way to throw an exception from a subclass.
136      * Logs the error, sets the mode of the database to rollback only and throws an exception.
137      *
138      * @param message the exception message.
139      * @throws WorkflowException always throws an exception with the specified message.
140      */

141     protected void throwException(final String JavaDoc message) throws WorkflowException
142     {
143         throwException(new WorkflowException(message));
144     }
145     
146     /**
147      * The preferred way to throw an exception from a subclass.
148      * Logs the error, sets the mode of the database to rollback only and throws an exception.
149      *
150      * @param e the exception to chain.
151      * @throws WorkflowException always throws an exception. If the specified exception is a
152      * workflow exception, that exception is thrown. Otherwise a chained workflow exception is thrown.
153      */

154     protected void throwException(final Exception JavaDoc e) throws WorkflowException
155     {
156         if(lastException != e)
157         {
158             logger.error(e.getMessage(), e);
159         }
160         lastException = e;
161         workflowDatabase.setRollbackOnly();
162         throw (e instanceof WorkflowException) ? (WorkflowException) e : new WorkflowException(e);
163     }
164     
165     /**
166      * Returns true if the specified argument exists; false otherwise.
167      *
168      * @param name the name of the argument.
169      * @return true if the specified argument exists; false otherwise.
170      */

171     protected final boolean argumentExists(final String JavaDoc name)
172     {
173         return arguments.containsKey(name);
174     }
175     
176     /**
177      * Returns the specified argument if it exists; otherwise an exception is thrown.
178      * Only use this method if the argument is absolutely required.
179      *
180      * @param name the name of the argument.
181      * @return the specified argument.
182      * @throws WorkflowException if the specified argument doesn't exists.
183      */

184     protected final String JavaDoc getArgument(final String JavaDoc name) throws WorkflowException
185     {
186         if(!arguments.containsKey(name))
187         {
188             throwException("Required argument " + name + " is missing.");
189         }
190         return arguments.get(name).toString();
191     }
192     
193     /**
194      * Returns the specified argument if it exists; otherwise the default value.
195      *
196      * @param name the name of the argument.
197      * @param defaultValue the default value.
198      * @return the specified argument if it exists; otherwise the default value.
199      */

200     protected final String JavaDoc getArgument(final String JavaDoc name, final String JavaDoc defaultValue) throws WorkflowException
201     {
202         return arguments.containsKey(name) ? arguments.get(name).toString() : defaultValue;
203     }
204     
205     /**
206      * Returns true if the specified parameter exists; false otherwise.
207      *
208      * @param name the name of the parameter.
209      * @return true if the specified parameter exists; false otherwise.
210      */

211     protected final boolean parameterExists(final String JavaDoc key)
212     {
213         return parameters.containsKey(key);
214     }
215     
216     /**
217      * Returns the specified parameter if it exists; otherwise an exception is thrown.
218      * Only use this method if the parameter is absolutely required.
219      *
220      * @param name the name of the parameter.
221      * @return the specified parameter.
222      * @throws WorkflowException if the specified parameter doesn't exists.
223      */

224     protected final Object JavaDoc getParameter(final String JavaDoc key) throws WorkflowException
225     {
226         return getParameter(key, true);
227     }
228     
229     /**
230      * Returns the specified parameter if it exists; otherwise the default value.
231      *
232      * @param name the name of the parameter.
233      * @param defaultValue the default value.
234      * @return the specified parameter if it exists; otherwise the default value.
235      */

236     protected final Object JavaDoc getParameter(final String JavaDoc key, final Object JavaDoc defaultValue) throws WorkflowException
237     {
238         return parameters.containsKey(key) ? parameters.get(key) : defaultValue;
239     }
240     
241     /**
242      * Returns the specified parameter. If the parameter is required and not found, an exception is thrown.
243      *
244      * @param key the key.
245      * @param required indicates if the parameter is required.
246      * @return the specified parameter.
247      * @throws WorkflowException if a required parameter is missing.
248      */

249     protected final Object JavaDoc getParameter(final String JavaDoc key, final boolean required) throws WorkflowException
250     {
251         final Object JavaDoc parameter = parameters.get(key);
252         if(required && parameter == null)
253         {
254             final WorkflowException e = new WorkflowException("Required parameter " + key + " is missing.");
255             logger.error(e.toString());
256             throw e;
257         }
258         return parameter;
259     }
260     
261     /**
262      * Stores the specified parameter.
263      *
264      * @param key the lookup key.
265      * @param value the value.
266      */

267     protected final void setParameter(final String JavaDoc key, final Object JavaDoc value)
268     {
269         parameters.put(key, value);
270     }
271     
272     /**
273      * Returns the parameters (transient variables) of the current execution context.
274      *
275      * @return the parameters (transient variables) of the current execution context.
276      */

277     protected final Map JavaDoc getParameters()
278     {
279         return parameters;
280     }
281     
282     /**
283      * Returns true if the specified property exists; false otherwise.
284      *
285      * @return true if the specified property exists; false otherwise.
286      */

287     protected final boolean propertySetContains(final String JavaDoc key)
288     {
289         return propertySet.exists(key);
290     }
291     
292     /**
293      * Returns the specified data property as a string.
294      *
295      * @param key the key.
296      */

297     protected final String JavaDoc getPropertySetDataString(final String JavaDoc key)
298     {
299         return propertySet.getDataString(key);
300     }
301     
302     /**
303      * Stores the specified data property.
304      *
305      * @param key the key.
306      * @param value the value.
307      */

308     protected final void setPropertySetDataString(final String JavaDoc key, final String JavaDoc value)
309     {
310         propertySet.setDataString(key, value);
311     }
312     
313     /**
314      * Returns the specified string property.
315      *
316      * @param key the key.
317      */

318     protected final String JavaDoc getPropertySetString(final String JavaDoc key)
319     {
320         return propertySet.getString(key);
321     }
322     
323     /**
324      * Stores the specified string property.
325      *
326      * @param key the key.
327      * @param value the value.
328      */

329     protected final void setPropertySetString(final String JavaDoc key, final String JavaDoc value)
330     {
331         propertySet.setString(key, value);
332     }
333     
334     /**
335      * Removes the property with the specified key from the propertyset.
336      *
337      * @param key the property key.
338      */

339     protected final void removeFromPropertySet(final String JavaDoc key)
340     {
341         removeFromPropertySet(key, false);
342     }
343     
344     /**
345      * Removes the property with the specified key from the propertyset.
346      * If key is a prefix, all properties having keys starting with the specified key
347      * will be removed.
348      *
349      * @param key the property key.
350      * @param isPrefix indicates if the key should be used as key prefix.
351      */

352     protected final void removeFromPropertySet(final String JavaDoc key, final boolean isPrefix)
353     {
354         propertySet.removeKeys(key, isPrefix);
355     }
356
357     /**
358      *
359      */

360     
361     protected final String JavaDoc translate(final String JavaDoc s)
362     {
363         final Object JavaDoc o = translateVariables(s, parameters, propertySet);
364         return (o == null) ? null : o.toString();
365     }
366     
367     /**
368      * Returns the propertyset associated with the current workflow.
369      *
370      * @return the propertyset associated with the current workflow.
371      */

372     protected final InfogluePropertySet getPropertySet()
373     {
374         return propertySet;
375     }
376         
377     /**
378      * Returns the database associated with the current execution.
379      *
380      * @return the database associated with the current execution.
381      * @throws WorkflowException if an error occurs when opening/starting the database/transaction.
382      */

383     protected final Database getDatabase() throws WorkflowException
384     {
385         return workflowDatabase.getDB();
386     }
387     
388     /**
389      * Parses a string for instances of "${foo}" and returns a string with all instances replaced
390      * with the string value of the foo object (<b>foo.toString()</b>). If the string being passed
391      * in only refers to a single variable and contains no other characters (for example: ${foo}),
392      * then the actual object is returned instead of converting it to a string.
393      */

394   public static Object JavaDoc translateVariables(String JavaDoc s, Map JavaDoc transientVars, PropertySet ps)
395   {
396       Object JavaDoc result = null;
397       
398       String JavaDoc temp = s.trim();
399
400       if (temp.startsWith("${") && temp.endsWith("}") && (temp.indexOf('$', 1) == -1))
401       {
402           // the string is just a variable reference, don't convert it to a string
403
String JavaDoc var = temp.substring(2, temp.length() - 1);
404
405           result = getVariableFromMaps(var, transientVars, ps);
406       }
407       else
408       {
409           // the string passed in contains multiple variables (or none!) and should be treated as a string
410
while (true)
411           {
412               int x = s.indexOf("${");
413               int y = s.indexOf("}", x);
414
415               if ((x != -1) && (y != -1))
416               {
417                   String JavaDoc var = s.substring(x + 2, y);
418                   String JavaDoc t = null;
419                   Object JavaDoc o = getVariableFromMaps(var, transientVars, ps);
420
421                   if (o != null)
422                   {
423                       t = o.toString();
424                   }
425
426                   if (t != null)
427                   {
428                       s = s.substring(0, x) + t + s.substring(y + 1);
429                   }
430                   else
431                   {
432                       // the variable doesn't exist, so don't display anything
433
s = s.substring(0, x) + s.substring(y + 1);
434                   }
435               }
436               else
437               {
438                   break;
439               }
440           }
441
442           result = s;
443       }
444       
445       return result;
446   }
447   
448   private static BeanProvider beanProvider = new DefaultBeanProvider();
449
450   //~ Methods ////////////////////////////////////////////////////////////////
451

452   public static Object JavaDoc getVariableFromMaps(String JavaDoc var, Map JavaDoc transientVars, PropertySet ps) {
453       int firstDot = var.indexOf('.');
454       String JavaDoc actualVar = var;
455
456       if (firstDot != -1) {
457           actualVar = var.substring(0, firstDot);
458       }
459
460       Object JavaDoc o = transientVars.get(actualVar);
461
462       if (o == null) {
463           o = ps.getAsActualType(actualVar);
464       }
465
466       if (firstDot != -1) {
467           o = beanProvider.getProperty(o, var.substring(firstDot + 1));
468       }
469
470       return o;
471   }
472 }
473
Popular Tags