KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > pentaho > plugin > misc > UtilityComponent


1 /*
2  * Copyright 2006 Pentaho Corporation. All rights reserved.
3  * This software was developed by Pentaho Corporation and is provided under the terms
4  * of the Mozilla Public License, Version 1.1, or any later version. You may not use
5  * this file except in compliance with the license. If you need a copy of the license,
6  * please go to http://www.mozilla.org/MPL/MPL-1.1.txt. The Original Code is the Pentaho
7  * BI Platform. The Initial Developer is Pentaho Corporation.
8  *
9  * Software distributed under the Mozilla Public License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
11  * the license for the specific language governing your rights and limitations.
12  *
13  * @created Jun 24, 2005
14  * @author Doug Moran
15  */

16
17 package org.pentaho.plugin.misc;
18
19 import java.text.MessageFormat JavaDoc;
20 import java.util.ArrayList JavaDoc;
21 import java.util.HashMap JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.List JavaDoc;
24 import java.util.Map JavaDoc;
25 import java.util.Set JavaDoc;
26 import org.apache.commons.logging.Log;
27 import org.apache.commons.logging.LogFactory;
28 import org.dom4j.Node;
29 import org.pentaho.messages.Messages;
30 import org.pentaho.plugin.ComponentBase;
31
32 /**
33  *
34  * Provides utilities to help manipulate parameters used in action sequences.
35  * <p>
36  * <ul>
37  * <li><i>format</i> - Java style message formatting</li>
38  * <li><i>getvalues</i> - Make the key value pairs from a property map
39  * available as action-outputs</li>
40  * <li><i>copy</i> - Set the action-output with the value of the action input</li>
41  * <li><i>tostring</i> - Sets the action-output to the string value of the
42  * action-input</li>
43  * <li><i></i> - </li>
44  */

45 public class UtilityComponent extends ComponentBase {
46
47     /**
48      *
49      */

50     private static final long serialVersionUID = -3257037449482351540L;
51
52     List JavaDoc commandList = new ArrayList JavaDoc();
53
54     HashMap JavaDoc tmpOutputs = new HashMap JavaDoc();
55
56     /*
57      * (non-Javadoc)
58      *
59      * @see org.pentaho.component.ComponentBase#validate()
60      */

61
62     public Log getLogger() {
63         return LogFactory.getLog(UtilityComponent.class);
64     }
65
66     protected boolean validateSystemSettings() {
67         // This component does not have any system settings to validate
68
return true;
69     }
70
71     protected boolean validateAction() {
72         boolean hasError = false;
73         commandList = new ArrayList JavaDoc();
74
75         Node componentNode = getComponentDefinition();
76         List JavaDoc commandNodes = componentNode.selectNodes("*"); //$NON-NLS-1$
77

78         for (Iterator JavaDoc it = commandNodes.iterator(); it.hasNext();) {
79             Node commandNode = (Node) it.next();
80             UtilityBase command = utilityFactory(commandNode);
81             if ((command != null) && command.validate(commandNode)) {
82                 commandList.add(command);
83             } else {
84                 hasError = true;
85             }
86         }
87
88         return (!hasError);
89     }
90
91     /*
92      * (non-Javadoc)
93      *
94      * @see org.pentaho.component.ComponentBase#done()
95      */

96     public void done() {
97
98     }
99
100     /*
101      * (non-Javadoc)
102      *
103      * @see org.pentaho.component.ComponentBase#execute()
104      */

105     protected boolean executeAction() {
106         tmpOutputs = new HashMap JavaDoc(); // Make sure we start with an empty list in
107
// this iteration
108
try {
109             for (Iterator JavaDoc it = commandList.iterator(); it.hasNext();) {
110                 UtilityBase ud = (UtilityBase) it.next();
111                 if (debug)
112                     debug("Executing Utility - " + ud.getCommandName()); //$NON-NLS-1$
113
if (!ud.execute()) {
114                     return (false);
115                 }
116             }
117
118             Set JavaDoc outNames = getOutputNames();
119             for (Iterator JavaDoc it = outNames.iterator(); it.hasNext();) {
120                 String JavaDoc name = (String JavaDoc) it.next();
121                 Object JavaDoc value = tmpOutputs.get(name);
122                 if (value != null) {
123                     setOutputValue(name, value);
124                 }
125             }
126
127             return (true);
128         } finally {
129             tmpOutputs = null; // GC temp data
130
}
131     }
132
133     /*
134      *
135      * if ( "format".equals( test ) ) { //$NON-NLS-1$ } else { Object p1 =
136      * getParamFromComponentNode( "p1", componentNode ); //$NON-NLS-1$ if ( p1 ==
137      * null ) { return( false ); } else if ( "toupper".equals( test ) ) {
138      * //$NON-NLS-1$
139      *
140      * theResult = p1.toString().toUpperCase(); } else if ( "rename".equals(
141      * test ) ) { //$NON-NLS-1$ theResult = p1; }
142      *
143      * else if ( "map2params".equals( test ) ) { //$NON-NLS-1$
144      *
145      * if ( !(p1 instanceof Map) ) { error(
146      * Messages.getErrorString("TestComponent.ERROR_0003_PARAMETER_NOT_MAP",
147      * "p1" ) ); //$NON-NLS-1$ //$NON-NLS-2$ return( false ); }
148      *
149      * Map srcMap = (Map)p1; for ( Iterator it = srcMap.keySet().iterator();
150      * it.hasNext(); ) { String key = it.next().toString();
151      * context.setOutputValue( key, srcMap.get( key ) ); } } else if (
152      * "print".equals( test ) ) { //$NON-NLS-1$ } else if ( "getkeys".equals(
153      * test ) ) { //$NON-NLS-1$
154      *
155      * if ( !(p1 instanceof Map) ) { error(
156      * Messages.getErrorString("TestComponent.ERROR_0003_PARAMETER_NOT_MAP",
157      * "p1" ) ); //$NON-NLS-1$ //$NON-NLS-2$ return( false ); } theResult = new
158      * ArrayList( ((Map)p1).keySet() ); } else {
159      *
160      * Object p2 = getParamFromComponentNode( "p2", componentNode );
161      * //$NON-NLS-1$ if ( p2 == null ) { return( false ); }
162      *
163      * if ( "concat".equals( test ) ) { //$NON-NLS-1$ theResult = p1.toString() +
164      * p2.toString(); } else if ( "print2".equals( test ) ) { //$NON-NLS-1$
165      *
166      * String delim = Messages.getString("TestComponent.PRINT_DELIM");
167      * //$NON-NLS-1$ theResult = delim + p1.toString() + " - " + p2.toString() +
168      * delim; //$NON-NLS-1$ } else {
169      *
170      * Object p3 = getParamFromComponentNode( "p3", componentNode );
171      * //$NON-NLS-1$ if ( p3 == null ) { return( false ); }
172      *
173      * if ( "merge".equals( test ) ) { //$NON-NLS-1$ // merge cycles through
174      * each property map in list p2. For each map, it cycles through the keys in
175      * map p1 and compares the key name // from p1 with a value from p2. p3
176      * specifies the key in p2 to compare with. When a match is found, an entry
177      * is added to an output // output list that is identical to the map from
178      * p2. The value specified by the key in p1 will be added to the output
179      * under the key "NewKey"
180      *
181      * if ( !(p1 instanceof Map) || !(p2 instanceof List) || !(p3 instanceof
182      * String) ) { error(
183      * Messages.getErrorString("TestComponent.ERROR_0003_P1_P2_WRONG_TYPE") );
184      * //$NON-NLS-1$ return( false ); }
185      *
186      * theResult = merge( (Map)p1, (List)p2, (String)p3 ); } else { message(
187      * Messages.getString("TestComponent.ERROR_0001_TEST_NODE_NOT_FOUND") );
188      * //$NON-NLS-1$ return false; } } } }
189      *
190      * if ( newName != null ) { message( newName + " = " + theResult );
191      * //$NON-NLS-1$ try { context.setOutputValue( newName, theResult ); } catch
192      * (Exception e ){} //setOutputValue logs an error mesage } else { message(
193      * "The result = " + theResult ); //$NON-NLS-1$ }
194      *
195      *
196      * return( true ); }
197      */

198
199     /*
200      * (non-Javadoc)
201      *
202      * @see org.pentaho.component.ComponentBase#init()
203      */

204     public boolean init() {
205         if (debug)
206             debug(Messages.getString("TestComponent.DEBUG_INITIALIZING_TEST")); //$NON-NLS-1$
207
return true;
208     }
209
210     protected Object JavaDoc getActionParameterValue(String JavaDoc name) {
211         try {
212             return (getInputValue(name));
213         } catch (Exception JavaDoc e) {
214         } // Return null if it doesn't exist
215

216         return (null);
217     }
218
219     /*
220      * private List merge( Map hm, List list, String keyName ) { ArrayList al =
221      * new ArrayList(); for ( Iterator it = list.iterator(); it.hasNext(); ) {
222      * Object item = it.next(); if ( item instanceof Map ) { Map resMap = merge(
223      * hm, (Map)item, keyName ); if ( resMap != null ) { al.add( resMap ); } } }
224      * return( al ); }
225      *
226      * private Map merge( Map srcMap, Map destMap, String keyName ) { Object
227      * keyValue = destMap.get( keyName ); Map rtnMap = null; for ( Iterator it =
228      * srcMap.keySet().iterator(); it.hasNext(); ) { String key =
229      * it.next().toString(); if ( (keyValue != null) && key.equalsIgnoreCase(
230      * keyValue.toString() ) ) { rtnMap = new HashMap( destMap ); rtnMap.put(
231      * "NewKey", srcMap.get( key ) ); //$NON-NLS-1$ return( rtnMap ); } }
232      *
233      * return( rtnMap ); }
234      *
235      *
236      * private Object getParamFromComponentNode( String paramName, Node
237      * componentNode ) { String param = XmlHelper.getNodeText( paramName,
238      * componentNode ); if ( (param == null) || (param.length() < 1) ) { error(
239      * Messages.getErrorString("TestComponent.ERROR_0002_PARAMETER_MISSING",
240      * paramName ) ); //$NON-NLS-1$ return( null ); } return(
241      * getActionParameterValue( param ) ); }
242      */

243     private UtilityBase utilityFactory(Node commandNode) {
244
245         String JavaDoc commandName = commandNode.getName();
246         if ((commandName == null) || (commandName.length() < 1)) {
247             error(Messages.getErrorString("UtilityComponent.ERROR_0006_NO_COMMAND")); //$NON-NLS-1$
248
return (null);
249         }
250
251         if ("format".equalsIgnoreCase(commandName)) { //$NON-NLS-1$
252
return (new FormatUtil());
253         }
254
255         if ("print".equalsIgnoreCase(commandName)) { //$NON-NLS-1$
256
return (new PrintUtil());
257         }
258
259         if ("copy".equalsIgnoreCase(commandName)) { //$NON-NLS-1$
260
return (new CopyUtil());
261         }
262
263         if ("getmapvalues".equalsIgnoreCase(commandName)) { //$NON-NLS-1$
264
return (new GetMapValues());
265         }
266
267         error(Messages.getErrorString("UtilityComponent.ERROR_0007_UNKNOWN_COMMAND", commandName)); //$NON-NLS-1$
268
return (null);
269     }
270
271     abstract class UtilityBase {
272         String JavaDoc commandName;
273
274         HashMap JavaDoc parameterMap;
275
276         HashMap JavaDoc parameterListMap;
277
278         public UtilityBase(String JavaDoc commandName) {
279             this.commandName = commandName;
280             parameterMap = new HashMap JavaDoc();
281             parameterListMap = new HashMap JavaDoc();
282         }
283
284         /**
285          * Adds a passed parameter to the list of parameters for this command.
286          *
287          * @param paramNode
288          * @return The String value of the parameter name or "" if null
289          */

290         boolean addParameter(String JavaDoc paramName, Node cmdNode, boolean required) {
291             Node paramNode = cmdNode.selectSingleNode(paramName);
292             if (paramNode == null) {
293                 if (required) {
294                     error(Messages.getErrorString("TestComponent.ERROR_0002_PARAMETER_MISSING", paramName)); //$NON-NLS-1$
295
return (false);
296                 }
297                 return (true);
298             }
299
300             String JavaDoc paramValue = paramNode.getText();
301
302             if (paramValue.startsWith("\"") && paramValue.endsWith("\"")) { //$NON-NLS-1$ //$NON-NLS-2$
303
parameterMap.put(paramName, paramValue);
304             } else {
305                 parameterMap.put(paramName, paramValue);
306             }
307             return (true);
308         }
309
310         int addParameterList(String JavaDoc paramName, Node cmdNode, int minReqd) {
311             List JavaDoc paramList = cmdNode.selectNodes(paramName);
312             if (paramList.size() < minReqd) {
313                 error(Messages.getErrorString("TestComponent.ERROR_0003_PARAMETER_MISSING", paramName, String.valueOf(minReqd), String.valueOf(paramList.size()))); //$NON-NLS-1$
314
}
315
316             ArrayList JavaDoc al = new ArrayList JavaDoc();
317             for (Iterator JavaDoc it = paramList.iterator(); it.hasNext();) {
318                 al.add(((Node) it.next()).getText());
319             }
320             parameterListMap.put(paramName, al);
321
322             return (al.size());
323         }
324
325         String JavaDoc getCommandName() {
326             return (commandName);
327         }
328
329         Object JavaDoc getParameter(String JavaDoc name) {
330             String JavaDoc paramValue = (String JavaDoc) parameterMap.get(name);
331             return (getValueOf(paramValue));
332         }
333
334         boolean addOutputParameter(String JavaDoc name, Object JavaDoc value) {
335             try {
336                 tmpOutputs.put(name, value);
337                 return (true);
338             } catch (Exception JavaDoc e) {
339                 // setOutputValue already logs a message
340
}
341
342             return (false);
343         }
344
345         boolean setOutputParameter(String JavaDoc name, Object JavaDoc value) {
346             try {
347                 String JavaDoc paramValue = (String JavaDoc) parameterMap.get(name);
348                 tmpOutputs.put(paramValue, value);
349                 return (true);
350             } catch (Exception JavaDoc e) {
351                 // setOutputValue already logs a message
352
}
353
354             return (false);
355         }
356
357         List JavaDoc getParameterList(String JavaDoc name) {
358             ArrayList JavaDoc rtnList = new ArrayList JavaDoc();
359             List JavaDoc paramList = (List JavaDoc) parameterListMap.get(name);
360             if (paramList == null) {
361                 return (rtnList);
362             }
363
364             for (Iterator JavaDoc it = paramList.iterator(); it.hasNext();) {
365                 rtnList.add(getValueOf((String JavaDoc) it.next()));
366             }
367             return (rtnList);
368         }
369
370         List JavaDoc getParameterListNames(String JavaDoc name) {
371             ArrayList JavaDoc rtnList = new ArrayList JavaDoc();
372             List JavaDoc paramList = (List JavaDoc) parameterListMap.get(name);
373             if (paramList == null) {
374                 return (rtnList);
375             }
376
377             for (Iterator JavaDoc it = paramList.iterator(); it.hasNext();) {
378                 rtnList.add(it.next());
379             }
380
381             return (rtnList);
382         }
383
384         Object JavaDoc getValueOf(String JavaDoc paramValue) {
385             if (paramValue == null) {
386                 return (null);
387             }
388
389             if (paramValue.startsWith("\"") && paramValue.endsWith("\"")) { //$NON-NLS-1$ //$NON-NLS-2$
390
if (paramValue.length() < 3) {
391                     return (""); //$NON-NLS-1$
392
}
393                 return (paramValue.substring(1, paramValue.length() - 1));
394             }
395
396             Object JavaDoc obj = tmpOutputs.get(paramValue);
397             if (obj != null) {
398                 return (obj);
399             }
400
401             return (getInputValue(paramValue));
402         }
403
404         abstract boolean validate(Node commandNode);
405
406         abstract boolean execute();
407     }
408
409     class FormatUtil extends UtilityBase {
410
411         FormatUtil() {
412             super("format"); //$NON-NLS-1$
413
}
414
415         boolean validate(Node commandNode) {
416             if (!addParameter("format-string", commandNode, true)) { //$NON-NLS-1$
417
return (false);
418             }
419
420             if (!addParameter("return", commandNode, false)) { //$NON-NLS-1$
421
return (false);
422             }
423
424             addParameterList("arg", commandNode, 0); //$NON-NLS-1$
425
return (true);
426         }
427
428         boolean execute() {
429             try {
430                 MessageFormat JavaDoc mf = new MessageFormat JavaDoc(getParameter("format-string").toString()); //$NON-NLS-1$
431
String JavaDoc theResult = mf.format(getParameterList("arg").toArray()); //$NON-NLS-1$
432
setOutputParameter("return", theResult); //$NON-NLS-1$
433
return (true);
434             } catch (Exception JavaDoc e) {
435                 error(Messages.getString("UtilityComponent.ERROR_0001_FORMAT_ERROR")); //$NON-NLS-1$
436
}
437             return (false);
438         }
439     }
440
441     class PrintUtil extends UtilityBase {
442
443         PrintUtil() {
444             super("print"); //$NON-NLS-1$
445
}
446
447         boolean validate(Node commandNode) {
448             if (!addParameter("delimiter", commandNode, false)) { //$NON-NLS-1$
449
return (false);
450             }
451
452             addParameterList("arg", commandNode, 0); //$NON-NLS-1$
453

454             return (true);
455         }
456
457         boolean execute() {
458             try {
459                 StringBuffer JavaDoc sb = new StringBuffer JavaDoc("\n***************************************************************\n"); //$NON-NLS-1$
460

461                 Object JavaDoc o = getParameter("delimiter"); //$NON-NLS-1$
462
String JavaDoc delim = (o != null) ? o.toString() : ""; //$NON-NLS-1$
463

464                 List JavaDoc args = getParameterList("arg"); //$NON-NLS-1$
465
for (Iterator JavaDoc it = args.iterator(); it.hasNext();) {
466                     sb.append(it.next()).append(delim);
467                 }
468
469                 sb.append("\n***************************************************************\n"); //$NON-NLS-1$
470

471                 info(sb.toString());
472
473                 return (true);
474             } catch (Exception JavaDoc e) {
475                 error(Messages.getString("UtilityComponent.ERROR_0002_MESSAGE_LOG_ERROR")); //$NON-NLS-1$
476
}
477             return (false);
478         }
479     }
480
481     class CopyUtil extends UtilityBase {
482
483         CopyUtil() {
484             super("copy"); //$NON-NLS-1$
485
}
486
487         boolean validate(Node commandNode) {
488             if (!addParameter("from", commandNode, false)) { //$NON-NLS-1$
489
return (false);
490             }
491
492             if (!addParameter("return", commandNode, false)) { //$NON-NLS-1$
493
return (false);
494             }
495
496             return (true);
497         }
498
499         boolean execute() {
500             try {
501                 setOutputParameter("return", getParameter("from")); //$NON-NLS-1$ //$NON-NLS-2$
502
return (true);
503             } catch (Exception JavaDoc e) {
504                 error(Messages.getString("UtilityComponent.ERROR_0003_ERROR_COPYING_PARAMETER")); //$NON-NLS-1$
505
}
506             return (false);
507         }
508     }
509
510     class GetMapValues extends UtilityBase {
511
512         GetMapValues() {
513             super("getmapvalues"); //$NON-NLS-1$
514
}
515
516         boolean validate(Node commandNode) {
517             if (!addParameter("property-map", commandNode, true)) { //$NON-NLS-1$
518
return (false);
519             }
520             addParameterList("arg", commandNode, 1); //$NON-NLS-1$
521

522             return (true);
523         }
524
525         boolean execute() {
526             try {
527                 Object JavaDoc mapObj = getParameter("property-map"); //$NON-NLS-1$
528

529                 if (!(mapObj instanceof Map JavaDoc)) {
530                     error(Messages.getErrorString("UtilityComponent.ERROR_0004_PARAMETER_NOT_MAP", "property-map")); //$NON-NLS-1$ //$NON-NLS-2$
531
return (false);
532                 }
533
534                 Map JavaDoc srcMap = (Map JavaDoc) mapObj;
535                 for (Iterator JavaDoc it = getParameterListNames("arg").iterator(); it.hasNext();) { //$NON-NLS-1$
536
String JavaDoc key = it.next().toString();
537                     addOutputParameter(key, srcMap.get(key));
538                 }
539
540                 return (true);
541             } catch (Exception JavaDoc e) {
542                 error(Messages.getString(Messages.getString("UtilityComponent.ERROR_0005_GET_MAP_VALUES_ERROR"))); //$NON-NLS-1$
543
}
544             return (false);
545         }
546     }
547
548 }
Popular Tags