KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > pentaho > core > runtime > RuntimeContext


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 /*
14  * Created on Jun 17, 2005
15  *
16  * TODO To change the template for this generated file go to
17  * Window - Preferences - Java - Code Style - Code Templates
18  */

19 package org.pentaho.core.runtime;
20
21 import java.io.File JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.InputStream JavaDoc;
24 import java.io.OutputStream JavaDoc;
25 import java.io.Reader JavaDoc;
26 import java.lang.reflect.Array JavaDoc;
27 import java.math.BigDecimal JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.Date JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.Set JavaDoc;
35 import java.util.regex.Matcher JavaDoc;
36 import java.util.regex.Pattern JavaDoc;
37 import javax.activation.DataSource JavaDoc;
38 import org.apache.commons.logging.Log;
39 import org.apache.commons.logging.LogFactory;
40 import org.dom4j.Document;
41 import org.dom4j.Element;
42 import org.dom4j.Node;
43 import org.pentaho.core.audit.AuditHelper;
44 import org.pentaho.core.audit.MessageTypes;
45 import org.pentaho.core.component.IComponent;
46 import org.pentaho.core.connection.IPentahoResultSet;
47 import org.pentaho.core.repository.IContentItem;
48 import org.pentaho.core.repository.IContentLocation;
49 import org.pentaho.core.repository.IContentRepository;
50 import org.pentaho.core.repository.IRuntimeElement;
51 import org.pentaho.core.repository.IRuntimeRepository;
52 import org.pentaho.core.repository.content.ContentRepositoryOutputHandler;
53 import org.pentaho.core.session.IPentahoSession;
54 import org.pentaho.core.solution.ActionParameterSource;
55 import org.pentaho.core.solution.ConditionalExecution;
56 import org.pentaho.core.solution.IActionCompleteListener;
57 import org.pentaho.core.solution.IActionDefinition;
58 import org.pentaho.core.solution.IActionResource;
59 import org.pentaho.core.solution.IActionSequence;
60 import org.pentaho.core.solution.IOutputHandler;
61 import org.pentaho.core.solution.IParameterProvider;
62 import org.pentaho.core.solution.ISolutionEngine;
63 import org.pentaho.core.system.PentahoMessenger;
64 import org.pentaho.core.system.PentahoSystem;
65 import org.pentaho.core.ui.IPentahoUrlFactory;
66 import org.pentaho.core.util.IParameterResolver;
67 import org.pentaho.core.util.TemplateUtil;
68 import org.pentaho.core.util.XForm;
69 import org.pentaho.core.util.XmlHelper;
70 import org.pentaho.messages.Messages;
71 import org.pentaho.messages.util.LocaleHelper;
72 import org.pentaho.util.logging.Logger;
73
74 /**
75  * @author James Dixon
76  *
77  * TODO To change the template for this generated type comment go to Window -
78  * Preferences - Java - Code Style - Code Templates
79  */

80 public class RuntimeContext extends PentahoMessenger implements IRuntimeContext {
81
82     /**
83      *
84      */

85     private static final long serialVersionUID = -1179016850860938879L;
86
87     public static final String JavaDoc PARAMS_REQUEST = "request"; //$NON-NLS-1$
88
public static final String JavaDoc PARAMS_SESSION = "session"; //$NON-NLS-1$
89

90     private IRuntimeElement runtimeData;
91
92     // private int loggingLevel = UNKNOWN;
93
private static String JavaDoc LOG_NAME = "RUNTIME"; //$NON-NLS-1$
94

95     protected static String JavaDoc PARAMETER_FORM = "actionparam"; //$NON-NLS-1$
96

97     private String JavaDoc logId;
98
99     private IPentahoSession session;
100
101     protected ISolutionEngine solutionEngine;
102
103     private int errorLevel = RUNTIME_CONTEXT_RESOLVE_OK;
104
105     protected StringBuffer JavaDoc xformHeader;
106
107     protected StringBuffer JavaDoc xformBody;
108
109     protected Map JavaDoc xformFields;
110
111     protected String JavaDoc parameterXsl = "DefaultParameterForm.xsl"; //$NON-NLS-1$
112

113     protected String JavaDoc parameterTemplate = null;
114
115     protected String JavaDoc parameterTarget;
116
117     private String JavaDoc instanceId;
118
119     private String JavaDoc processId;
120
121     private String JavaDoc handle;
122
123     private String JavaDoc solutionName;
124
125     protected IPentahoUrlFactory urlFactory;
126
127     protected Map JavaDoc parameterProviders;
128
129     protected Map JavaDoc componentClassMap;
130
131     protected IActionSequence actionSequence;
132
133     public static final boolean debug = PentahoSystem.debug;
134
135     private boolean audit = true;
136
137     private int status;
138
139     protected IOutputHandler outputHandler;
140     
141     protected ParameterManager paramManager;
142
143     private String JavaDoc currentComponent;
144
145     private IActionDefinition currentActionDef;
146
147     private int promptStatus = PROMPT_NO;
148
149     // Normally shouldn't need to synchronize. But, a bug in
150
// pattern compilation results in the need to synchronize
151
// a small block of code. If/when this problem is fixed, we
152
// can remove this synchronization lock.
153
private static final byte[] PATTERN_COMPILE_LOCK = new byte[0];
154     
155     private static final Log logger = LogFactory.getLog(RuntimeContext.class);
156
157     public Log getLogger() {
158         return logger;
159     }
160
161     /*
162      * public RuntimeContext( IApplicationContext applicationContext, String
163      * solutionName ) { this( null, solutionName, applicationContext, null,
164      * null, null, null ); }
165      */

166     public RuntimeContext(String JavaDoc instanceId, ISolutionEngine solutionEngine, String JavaDoc solutionName, IRuntimeElement runtimeData, IPentahoSession session, IOutputHandler outputHandler, String JavaDoc processId, IPentahoUrlFactory urlFactory, Map JavaDoc parameterProviders,
167             List JavaDoc messages) {
168         this.instanceId = instanceId;
169         this.solutionEngine = solutionEngine;
170         this.session = session;
171         this.outputHandler = outputHandler;
172         this.processId = processId;
173         this.solutionName = solutionName;
174         this.urlFactory = urlFactory;
175         this.parameterProviders = parameterProviders;
176         setMessages(messages);
177         xformHeader = new StringBuffer JavaDoc();
178         xformBody = new StringBuffer JavaDoc();
179         xformFields = new HashMap JavaDoc();
180         // TODO - Throw invalid parameter error if these babies are null
181

182         this.currentComponent = ""; //$NON-NLS-1$
183
this.currentActionDef = null;
184
185         status = RUNTIME_STATUS_NOT_STARTED;
186
187         this.runtimeData = runtimeData;
188         if (runtimeData != null) {
189             this.instanceId = runtimeData.getInstanceId();
190         }
191
192         handle = "context-" + this.hashCode() + "-" + new Date JavaDoc().getTime(); //$NON-NLS-1$ //$NON-NLS-2$
193

194         logId = ((instanceId != null) ? instanceId : solutionName) + ":" + LOG_NAME + ":" + handle + " "; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
195

196         paramManager = new ParameterManager();
197         
198         // Set the default XSL for parameter forms
199
parameterXsl = "DefaultParameterForm.xsl"; //$NON-NLS-1$
200

201     }
202
203     private IRuntimeElement createChild(boolean persisted) {
204         try {
205             IRuntimeRepository runtimeRepository = PentahoSystem.getRuntimeRepository( session );
206 // IRuntimeRepository runtimeRepository = RuntimeRepository.getInstance(session);
207
runtimeRepository.setLoggingLevel(loggingLevel);
208             IRuntimeElement childRuntimeData = runtimeRepository.newRuntimeElement(instanceId, "instance", !persisted); //$NON-NLS-1$
209
String JavaDoc childInstanceId = childRuntimeData.getInstanceId();
210             // audit the creation of this against the parent instance
211
AuditHelper.audit(instanceId, session.getName(), getActionName(), getObjectName(), processId, MessageTypes.INSTANCE_START, childInstanceId, "", null, this); //$NON-NLS-1$
212
return childRuntimeData;
213         } catch (Exception JavaDoc e) {
214             error(Messages.getString("RuntimeContext.ERROR_0027_COULD_NOT_CREATE_CHILD"), e); //$NON-NLS-1$
215
return null;
216         }
217     }
218
219     public String JavaDoc createNewInstance(boolean persisted) {
220         try {
221             IRuntimeElement childRuntimeData = createChild(persisted);
222             String JavaDoc childInstanceId = childRuntimeData.getInstanceId();
223             return childInstanceId;
224         } catch (Exception JavaDoc e) {
225             error(Messages.getString("RuntimeContext.ERROR_0027_COULD_NOT_CREATE_CHILD"), e); //$NON-NLS-1$
226
return null;
227         }
228     }
229
230     public String JavaDoc createNewInstance(boolean persisted, Map JavaDoc parameters) {
231         return createNewInstance(persisted, parameters, false);
232     }
233
234     public String JavaDoc createNewInstance(boolean persisted, Map JavaDoc parameters, boolean forceImmediateWrite) {
235         try {
236             IRuntimeElement childRuntimeData = createChild(persisted);
237             if (parameters != null) {
238                 Iterator JavaDoc parameterIterator = parameters.keySet().iterator();
239                 while (parameterIterator.hasNext()) {
240                     String JavaDoc parameterName = (String JavaDoc) parameterIterator.next();
241                     Object JavaDoc parameterValue = parameters.get(parameterName);
242                     if (parameterValue instanceof String JavaDoc) {
243                         childRuntimeData.setStringProperty(parameterName, (String JavaDoc) parameterValue);
244                     } else if (parameterValue instanceof BigDecimal JavaDoc) {
245                         childRuntimeData.setBigDecimalProperty(parameterName, (BigDecimal JavaDoc) parameterValue);
246                     } else if (parameterValue instanceof Date JavaDoc) {
247                         childRuntimeData.setDateProperty(parameterName, (Date JavaDoc) parameterValue);
248                     } else if (parameterValue instanceof List JavaDoc) {
249                         childRuntimeData.setListProperty(parameterName, (List JavaDoc) parameterValue);
250                     } else if (parameterValue instanceof Long JavaDoc) {
251                         childRuntimeData.setLongProperty(parameterName, (Long JavaDoc) parameterValue);
252                     }
253                 }
254             }
255             String JavaDoc childInstanceId = childRuntimeData.getInstanceId();
256             if (forceImmediateWrite) {
257                 childRuntimeData.forceSave();
258             }
259             return childInstanceId;
260         } catch (Exception JavaDoc e) {
261             error(Messages.getString("RuntimeContext.ERROR_0027_COULD_NOT_CREATE_CHILD"), e); //$NON-NLS-1$
262
return null;
263         }
264
265     }
266
267     public int getStatus() {
268         return status;
269     }
270
271     public void promptNow() {
272         promptStatus = PROMPT_NOW;
273     }
274
275     /** Sets the prompt flag but continue processing Actions */
276     public void promptNeeded() {
277         if (promptStatus < PROMPT_WAITING) { // Don't mask a Prompt_Now
278
promptStatus = PROMPT_WAITING;
279         }
280     }
281
282     /**
283      * Tells if a component is waiting for a prompt
284      *
285      * @return true if a prompt is pending
286      */

287     public boolean isPromptPending() {
288         return (promptStatus != PROMPT_NO);
289     }
290
291     public IPentahoUrlFactory getUrlFactory() {
292         return urlFactory;
293     }
294
295     public boolean feedbackAllowed() {
296         return outputHandler != null && outputHandler.allowFeedback();
297     }
298
299     public IContentItem getFeedbackContentItem() {
300         return outputHandler.getFeedbackContentItem();
301     }
302
303     public IContentItem getOutputContentItem() {
304         // TODO check the sequence definition to see where this should come from
305
return outputHandler.getOutputContentItem(IOutputHandler.RESPONSE, IOutputHandler.CONTENT, actionSequence.getTitle(), null);
306     }
307
308     public IContentItem getOutputContentItem(String JavaDoc outputName) {
309
310         IActionParameter parameter = (IActionParameter) actionSequence.getOutputDefinitions().get(outputName);
311         if (parameter == null) {
312             error(Messages.getErrorString("RuntimeContext.ERROR_0021_INVALID_OUTPUT_REQUEST", outputName, actionSequence.getSequenceName())); //$NON-NLS-1$
313
throw new InvalidParameterException();
314         }
315
316         List JavaDoc destinationsList = parameter.getVariables();
317         Iterator JavaDoc destinationsIterator = destinationsList.iterator();
318         // we can only handle one destination at the moment
319
if (destinationsIterator.hasNext()) {
320             ActionParameterSource destination = (ActionParameterSource) destinationsIterator.next();
321             String JavaDoc objectName = destination.getSourceName();
322             String JavaDoc contentName = destination.getValue();
323             contentName = TemplateUtil.applyTemplate(contentName, this);
324             return outputHandler.getOutputContentItem(objectName, contentName, actionSequence.getTitle(), null);
325         }
326         return null;
327     }
328
329     public String JavaDoc getHandle() {
330         return handle;
331     }
332
333     public IPentahoSession getSession() {
334         return session;
335     }
336
337     public String JavaDoc getSolutionName() {
338         return (solutionName);
339     }
340
341     public String JavaDoc getSolutionPath() {
342         return ((actionSequence != null) ? actionSequence.getSolutionPath() : null);
343     }
344
345     public String JavaDoc getCurrentComponentName() {
346         if ("".equals(currentComponent)) { //$NON-NLS-1$
347
return this.getClass().getName();
348         }
349         return currentComponent;
350     }
351
352     public String JavaDoc getInstanceId() {
353         return instanceId;
354     }
355
356     public int getErrorLevel() {
357         return errorLevel;
358     }
359
360     public void setActionSequence( IActionSequence sequence ) {
361         this.actionSequence = sequence;
362         paramManager = new ParameterManager( sequence );
363     }
364     
365     public int validateSequence(String JavaDoc sequenceName) {
366         paramManager.resetParameters();
367
368         logId = ((instanceId != null) ? instanceId : solutionName) + ":" + LOG_NAME + ":" + handle + ":" + sequenceName + " "; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
369
if (audit) {
370             audit(MessageTypes.ACTION_SEQUENCE_START, MessageTypes.START, "", 0); //$NON-NLS-1$
371
}
372
373         if (status != RUNTIME_STATUS_NOT_STARTED) {
374             error(Messages.getErrorString("RuntimeContext.ERROR_0001_RUNTIME_RUNNING")); //$NON-NLS-1$
375
return (status);
376         }
377
378         errorLevel = RUNTIME_CONTEXT_VALIDATE_OK;
379
380         // validate action header
381
errorLevel = validateHeader(sequenceName);
382         if (errorLevel != RUNTIME_CONTEXT_VALIDATE_OK) {
383             error(Messages.getErrorString("RuntimeContext.ERROR_0002_ACTION_NOT_VALIDATED", sequenceName)); //$NON-NLS-1$
384
status = RUNTIME_CONTEXT_VALIDATE_FAIL;
385             return errorLevel;
386         }
387
388         // TODO deep validation of sequence and action inputs and outputs
389

390         // validate resources
391
errorLevel = validateResources();
392         if (errorLevel != RUNTIME_CONTEXT_VALIDATE_OK) {
393             error(Messages.getErrorString("RuntimeContext.ERROR_0005_ACTION_RESOURCES_NOT_VALID", sequenceName)); //$NON-NLS-1$
394
status = RUNTIME_CONTEXT_VALIDATE_FAIL;
395             return errorLevel;
396         }
397
398         // validate component
399
errorLevel = validateComponents();
400         if (errorLevel != RUNTIME_CONTEXT_VALIDATE_OK) {
401             error(Messages.getErrorString("RuntimeContext.ERROR_0006_ACTION_COMPONENT_NOT_VALID", sequenceName)); //$NON-NLS-1$
402
status = RUNTIME_CONTEXT_VALIDATE_FAIL;
403             return errorLevel;
404         }
405
406         status = RUNTIME_CONTEXT_VALIDATE_OK;
407
408         return RUNTIME_CONTEXT_VALIDATE_OK;
409     }
410
411     private int validateHeader(String JavaDoc sequenceName) {
412
413 /* if (!actionSequence.getSequenceName().equals(sequenceName)) {
414             error(Messages.getErrorString("RuntimeContext.ERROR_0007_NAMES_DO_NOT_MATCH", actionSequence.getSequenceName(), sequenceName)); //$NON-NLS-1$
415             return RUNTIME_CONTEXT_VALIDATE_FAIL;
416         }*/

417
418         // setup auditing and logging etc
419
errorLevel = initFromActionSequenceDefinition();
420         if (errorLevel != RUNTIME_CONTEXT_RESOLVE_OK) {
421             error(Messages.getErrorString("RuntimeContext.ERROR_0008_ACTION_INITIALIZATION_FAILED", sequenceName)); //$NON-NLS-1$
422
return errorLevel;
423         }
424
425         return RUNTIME_CONTEXT_VALIDATE_OK;
426     }
427
428     private int validateResources() {
429
430         // allResources = actionSequence.getResourceDefinitions();
431
return RUNTIME_CONTEXT_VALIDATE_OK;
432     }
433
434     private int validateComponents() {
435         return ( validateComponents(actionSequence) );
436     }
437
438     private int validateComponents(IActionSequence sequence) {
439
440         List JavaDoc defList = sequence.getActionDefinitionsAndSequences();
441
442         Object JavaDoc listItem;
443         for (Iterator JavaDoc it = defList.iterator(); it.hasNext();) {
444             listItem = it.next();
445
446             if (listItem instanceof IActionSequence) {
447                 int rtn = validateComponents((IActionSequence) listItem);
448                 if (rtn != RUNTIME_CONTEXT_VALIDATE_OK) {
449                     return (rtn);
450                 }
451             } else if (listItem instanceof IActionDefinition) {
452                 IActionDefinition actionDef = (IActionDefinition) listItem;
453
454                 if (debug)
455                     debug(Messages.getString("RuntimeContext.DEBUG_VALIDATING_COMPONENT", actionDef.getComponentName())); //$NON-NLS-1$
456

457                 IComponent component = resolveComponent(actionDef);
458                 if (component != null) {
459                     component.setLoggingLevel(loggingLevel);
460
461                     // allow the ActionDefinition to cache the component
462
actionDef.setComponent(component);
463                     paramManager.setCurrentParameters(actionDef);
464                     // int stat = component.validate( instanceId,
465
// actionSequence.getSequenceName(), processId,
466
// actionDef.getComponentSection(), this, session, this,
467
// loggingLevel );
468
int stat = component.validate();
469                     if (stat != RUNTIME_CONTEXT_VALIDATE_OK) {
470                         return (stat);
471                     }
472                     paramManager.addOutputParameters(actionDef);
473                 } else {
474                     return RUNTIME_CONTEXT_VALIDATE_FAIL;
475                 }
476                 currentComponent = ""; //$NON-NLS-1$
477
currentActionDef = null;
478             }
479         }
480         return (RUNTIME_CONTEXT_VALIDATE_OK);
481     }
482
483     protected Map JavaDoc getComponentClassMap() {
484         if (componentClassMap == null) {
485             componentClassMap = createComponentClassMap();
486         }
487         return componentClassMap;
488     }
489
490     protected Map JavaDoc createComponentClassMap() {
491         componentClassMap = new HashMap JavaDoc();
492         // map the short names
493
componentClassMap.put("ContentOutputComponent", "org.pentaho.plugin.core.ContentOutputComponent"); //$NON-NLS-1$ //$NON-NLS-2$
494
componentClassMap.put("ContentRepositoryCleaner", "org.pentaho.plugin.core.ContentRepositoryCleaner"); //$NON-NLS-1$ //$NON-NLS-2$
495
componentClassMap.put("HelloWorldComponent", "org.pentaho.plugin.core.HelloWorldComponent"); //$NON-NLS-1$ //$NON-NLS-2$
496
componentClassMap.put("ResultSetCompareComponent", "org.pentaho.plugin.core.ResultSetCompareComponent"); //$NON-NLS-1$ //$NON-NLS-2$
497
componentClassMap.put("ResultSetExportComponent", "org.pentaho.plugin.core.ResultSetExportComponent"); //$NON-NLS-1$ //$NON-NLS-2$
498
componentClassMap.put("ResultSetFlattenerComponent", "org.pentaho.plugin.core.ResultSetFlattenerComponent"); //$NON-NLS-1$ //$NON-NLS-2$
499
componentClassMap.put("SecureFilterComponent", "org.pentaho.plugin.core.SecureFilterComponent"); //$NON-NLS-1$ //$NON-NLS-2$
500
componentClassMap.put("SubActionComponent", "org.pentaho.plugin.core.SubActionComponent"); //$NON-NLS-1$ //$NON-NLS-2$
501
componentClassMap.put("TemplateComponent", "org.pentaho.plugin.core.TemplateComponent"); //$NON-NLS-1$ //$NON-NLS-2$
502
componentClassMap.put("BIRTReportComponent", "org.pentaho.plugin.eclipsebirt.BIRTReportComponent"); //$NON-NLS-1$ //$NON-NLS-2$
503
componentClassMap.put("EmailComponent", "org.pentaho.plugin.email.EmailComponent"); //$NON-NLS-1$ //$NON-NLS-2$
504
componentClassMap.put("JasperReportsComponent", "org.pentaho.plugin.jasperreports.JasperReportsComponent"); //$NON-NLS-1$ //$NON-NLS-2$
505
componentClassMap.put("JavascriptRule", "org.pentaho.plugin.javascript.JavascriptRule"); //$NON-NLS-1$ //$NON-NLS-2$
506
componentClassMap.put("ChartComponent", "org.pentaho.plugin.jfreechart.ChartComponent"); //$NON-NLS-1$ //$NON-NLS-2$
507
componentClassMap.put("JFreeReportComponent", "org.pentaho.plugin.jfreereport.JFreeReportComponent"); //$NON-NLS-1$ //$NON-NLS-2$
508
componentClassMap.put("ReportWizardSpecComponent", "org.pentaho.plugin.jfreereport.ReportWizardSpecComponent"); //$NON-NLS-1$ //$NON-NLS-2$
509
componentClassMap.put("KettleComponent", "org.pentaho.plugin.kettle.KettleComponent"); //$NON-NLS-1$ //$NON-NLS-2$
510
componentClassMap.put("MDXDataComponent", "org.pentaho.plugin.mdx.MDXDataComponent"); //$NON-NLS-1$ //$NON-NLS-2$
511
componentClassMap.put("MDXLookupRule", "org.pentaho.plugin.mdx.MDXLookupRule"); //$NON-NLS-1$ //$NON-NLS-2$
512
componentClassMap.put("ReceiptAuditComponent", "org.pentaho.plugin.misc.ReceiptAuditComponent"); //$NON-NLS-1$ //$NON-NLS-2$
513
componentClassMap.put("TestComponent", "org.pentaho.plugin.misc.TestComponent"); //$NON-NLS-1$ //$NON-NLS-2$
514
componentClassMap.put("UtilityComponent", "org.pentaho.plugin.misc.UtilityComponent"); //$NON-NLS-1$ //$NON-NLS-2$
515
componentClassMap.put("MondrianModelComponent", "org.pentaho.plugin.olap.MondrianModelComponent"); //$NON-NLS-1$ //$NON-NLS-2$
516
componentClassMap.put("PivotViewComponent", "org.pentaho.plugin.olap.PivotViewComponent"); //$NON-NLS-1$ //$NON-NLS-2$
517
componentClassMap.put("PrintComponent", "org.pentaho.plugin.print.PrintComponent"); //$NON-NLS-1$ //$NON-NLS-2$
518
componentClassMap.put("JobSchedulerComponent", "org.pentaho.plugin.quartz.JobSchedulerComponent"); //$NON-NLS-1$ //$NON-NLS-2$
519
componentClassMap.put("SchedulerAdminComponent", "org.pentaho.plugin.quartz.SchedulerAdminComponent"); //$NON-NLS-1$ //$NON-NLS-2$
520
componentClassMap.put("SharkWorkflowComponent", "org.pentaho.plugin.shark.SharkWorkflowComponent"); //$NON-NLS-1$ //$NON-NLS-2$
521
componentClassMap.put("SQLDataComponent", "org.pentaho.plugin.sql.SQLDataComponent"); //$NON-NLS-1$ //$NON-NLS-2$
522
componentClassMap.put("SQLLookupRule", "org.pentaho.plugin.sql.SQLLookupRule"); //$NON-NLS-1$ //$NON-NLS-2$
523
componentClassMap.put("SQLExecute", "org.pentaho.plugin.sql.SQLExecute"); //$NON-NLS-1$ //$NON-NLS-2$
524
componentClassMap.put("XQueryLookupRule", "org.pentaho.plugin.xquery.XQueryLookupRule"); //$NON-NLS-1$ //$NON-NLS-2$
525
componentClassMap.put("ResultSetCrosstabComponent", "org.pentaho.plugin.core.ResultSetCrosstabComponent"); //$NON-NLS-1$ //$NON-NLS-2$
526

527         // map the old names
528
componentClassMap.put("org.pentaho.component.ContentOutputComponent", "!org.pentaho.plugin.core.ContentOutputComponent"); //$NON-NLS-1$ //$NON-NLS-2$
529
componentClassMap.put("org.pentaho.component.ContentRepositoryCleaner", "!org.pentaho.plugin.core.ContentRepositoryCleaner"); //$NON-NLS-1$ //$NON-NLS-2$
530
componentClassMap.put("org.pentaho.component.HelloWorldComponent", "!org.pentaho.plugin.core.HelloWorldComponent"); //$NON-NLS-1$ //$NON-NLS-2$
531
componentClassMap.put("org.pentaho.component.ResultSetCompareComponent", "!org.pentaho.plugin.core.ResultSetCompareComponent"); //$NON-NLS-1$ //$NON-NLS-2$
532
componentClassMap.put("org.pentaho.component.ResultSetExportComponent", "!org.pentaho.plugin.core.ResultSetExportComponent"); //$NON-NLS-1$ //$NON-NLS-2$
533
componentClassMap.put("org.pentaho.component.ResultSetFlattenerComponent", "!org.pentaho.plugin.core.ResultSetFlattenerComponent"); //$NON-NLS-1$ //$NON-NLS-2$
534
componentClassMap.put("org.pentaho.component.SecureFilterComponent", "!org.pentaho.plugin.core.SecureFilterComponent"); //$NON-NLS-1$ //$NON-NLS-2$
535
componentClassMap.put("org.pentaho.component.SubActionComponent", "!org.pentaho.plugin.core.SubActionComponent"); //$NON-NLS-1$ //$NON-NLS-2$
536
componentClassMap.put("org.pentaho.component.TemplateComponent", "!org.pentaho.plugin.core.TemplateComponent"); //$NON-NLS-1$ //$NON-NLS-2$
537
componentClassMap.put("org.pentaho.birt.BIRTReportComponent", "!org.pentaho.plugin.eclipsebirt.BIRTReportComponent"); //$NON-NLS-1$ //$NON-NLS-2$
538
componentClassMap.put("org.pentaho.component.EmailComponent", "!org.pentaho.plugin.email.EmailComponent"); //$NON-NLS-1$ //$NON-NLS-2$
539
componentClassMap.put("org.pentaho.jasper.JasperReportsComponent", "!org.pentaho.plugin.jasperreports.JasperReportsComponent"); //$NON-NLS-1$ //$NON-NLS-2$
540
componentClassMap.put("org.pentaho.component.JavascriptRule", "!org.pentaho.plugin.javascript.JavascriptRule"); //$NON-NLS-1$ //$NON-NLS-2$
541
componentClassMap.put("org.pentaho.component.ChartComponent", "!org.pentaho.plugin.jfreechart.ChartComponent"); //$NON-NLS-1$ //$NON-NLS-2$
542
componentClassMap.put("org.pentaho.jfree.JFreeReportComponent", "!org.pentaho.plugin.jfreereport.JFreeReportComponent"); //$NON-NLS-1$ //$NON-NLS-2$
543
componentClassMap.put("org.pentaho.kettle.KettleComponent", "!org.pentaho.plugin.kettle.KettleComponent"); //$NON-NLS-1$ //$NON-NLS-2$
544
componentClassMap.put("org.pentaho.component.MDXDataComponent", "!org.pentaho.plugin.mdx.MDXDataComponent"); //$NON-NLS-1$ //$NON-NLS-2$
545
componentClassMap.put("org.pentaho.component.MDXLookupRule", "!org.pentaho.plugin.mdx.MDXLookupRule"); //$NON-NLS-1$ //$NON-NLS-2$
546
componentClassMap.put("org.pentaho.component.ReceiptAuditComponent", "!org.pentaho.plugin.misc.ReceiptAuditComponent"); //$NON-NLS-1$ //$NON-NLS-2$
547
componentClassMap.put("org.pentaho.component.TestComponent", "!org.pentaho.plugin.misc.TestComponent"); //$NON-NLS-1$ //$NON-NLS-2$
548
componentClassMap.put("org.pentaho.component.UtilityComponent", "!org.pentaho.plugin.misc.UtilityComponent"); //$NON-NLS-1$ //$NON-NLS-2$
549
componentClassMap.put("org.pentaho.component.MondrianModelComponent", "!org.pentaho.plugin.olap.MondrianModelComponent"); //$NON-NLS-1$ //$NON-NLS-2$
550
componentClassMap.put("org.pentaho.component.PivotViewComponent", "!org.pentaho.plugin.olap.PivotViewComponent"); //$NON-NLS-1$ //$NON-NLS-2$
551
componentClassMap.put("org.pentaho.component.PrintComponent", "!org.pentaho.plugin.print.PrintComponent"); //$NON-NLS-1$ //$NON-NLS-2$
552
componentClassMap.put("org.pentaho.component.JobSchedulerComponent", "!org.pentaho.plugin.quartz.JobSchedulerComponent"); //$NON-NLS-1$ //$NON-NLS-2$
553
componentClassMap.put("org.pentaho.component.SchedulerAdminComponent", "!org.pentaho.plugin.quartz.SchedulerAdminComponent"); //$NON-NLS-1$ //$NON-NLS-2$
554
componentClassMap.put("org.pentaho.component.SharkWorkflowComponent", "!org.pentaho.plugin.shark.SharkWorkflowComponent"); //$NON-NLS-1$ //$NON-NLS-2$
555
componentClassMap.put("org.pentaho.component.SQLDataComponent", "!org.pentaho.plugin.sql.SQLDataComponent"); //$NON-NLS-1$ //$NON-NLS-2$
556
componentClassMap.put("org.pentaho.component.SQLLookupRule", "!org.pentaho.plugin.sql.SQLLookupRule"); //$NON-NLS-1$ //$NON-NLS-2$
557
componentClassMap.put("org.pentaho.component.XQueryLookupRule", "!org.pentaho.plugin.xquery.XQueryLookupRule"); //$NON-NLS-1$ //$NON-NLS-2$
558

559         return componentClassMap;
560     }
561
562     private IComponent resolveComponent(IActionDefinition actionDefinition) {
563
564         // try to create an instance of the component class specified in the
565
// action document
566
String JavaDoc componentClassName = actionDefinition.getComponentName().trim();
567
568         String JavaDoc mappedClassName = (String JavaDoc) getComponentClassMap().get(componentClassName);
569         if (mappedClassName != null) {
570             if (mappedClassName.indexOf('!') == 0) {
571                 // this is deprecated, log a warning
572
mappedClassName = mappedClassName.substring(1);
573                 warn( Messages.getString( "RuntimeContext.WARN_DEPRECATED_COMPONENT_CLASS", componentClassName, mappedClassName ) ); //$NON-NLS-1$
574
audit(MessageTypes.DEPRECATION_WARNING, componentClassName, mappedClassName, 0);
575             }
576             componentClassName = mappedClassName;
577         }
578
579         Node componentDefinition = actionDefinition.getComponentSection();
580         currentComponent = componentClassName;
581         currentActionDef = actionDefinition;
582         try {
583
584             /*
585              * String instanceId, String actionName, String processId, Node
586              * componentDefinition, IRuntimeContext runtimeContext,
587              * IPentahoSession sessionContext, int loggingLevel
588              */

589
590             IComponent component = null;
591             Class JavaDoc componentClass;
592 /*
593             Class[] paramClasses = new Class[] { String.class, String.class, String.class, Node.class, IRuntimeContext.class, IPentahoSession.class, int.class, List.class };
594             Integer logLevel = new Integer(getLoggingLevel());
595             Object[] paramArgs = new Object[] { instanceId, getActionName(), processId, componentDefinition, this, session, logLevel, getMessages() };
596             Constructor componentConstructor;
597             componentClass = Class.forName(componentClassName);
598             componentConstructor = componentClass.getConstructor(paramClasses);
599             component = (IComponent) componentConstructor.newInstance(paramArgs);
600 */

601             
602             componentClass = Class.forName(componentClassName);
603             component = (IComponent) componentClass.newInstance();
604             component.setInstanceId( instanceId );
605             component.setActionName( getActionName() );
606             component.setProcessId( processId );
607             component.setComponentDefinition( componentDefinition );
608             component.setRuntimeContext( this );
609             component.setSession( session );
610             component.setLoggingLevel( getLoggingLevel() );
611             component.setMessages( getMessages() );
612             return component;
613
614         } catch (Exception JavaDoc e) {
615             error(Messages.getErrorString("RuntimeContext.ERROR_0009_COULD_NOT_CREATE_COMPONENT", componentClassName), e); //$NON-NLS-1$
616
}
617
618         // we were not successful
619
return null;
620     }
621
622     public int executeSequence(IActionCompleteListener listener, boolean async) {
623         paramManager.resetParameters();
624         
625         long start = new Date JavaDoc().getTime();
626         if (status != RUNTIME_CONTEXT_VALIDATE_OK) {
627             audit(MessageTypes.ACTION_SEQUENCE_FAILED, MessageTypes.VALIDATION, Messages.getErrorString("RuntimeContext.ERROR_0010_RUNTIME_DID_NOT_VALIDATE"), 0); //$NON-NLS-1$
628
error(Messages.getErrorString("RuntimeContext.ERROR_0010_RUNTIME_DID_NOT_VALIDATE")); //$NON-NLS-1$
629
return (status);
630         }
631         status = RUNTIME_STATUS_RUNNING;
632
633         // create an IActionDef object
634
List JavaDoc actionDefinitions = actionSequence.getActionDefinitionsAndSequences();
635
636         if (actionDefinitions == null) {
637             audit(MessageTypes.ACTION_SEQUENCE_FAILED, MessageTypes.VALIDATION, Messages.getErrorString("RuntimeContext.ERROR_0011_NO_VALID_ACTIONS"), 0); //$NON-NLS-1$
638
error(Messages.getErrorString("RuntimeContext.ERROR_0011_NO_VALID_ACTIONS")); //$NON-NLS-1$
639
return RUNTIME_CONTEXT_VALIDATE_FAIL;
640         }
641
642         setLoggingLevel(loggingLevel);
643
644         if (debug)
645             debug(Messages.getString("RuntimeContext.DEBUG_EXECUTING_ACTIONS")); //$NON-NLS-1$
646

647         paramManager.setCurrentParameters( null );
648         errorLevel = resolveParameters();
649         if (errorLevel != RUNTIME_CONTEXT_RESOLVE_OK) {
650             audit(MessageTypes.ACTION_SEQUENCE_FAILED, MessageTypes.VALIDATION, Messages.getErrorString("RuntimeContext.ERROR_0013_BAD_PARAMETERS"), 0); //$NON-NLS-1$
651
error(Messages.getErrorString("RuntimeContext.ERROR_0013_BAD_PARAMETERS")); //$NON-NLS-1$
652
return errorLevel;
653         }
654
655         int rtnStat = executeSequence(actionSequence, listener, async);
656
657         if (this.feedbackAllowed() && ( promptStatus!=PROMPT_NO || (xformBody.length() > 0) || (parameterTemplate != null))) {
658             try {
659                  sendFeedbackForm();
660             } catch (Exception JavaDoc e) {
661                 // TODO log an error
662
error(Messages.getString("RuntimeContext.ERROR_0030_SEND_FEEDBACKFORM"), e); //$NON-NLS-1$
663
try {
664                     outputHandler.getFeedbackContentItem().setMimeType("text/html"); //$NON-NLS-1$
665
OutputStream JavaDoc os = outputHandler.getFeedbackContentItem().getOutputStream(getActionName());
666                     if (os != null) {
667                         os.write(Messages.getString("RuntimeContext.USER_BAD_PARAMETER_PAGE").getBytes(LocaleHelper.getSystemEncoding())); //$NON-NLS-1$
668
}
669                 } catch (Throwable JavaDoc t) {
670                     return RUNTIME_STATUS_FAILURE;
671                 }
672             }
673         }
674
675         paramManager.setCurrentParameters( null );
676
677         long end = new Date JavaDoc().getTime();
678         if ((rtnStat == RUNTIME_STATUS_SUCCESS) && audit) {
679             audit(MessageTypes.ACTION_SEQUENCE_END, MessageTypes.END, "", (int) (end - start)); //$NON-NLS-1$
680
} else {
681             audit(MessageTypes.ACTION_SEQUENCE_FAILED, MessageTypes.EXECUTION, "", (int) (end - start)); //$NON-NLS-1$
682
}
683
684         status = rtnStat;
685
686         if ( (rtnStat == RUNTIME_STATUS_SUCCESS) && !isPromptPending() ) {
687             Map JavaDoc returnParamMap = paramManager.getReturnParameters();
688             
689             for (Iterator JavaDoc it = returnParamMap.entrySet().iterator(); it.hasNext(); ) {
690                 Map.Entry JavaDoc mapEntry = (Map.Entry JavaDoc)it.next();
691
692                 String JavaDoc paramName = (String JavaDoc)mapEntry.getKey();
693                 ParameterManager.ReturnParameter returnParam = (ParameterManager.ReturnParameter)mapEntry.getValue();
694
695                 if ( returnParam == null) {
696                     error(Messages.getErrorString("RuntimeContext.ERROR_0029_SAVE_PARAM_NOT_FOUND", paramName )); //$NON-NLS-1$
697
}
698                 else {
699                     if ( PARAMS_SESSION.equals(returnParam.destinationName) ) {
700                         session.setAttribute( returnParam.destinationParameter, returnParam.value );
701                         if (debug)
702                             debug( paramName + " - session - " + returnParam.destinationParameter ); //$NON-NLS-1$
703
}
704                     else if ("response".equals(returnParam.destinationName)) { //$NON-NLS-1$
705
if (outputHandler != null) {
706                         outputHandler.setOutput( returnParam.destinationParameter, returnParam.value );
707                       } else {
708                         info(Messages.getString("RuntimeContext.INFO_NO_OUTPUT_HANDLER")); //$NON-NLS-1$
709
}
710                       if (debug)
711                           debug( paramName + " - response - " + returnParam.destinationParameter ); //$NON-NLS-1$
712
}
713                 }
714             }
715         }
716                 
717         // return the status for the action
718
return (rtnStat);
719     }
720
721     public void setPromptStatus( int status ) {
722             promptStatus = status;
723     }
724     
725     private int executeSequence(IActionSequence sequence, IActionCompleteListener listener, boolean async) {
726         String JavaDoc loopParamName = sequence.getLoopParameter();
727         Object JavaDoc loopList;
728         IActionParameter loopParm = null;
729
730         if (loopParamName == null) {
731             loopList = new ArrayList JavaDoc();
732             ((ArrayList JavaDoc) loopList).add(new Integer JavaDoc(0));
733         } else {
734             loopParm = getLoopParameter(loopParamName);
735             loopList = loopParm.getValue();
736         }
737
738         if (loopList instanceof List JavaDoc) {
739             int result = executeLoop(loopParm, (List JavaDoc) loopList, sequence, listener, async);
740             if (loopParm != null) {
741                 addInputParameter(loopParm.getName(), loopParm); // replace the loop param in case the last loop muggled it
742
}
743
744             if (result != RUNTIME_STATUS_SUCCESS) {
745                 return result;
746             }
747         } else if (loopList instanceof IPentahoResultSet) {
748             int result = executeLoop(loopParm, (IPentahoResultSet) loopList, sequence, listener, async);
749             if (result != RUNTIME_STATUS_SUCCESS) {
750                 return result;
751             }
752         }
753
754         return (RUNTIME_STATUS_SUCCESS);
755     }
756
757     private int executeLoop(IActionParameter loopParm, IPentahoResultSet loopSet, IActionSequence sequence, IActionCompleteListener listener, boolean async) {
758
759         // execute the actions
760
int loopCount = 0;
761
762         // TODO handle results sets directly instead of using Properties maps
763

764         Object JavaDoc row[] = loopSet.next();
765         Object JavaDoc headerSet[][] = loopSet.getMetaData().getColumnHeaders();
766         // TODO handle OLAP result sets
767
Object JavaDoc headers[] = headerSet[0];
768         while (row != null) {
769
770             if (debug)
771                 debug(Messages.getString("RuntimeContext.DEBUG_EXECUTING_ACTION", Integer.toString(loopCount++))); //$NON-NLS-1$
772

773             if (loopParm != null) {
774                 IActionParameter ap;
775                 for (int columnNo = 0; columnNo < headers.length; columnNo++) {
776                     String JavaDoc name = headers[columnNo].toString();
777                     Object JavaDoc value = row[columnNo];
778                     String JavaDoc type = null;
779                     if (value instanceof String JavaDoc) {
780                         type = IActionParameter.TYPE_STRING;
781                     } else if (value instanceof Date JavaDoc) {
782                         type = IActionParameter.TYPE_DATE;
783                     } else if (value instanceof Long JavaDoc || value instanceof Integer JavaDoc) {
784                         type = IActionParameter.TYPE_INTEGER;
785                     } else if (value instanceof BigDecimal JavaDoc) {
786                         type = IActionParameter.TYPE_DECIMAL;
787                     } else if (value instanceof String JavaDoc[]) {
788                         type = IActionParameter.TYPE_STRING;
789                     } else if (value == null) {
790                         warn(Messages.getString("RuntimeContext.WARN_VARIABLE_IN_LOOP_IS_NULL", name)); //$NON-NLS-1$
791
} else {
792                         type = IActionParameter.TYPE_OBJECT;
793                         warn(Messages.getString("RuntimeContext.WARN_VARIABLE_IN_LOOP_NOT_RECOGNIZED", name, value.getClass().toString())); //$NON-NLS-1$
794
}
795                     // TODO make sure any previous loop values are removed
796
if (type != null) {
797                         ap = new ActionParameter(name, type, value, null, null);
798                         addInputParameter(name, ap);
799                     }
800                 }
801             }
802             int rtn = performActions(sequence, listener, async);
803             if (rtn != RUNTIME_STATUS_SUCCESS) {
804               return rtn;
805             }
806             row = loopSet.next();
807         }
808
809         return RUNTIME_STATUS_SUCCESS;
810     }
811     
812     private int executeLoop(IActionParameter loopParm, List JavaDoc loopList, IActionSequence sequence, IActionCompleteListener listener, boolean async) {
813
814         // execute the actions
815
int loopCount = 0;
816         for (Iterator JavaDoc it = loopList.iterator(); it.hasNext();) {
817
818             if (debug)
819                 debug(Messages.getString("RuntimeContext.DEBUG_EXECUTING_ACTION", Integer.toString(loopCount++))); //$NON-NLS-1$
820

821             Object JavaDoc loopVar = it.next();
822             if (loopParm != null) {
823                 IActionParameter ap;
824                 if (loopVar instanceof Map JavaDoc) {
825                     ap = new ActionParameter(loopParm.getName(), "property-map", loopVar, null, null); //$NON-NLS-1$
826
} else {
827                     ap = new ActionParameter(loopParm.getName(), "string", loopVar, null, null); //$NON-NLS-1$
828
}
829
830                 addInputParameter(loopParm.getName(), ap);
831             }
832
833             int rtn = performActions(sequence, listener, async);
834             if ( (rtn != RUNTIME_STATUS_SUCCESS) || (promptStatus == PROMPT_NOW) ) {
835               return rtn;
836             }
837         }
838         return RUNTIME_STATUS_SUCCESS;
839     }
840
841     private int performActions(IActionSequence sequence, IActionCompleteListener listener, boolean async) {
842       ConditionalExecution conditional = sequence.getConditionalExecution();
843       if (conditional != null) {
844         boolean shouldExecute = false;
845         try {
846           shouldExecute = conditional.shouldExecute( paramManager.getAllParameters(), logger);
847         } catch (Exception JavaDoc ex) {
848           error(Messages.getErrorString("RuntimeContext.ERROR_0032_CONDITIONAL_EXECUTION_FAILED"), ex); //$NON-NLS-1$
849
// return the runtime so the messages are available
850
currentComponent = ""; //$NON-NLS-1$
851
return RUNTIME_STATUS_FAILURE;
852         }
853         if (!shouldExecute) {
854           //audit(MessageTypes.ACTION_SEQUENCE_EXECUTE_CONDITIONAL, MessageTypes.NOT_EXECUTED, "", 0); //$NON-NLS-1$ //$NON-NLS-2$
855
if (debug ) this.debug(Messages.getString("RuntimeContext.INFO_ACTION_NOT_EXECUTED")); //$NON-NLS-1$
856
return RUNTIME_STATUS_SUCCESS;
857         }
858       }
859       
860       List JavaDoc defList = sequence.getActionDefinitionsAndSequences();
861
862       Object JavaDoc listItem;
863       for (Iterator JavaDoc actIt = defList.iterator(); actIt.hasNext();) {
864           listItem = actIt.next();
865
866           if (listItem instanceof IActionSequence) {
867               int rtn = executeSequence((IActionSequence) listItem, listener, async);
868               if (rtn != RUNTIME_STATUS_SUCCESS) {
869                   return (rtn);
870               }
871           } else if (listItem instanceof IActionDefinition) {
872               IActionDefinition actionDef = (IActionDefinition) listItem;
873               currentComponent = actionDef.getComponentName();
874               currentActionDef = actionDef;
875               paramManager.setCurrentParameters(actionDef);
876
877               int executeResult = executeAction(actionDef, parameterProviders, listener, async);
878               if (executeResult != IRuntimeContext.RUNTIME_STATUS_SUCCESS) {
879                   error(Messages.getErrorString("RuntimeContext.ERROR_0012_EXECUTION_FAILED", currentComponent)); //$NON-NLS-1$
880
// return the runtime so the messages are available
881
currentComponent = ""; //$NON-NLS-1$
882
return RUNTIME_STATUS_FAILURE;
883               }
884               paramManager.addOutputParameters(actionDef);
885           }
886           if (promptStatus == PROMPT_NOW) {
887             // promptStatus = PROMPT_NO; // turn it off - just in case DM - Turning off was causing problems
888
return (RUNTIME_STATUS_SUCCESS);
889           }
890           currentComponent = ""; //$NON-NLS-1$
891
currentActionDef = null;
892       }
893       return RUNTIME_STATUS_SUCCESS;
894     }
895     
896     private int executeAction(IActionDefinition actionDefinition, Map JavaDoc pParameterProviders, IActionCompleteListener listener, boolean async) {
897
898         this.parameterProviders = pParameterProviders;
899         // TODO get audit setting from action definition
900

901         long start = new Date JavaDoc().getTime();
902         if (audit) {
903             audit(MessageTypes.COMPONENT_EXECUTE_START, MessageTypes.START, "", 0); //$NON-NLS-1$
904
}
905
906         errorLevel = RUNTIME_CONTEXT_RESOLVE_OK;
907
908         // resolve the parameters
909
errorLevel = resolveParameters();
910         if (errorLevel != RUNTIME_CONTEXT_RESOLVE_OK) {
911             error(Messages.getErrorString("RuntimeContext.ERROR_0013_BAD_PARAMETERS")); //$NON-NLS-1$
912
audit(MessageTypes.COMPONENT_EXECUTE_FAILED, MessageTypes.VALIDATION, Messages.getErrorString("RuntimeContext.ERROR_0013_BAD_PARAMETERS"), 0); //$NON-NLS-1$
913
if (listener != null) {
914                 listener.actionComplete(this);
915             }
916             return errorLevel;
917         }
918
919         if (debug)
920             debug(Messages.getString("RuntimeContext.DEBUG_PRE-EXECUTE_AUDIT")); //$NON-NLS-1$
921
List JavaDoc auditPre = actionDefinition.getPreExecuteAuditList();
922         audit(auditPre);
923
924         // resolve the output parameters
925
errorLevel = resolveOutputHandler();
926         if (errorLevel != RUNTIME_CONTEXT_RESOLVE_OK) {
927             audit(MessageTypes.COMPONENT_EXECUTE_FAILED, MessageTypes.VALIDATION, Messages.getErrorString("RuntimeContext.ERROR_0014_NO_OUTPUT_HANDLER"), 0); //$NON-NLS-1$
928
if (listener != null) {
929                 listener.actionComplete(this);
930             }
931             return errorLevel;
932         }
933
934         // resolve the resources
935
// Param Manager resolves them at create time
936

937         if (async) {
938             // TODO handle threading
939
// create the thread if necessary
940
}
941
942         // initialize the component
943
IComponent component = actionDefinition.getComponent();
944
945         if (debug)
946             debug(Messages.getString("RuntimeContext.DEBUG_SETTING_LOGGING", Logger.getLogLevelName(loggingLevel))); //$NON-NLS-1$
947
component.setLoggingLevel(loggingLevel);
948         if (debug)
949             debug(Messages.getString("RuntimeContext.DEBUG_INITIALIZING_COMPONENT")); //$NON-NLS-1$
950
errorLevel = component.init() ? RUNTIME_STATUS_INITIALIZE_OK : RUNTIME_STATUS_INITIALIZE_FAIL;
951         if (errorLevel != RUNTIME_STATUS_INITIALIZE_OK) {
952             audit(MessageTypes.COMPONENT_EXECUTE_FAILED, MessageTypes.VALIDATION, Messages.getErrorString("RuntimeContext.ERROR_0016_COMPONENT_INITIALIZE_FAILED"), 0); //$NON-NLS-1$
953
error(Messages.getErrorString("RuntimeContext.ERROR_0016_COMPONENT_INITIALIZE_FAILED")); //$NON-NLS-1$
954
if (listener != null) {
955                 listener.actionComplete(this);
956             }
957             return errorLevel;
958         }
959
960         // run the component
961
errorLevel = executeComponent(actionDefinition);
962         if (errorLevel != RUNTIME_STATUS_SUCCESS) {
963             if (listener != null) {
964                 listener.actionComplete(this);
965             }
966             return errorLevel;
967         }
968
969         if (debug)
970             debug(Messages.getString("RuntimeContext.DEBUG_POST-EXECUTE_AUDIT")); //$NON-NLS-1$
971
List JavaDoc auditPost = actionDefinition.getPostExecuteAuditList();
972         audit(auditPost);
973         if (audit) {
974             long end = new Date JavaDoc().getTime();
975             audit(MessageTypes.COMPONENT_EXECUTE_END, MessageTypes.END, "", (int) (end - start)); //$NON-NLS-1$
976
}
977
978         if (listener != null) {
979             listener.actionComplete(this);
980         }
981         return errorLevel;
982     }
983
984     private int executeComponent(IActionDefinition actionDefinition) {
985         if (debug)
986             debug(Messages.getString("RuntimeContext.DEBUG_STARTING_COMPONENT_EXECUTE")); //$NON-NLS-1$
987
int executeStatus = RUNTIME_STATUS_FAILURE;
988         try {
989             executeStatus = actionDefinition.getComponent().execute();
990             actionDefinition.getComponent().done();
991         } catch (Exception JavaDoc e) {
992             audit(MessageTypes.COMPONENT_EXECUTE_FAILED, MessageTypes.FAILED, e.getLocalizedMessage(), 0);
993             error(Messages.getErrorString("RuntimeContext.ERROR_0017_COMPONENT_EXECUTE_FAILED"), e); //$NON-NLS-1$
994
}
995         if (debug)
996             debug(Messages.getString("RuntimeContext.DEBUG_FINISHED_COMPONENT_EXECUTE")); //$NON-NLS-1$
997
return executeStatus;
998     }
999
1000    private int initFromActionSequenceDefinition() {
1001
1002        // TODO get audit setting from action sequence
1003

1004        int actionLogLevel = actionSequence.getLoggingLevel();
1005        int instanceLogLevel = runtimeData.getLoggingLevel();
1006        int actionSequenceLoggingLevel = (instanceLogLevel != UNKNOWN) ? instanceLogLevel : ((actionLogLevel != UNKNOWN) ? actionLogLevel : solutionEngine.getLoggingLevel());
1007
1008        setLoggingLevel(actionSequenceLoggingLevel);
1009
1010        return RUNTIME_CONTEXT_RESOLVE_OK;
1011    }
1012
1013    private int resolveParameters() {
1014
1015        Set JavaDoc inputNames = getInputNames();
1016        Iterator JavaDoc inputNamesIterator = inputNames.iterator();
1017        IActionParameter actionParameter;
1018        List JavaDoc variables;
1019        Iterator JavaDoc variablesIterator;
1020        ActionParameterSource variable;
1021        String JavaDoc sourceName;
1022        String JavaDoc sourceValue;
1023        Object JavaDoc variableValue = null;
1024        IParameterProvider parameterProvider;
1025        while (inputNamesIterator.hasNext()) {
1026            variableValue = null;
1027
1028            String JavaDoc inputName = (String JavaDoc) inputNamesIterator.next();
1029            actionParameter = paramManager.getCurrentInput(inputName);
1030            if (actionParameter == null) {
1031                error(Messages.getErrorString("RuntimeContext.ERROR_0031_INPUT_NOT_FOUND", inputName)); //$NON-NLS-1$
1032
return RUNTIME_CONTEXT_RESOLVE_FAIL;
1033            }
1034
1035            variables = actionParameter.getVariables();
1036            variablesIterator = variables.iterator();
1037            while (variablesIterator.hasNext()) {
1038                variable = (ActionParameterSource) variablesIterator.next();
1039                sourceName = variable.getSourceName();
1040                sourceValue = variable.getValue();
1041                variableValue = null;
1042                // TODO support accessing the ancestors of the current instance,
1043
// e.g. runtme.parent
1044
if ("runtime".equals(sourceName)) { //$NON-NLS-1$
1045
// first check the standard variables
1046
variableValue = getStringParameter(sourceValue, null);
1047                    if (variableValue == null) {
1048                        // now check the runtime data
1049
variableValue = runtimeData.getStringProperty(sourceValue, null);
1050                    }
1051                    if (variableValue != null) {
1052                        break;
1053                    }
1054                } else {
1055                    parameterProvider = (IParameterProvider) parameterProviders.get(sourceName);
1056                    if (parameterProvider == null) {
1057                        warn(Messages.getString("RuntimeContext.WARN_REQUESTED_PARAMETER_SOURCE_NOT_AVAILABLE", sourceName, inputName)); //$NON-NLS-1$
1058
} else {
1059                        variableValue = parameterProvider.getParameter(sourceValue);
1060                        // variableValue = parameterProvider.getStringParameter(
1061
// sourceValue, null );
1062
if (variableValue != null) {
1063                            break;
1064                        }
1065                    }
1066                }
1067            }
1068
1069            if (variableValue == null) {
1070
1071                if (actionParameter.getValue() != null) {
1072                    if (actionParameter.hasDefaultValue()) {
1073                        trace(Messages.getString("RuntimeContext.TRACE_USING_DEFAULT_PARAMETER_VALUE", inputName)); //$NON-NLS-1$
1074
} else {
1075                        trace(Messages.getString("RuntimeContext.TRACE_INFO_USING_CURRENT_PARAMETER_VALUE" + inputName)); //$NON-NLS-1$
1076
}
1077                } else if ("content".equals(actionParameter.getType())) { //$NON-NLS-1$
1078
// store a dummy value in the map
1079
variableValue = ""; //$NON-NLS-1$
1080
} else {
1081                    error(Messages.getErrorString("RuntimeContext.ERROR_0018_PARAMETER_NOT_FULFILLED", inputName)); //$NON-NLS-1$
1082
return RUNTIME_CONTEXT_RESOLVE_FAIL;
1083                }
1084            } else {
1085                actionParameter.setValue(variableValue);
1086            }
1087        }
1088
1089        return RUNTIME_CONTEXT_RESOLVE_OK;
1090    }
1091
1092    public void dispose() {
1093        paramManager.dispose();
1094    }
1095
1096    private int resolveOutputHandler() {
1097
1098        // TODO
1099
return RUNTIME_CONTEXT_RESOLVE_OK;
1100    }
1101
1102    // IParameterProvider methods
1103
public String JavaDoc getStringParameter(String JavaDoc name, String JavaDoc defaultValue) {
1104        if ("instance-id".equals(name)) { //$NON-NLS-1$
1105
return instanceId;
1106        } else if ("solution-id".equals(name)) { //$NON-NLS-1$
1107
return solutionName;
1108        }
1109        return defaultValue;
1110        // return runtimeData.getStringProperty( name, defaultValue );
1111
}
1112
1113    // IRuntimeContext input and output methods
1114

1115    public Object JavaDoc getInputParameterValue(String JavaDoc name) {
1116        IActionParameter actionParameter = paramManager.getCurrentInput(name);
1117        if (actionParameter == null) {
1118            // TODO need to know from the action definition if this is ok or not
1119
error(Messages.getErrorString("RuntimeContext.ERROR_0019_INVALID_INPUT_REQUEST", name, actionSequence.getSequenceName())); //$NON-NLS-1$
1120
throw new InvalidParameterException();
1121        }
1122        return actionParameter.getValue();
1123    }
1124
1125    public String JavaDoc getInputParameterStringValue(String JavaDoc name) {
1126        IActionParameter actionParameter = paramManager.getCurrentInput(name);
1127        if (actionParameter == null) {
1128            // TODO need to know from the action definition if this is ok or not
1129
error(Messages.getErrorString("RuntimeContext.ERROR_0019_INVALID_INPUT_REQUEST", name, actionSequence.getSequenceName())); //$NON-NLS-1$
1130
throw new InvalidParameterException();
1131        }
1132        return actionParameter.getStringValue();
1133    }
1134
1135    // TODO Add to Param Manager - Need spcial case to grab loop param only from sequence inputs
1136
private IActionParameter getLoopParameter(String JavaDoc name) {
1137        IActionParameter actionParameter = paramManager.getLoopParameter(name);
1138        if (actionParameter == null) {
1139            // TODO need to know from the action definition if this is ok or not
1140
error(Messages.getErrorString("RuntimeContext.ERROR_0020_INVALID_LOOP_PARAMETER", name, actionSequence.getSequenceName())); //$NON-NLS-1$
1141
throw new InvalidParameterException();
1142        }
1143        return actionParameter;
1144    }
1145
1146    public IActionParameter getInputParameter(String JavaDoc name) {
1147        IActionParameter actionParameter = paramManager.getCurrentInput(name);
1148        if (actionParameter == null) {
1149            // TODO need to know from the action definition if this is ok or not
1150
error(Messages.getErrorString("RuntimeContext.ERROR_0019_INVALID_INPUT_REQUEST", name, actionSequence.getSequenceName())); //$NON-NLS-1$
1151
throw new InvalidParameterException();
1152        }
1153        return actionParameter;
1154    }
1155
1156    public IActionParameter getOutputParameter(String JavaDoc name) {
1157        IActionParameter actionParameter = paramManager.getCurrentOutput(name);
1158        if (actionParameter == null) {
1159            // TODO need to know from the action definition if this is ok or not
1160
error(Messages.getErrorString("RuntimeContext.ERROR_0021_INVALID_OUTPUT_REQUEST", name, actionSequence.getSequenceName())); //$NON-NLS-1$
1161
throw new InvalidParameterException();
1162        }
1163        return actionParameter;
1164    }
1165
1166    public IActionResource getResourceDefintion(String JavaDoc name) {
1167        IActionResource actionResource = paramManager.getCurrentResource( name );
1168
1169        if (actionResource == null) {
1170            // TODO need to know from the action definition if this is ok or not
1171
error(Messages.getErrorString("RuntimeContext.ERROR_0022_INVALID_RESOURCE_REQUEST", name, actionSequence.getSequenceName())); //$NON-NLS-1$
1172
throw new InvalidParameterException();
1173        }
1174        return actionResource;
1175    }
1176
1177    public Set JavaDoc getInputNames() {
1178        return paramManager.getCurrentInputNames();
1179    }
1180    
1181    public void addTempParameter( String JavaDoc name, IActionParameter param ) {
1182        paramManager.addToCurrentInputs( name, param );
1183    }
1184
1185    public OutputStream JavaDoc getOutputStream(String JavaDoc outputName, String JavaDoc mimeType, String JavaDoc extension) {
1186
1187        // TODO support content output versions in the action definition
1188

1189        IActionParameter outputParameter = getOutputParameter(outputName);
1190        if (outputParameter == null) {
1191            error(Messages.getErrorString("RuntimeContext.ERROR_0021_INVALID_OUTPUT_REQUEST", outputName, actionSequence.getSequenceName())); //$NON-NLS-1$
1192
throw new InvalidParameterException();
1193        }
1194
1195        // If there is an output mapping, use that name to store the content
1196
// under.
1197
String JavaDoc contentName = outputName;
1198        if (currentActionDef != null) {
1199            contentName = currentActionDef.getMappedOutputName(outputName);
1200            contentName = (contentName != null) ? contentName : outputName;
1201        }
1202        
1203        if (!IActionParameter.TYPE_CONTENT.equals(outputParameter.getType())) {
1204            error(Messages.getErrorString("RuntimeContext.ERROR_0023_INVALID_OUTPUT_STREAM", outputName)); //$NON-NLS-1$
1205
return null;
1206        }
1207
1208        if (this.outputHandler instanceof ContentRepositoryOutputHandler) {
1209          // Handling for outputting to the content repository already provided
1210
// by the ContentRepositoryOutputHander. If it's the current output
1211
// handler, use it.
1212
IContentItem outputItem = this.outputHandler.getOutputContentItem(null, contentName, actionSequence.getTitle(), null);
1213          outputItem.setMimeType(mimeType);
1214          try {
1215              OutputStream JavaDoc stream = outputItem.getOutputStream(actionSequence.getSequenceName());
1216              if (stream == null) {
1217                  error(Messages.getErrorString("RuntimeContext.ERROR_0026_NO_OUTPUT_STREAM")); //$NON-NLS-1$
1218
}
1219              setOutputValue(outputName, outputItem);
1220              return stream;
1221          } catch (IOException JavaDoc e) {
1222  
1223          }
1224          return null;
1225        }
1226
1227        // get an output stream to hand to the caller
1228
IContentRepository contentRepository = PentahoSystem.getContentRepository(session);
1229        if (contentRepository == null) {
1230            error(Messages.getErrorString("RuntimeContext.ERROR_0024_NO_CONTENT_REPOSITORY")); //$NON-NLS-1$
1231
return null;
1232        }
1233        String JavaDoc extensionFolder = extension;
1234        if (extensionFolder.startsWith(".")) { //$NON-NLS-1$
1235
extensionFolder = extensionFolder.substring(1);
1236        }
1237        String JavaDoc outputFolder = actionSequence.getSequenceName().substring(0, actionSequence.getSequenceName().lastIndexOf('.'));
1238        String JavaDoc contentPath = getSolutionName() + "/" + getSolutionPath() + "/" + outputFolder + "/" + contentName + "/" + extensionFolder; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
1239
// Find the location if it's already there.
1240
IContentLocation contentLocation = null;
1241        try {
1242            contentLocation = contentRepository.getContentLocationByPath(contentPath);
1243        } catch (Exception JavaDoc ex) {
1244            // ignored
1245
}
1246        if (contentLocation == null) {
1247            contentLocation = contentRepository.newContentLocation(contentPath, contentName, contentName, getSolutionName(), true);
1248        }
1249        if (contentLocation == null) {
1250            error(Messages.getErrorString("RuntimeContext.ERROR_0025_INVALID_CONTENT_LOCATION")); //$NON-NLS-1$
1251
return null;
1252        }
1253        // TODO support content expiration
1254

1255        // TODO make the write mode based on the output definition
1256

1257        // Get the content item from the location - if it's there.
1258
IContentItem contentItem = null;
1259        try {
1260            contentItem = contentLocation.getContentItemByName(instanceId);
1261        } catch (Exception JavaDoc ex) {
1262            // Ignored
1263
}
1264        if (contentItem == null) { // DM - Need to keep versions so each report
1265
// in a burst gets saved
1266
contentItem = contentLocation.newContentItem(instanceId, contentName, extension, mimeType, null, IContentItem.WRITEMODE_KEEPVERSIONS);
1267        }
1268
1269        try {
1270            OutputStream JavaDoc stream = contentItem.getOutputStream(actionSequence.getSequenceName());
1271            if (stream == null) {
1272                error(Messages.getErrorString("RuntimeContext.ERROR_0026_NO_OUTPUT_STREAM")); //$NON-NLS-1$
1273
}
1274            setOutputValue(outputName, contentItem);
1275            return stream;
1276        } catch (IOException JavaDoc e) {
1277
1278        }
1279        return null;
1280
1281    }
1282
1283    public void setOutputValue(String JavaDoc name, Object JavaDoc output) {
1284        IActionParameter actionParameter = paramManager.getCurrentOutput(name);
1285        if (actionParameter == null) {
1286            // TODO need to know from the action definition if this is ok or not
1287
error(Messages.getErrorString("RuntimeContext.ERROR_0021_INVALID_OUTPUT_REQUEST", name, actionSequence.getSequenceName())); //$NON-NLS-1$
1288
throw new InvalidParameterException();
1289        }
1290        actionParameter.setValue(output);
1291
1292        if (output instanceof String JavaDoc) {
1293            runtimeData.setStringProperty(name, (String JavaDoc) output);
1294        } else if (output instanceof Date JavaDoc) {
1295            runtimeData.setDateProperty(name, (Date JavaDoc) output);
1296        } else if (output instanceof Long JavaDoc) {
1297            runtimeData.setLongProperty(name, (Long JavaDoc) output);
1298        } else if (output instanceof List JavaDoc) {
1299            runtimeData.setListProperty(name, (List JavaDoc) output);
1300        } else if (output instanceof Map JavaDoc) {
1301            runtimeData.setMapProperty(name, (Map JavaDoc) output);
1302        } else if (output instanceof IContentItem) {
1303            runtimeData.setStringProperty(name, ((IContentItem) output).getPath());
1304        }
1305
1306    }
1307
1308    public DataSource JavaDoc getDataSource(String JavaDoc parameterName) {
1309
1310        // TODO Temp workaround for content repos bug
1311
IActionParameter actionParameter = paramManager.getCurrentInput(parameterName);
1312        if (actionParameter == null) {
1313            error(Messages.getErrorString("RuntimeContext.ERROR_0019_INVALID_INPUT_REQUEST", parameterName, actionSequence.getSequenceName())); //$NON-NLS-1$
1314
throw new InvalidParameterException();
1315        }
1316
1317        Object JavaDoc locObj = actionParameter.getValue();
1318        String JavaDoc location = (locObj instanceof IContentItem) ? ((IContentItem) locObj).getPath() : locObj.toString();
1319
1320        // get an output stream to hand to the caller
1321
IContentRepository contentRepository = PentahoSystem.getContentRepository(session);
1322        if (contentRepository == null) {
1323            error(Messages.getErrorString("RuntimeContext.ERROR_0024_NO_CONTENT_REPOSITORY")); //$NON-NLS-1$
1324
return null;
1325        }
1326
1327        IContentItem contentItem = contentRepository.getContentItemByPath(location);
1328        if (contentItem == null) {
1329            return null;
1330        }
1331
1332        return contentItem.getDataSource();
1333    }
1334
1335    public String JavaDoc getContentUrl(IContentItem contentItem) {
1336        if (contentItem == null) {
1337            return (null);
1338        }
1339        String JavaDoc url = PentahoSystem.getApplicationContext().getBaseUrl();
1340        return (url + "GetContent?id=" + contentItem.getId()); //$NON-NLS-1$
1341
}
1342
1343    public InputStream JavaDoc getInputStream(String JavaDoc parameterName) {
1344
1345        IActionParameter inputParameter = getInputParameter(parameterName);
1346
1347        if (inputParameter == null) {
1348            error(Messages.getErrorString("RuntimeContext.ERROR_0019_INVALID_INPUT_REQUEST", parameterName, actionSequence.getSequenceName())); //$NON-NLS-1$
1349
throw new InvalidParameterException();
1350        }
1351        Object JavaDoc value = inputParameter.getValue();
1352        if (value instanceof IContentItem) {
1353            IContentItem contentItem = (IContentItem) value;
1354            return contentItem.getInputStream();
1355        } else {
1356            return null;
1357        }
1358
1359        /*
1360         * // get an output stream to hand to the caller IContentRepository
1361         * contentRepository = PentahoSystem.getContentRepository( session );
1362         * if( contentRepository == null ) { error(
1363         * Messages.getErrorString("RuntimeContext.ERROR_0024_NO_CONTENT_REPOSITORY") );
1364         * //$NON-NLS-1$ return null; } String outputFolder =
1365         * actionSequence.getSequenceName().substring( 0,
1366         * actionSequence.getSequenceName().lastIndexOf('.') ); String location =
1367         * getSolutionName()+"/"+getSolutionPath()+"/"+outputFolder+"/"+parameterName+"/"+instanceId;
1368         * //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ IContentItem
1369         * contentItem = contentRepository.getContentItemByPath( location );
1370         *
1371         * if( contentItem == null ) { return null; }
1372         *
1373         * return contentItem.getInputStream();
1374         */

1375    }
1376
1377    public Set JavaDoc getOutputNames() {
1378        return paramManager.getCurrentOutputNames();
1379    }
1380
1381    public Set JavaDoc getResourceNames() {
1382        return paramManager.getCurrentResourceNames();
1383    }
1384
1385    public InputStream JavaDoc getResourceInputStream(IActionResource actionResource) {
1386        return PentahoSystem.getSolutionRepository(session).getResourceInputStream(actionResource);
1387    }
1388
1389    public Reader JavaDoc getResourceReader(IActionResource actionResource) throws IOException JavaDoc {
1390        return PentahoSystem.getSolutionRepository(session).getResourceReader(actionResource);
1391    }
1392
1393    public String JavaDoc getResourceAsString(IActionResource actionResource) throws IOException JavaDoc {
1394        return PentahoSystem.getSolutionRepository(session).getResourceAsString(actionResource);
1395    }
1396
1397    public Document getResourceAsDocument(IActionResource actionResource) throws IOException JavaDoc {
1398        return PentahoSystem.getSolutionRepository(session).getResourceAsDocument(actionResource);
1399    }
1400
1401    public DataSource JavaDoc getResourceDataSource(IActionResource actionResource) {
1402        return PentahoSystem.getSolutionRepository(session).getResourceDataSource(actionResource);
1403    }
1404
1405    // IAuditable methods
1406

1407    public String JavaDoc getId() {
1408        return handle;
1409    }
1410
1411    public String JavaDoc getProcessId() {
1412        return processId;
1413    }
1414
1415    public String JavaDoc getActionName() {
1416        return ((actionSequence != null) ? actionSequence.getSequenceName() : Messages.getString("RuntimeContext.DEBUG_NO_ACTION")); //$NON-NLS-1$
1417
}
1418
1419    public String JavaDoc getActionTitle() {
1420        return ((actionSequence != null) ? actionSequence.getTitle() : Messages.getString("RuntimeContext.DEBUG_NO_ACTION")); //$NON-NLS-1$
1421
}
1422
1423    // Audit methods
1424

1425    public void audit(List JavaDoc auditList) {
1426
1427        if (auditList == null || auditList.size() == 0) {
1428            return;
1429        }
1430
1431        // TODO pass in a list of parameter objects instead of parameter names
1432
Iterator JavaDoc it = auditList.iterator();
1433        while (it.hasNext()) {
1434            Element auditNode = (Element) it.next();
1435            String JavaDoc name = auditNode.getText();
1436            String JavaDoc value = getStringParameter(name, ""); //$NON-NLS-1$
1437
AuditHelper.audit(this, session, MessageTypes.INSTANCE_ATTRIBUTE, name, value, null, this);
1438        }
1439
1440    }
1441
1442    public void audit(String JavaDoc messageType, String JavaDoc message, String JavaDoc value, long duration) {
1443        if (!audit) {
1444            return;
1445        }
1446
1447        if (debug)
1448            debug(Messages.getString("RuntimeContext.DEBUG_AUDIT", instanceId, getCurrentComponentName(), messageType)); //$NON-NLS-1$
1449
AuditHelper.audit(this, session, messageType, message, value, new BigDecimal JavaDoc(((double) duration / 1000)), this);
1450    }
1451
1452    public void addInputParameter(String JavaDoc name, IActionParameter param) {
1453        paramManager.addToAllInputs(name, param);
1454    }
1455
1456    public String JavaDoc applyInputsToFormat(String JavaDoc format) {
1457        return TemplateUtil.applyTemplate(format, this);
1458    }
1459
1460    public String JavaDoc applyInputsToFormat(String JavaDoc format, IParameterResolver resolver) {
1461      return TemplateUtil.applyTemplate(format, this, resolver);
1462    }
1463    
1464    // Feebdack form handling
1465

1466    public void sendFeedbackForm() throws IOException JavaDoc {
1467        try {
1468            if (!feedbackAllowed()) {
1469                return;
1470            }
1471            // add the standard parameters that we need
1472
createFeedbackParameter("solution", "solution", "", getSolutionName(), false); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
1473
createFeedbackParameter("action", "action", "", getActionName(), false); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
1474
createFeedbackParameter("path", "path", "", getSolutionPath(), false); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
1475

1476            IParameterProvider parameterProvider = (IParameterProvider) parameterProviders.get( PARAMS_REQUEST );
1477            Iterator JavaDoc parameterNameIterator = parameterProvider.getParameterNames();
1478            while (parameterNameIterator.hasNext()) {
1479                String JavaDoc name = (String JavaDoc) parameterNameIterator.next();
1480                if (!"solution".equals(name) && !"action".equals(name) && !"path".equals(name) && (xformFields.get(name) == null)) {//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
1481
Object JavaDoc value = parameterProvider.getParameter(name);
1482                    if ( value != null ) {
1483                        if ( value.getClass().isArray() ) {
1484                            for ( int i = 0; i < Array.getLength( value ); ++i ) {
1485                                createFeedbackParameter(name, name, "", String.valueOf( Array.get(value, i) ), false); //$NON-NLS-1$
1486
}
1487                        }
1488                        else {
1489                                createFeedbackParameter(name, name, "", value.toString(), false); //$NON-NLS-1$
1490
}
1491                    }
1492                }
1493            }
1494            if (parameterXsl == null) {
1495                // Generate XForm for the parameters needed, transform into
1496
// HTML, and float it down the feedback stream
1497
xformBody.append("<tr><td>"); //$NON-NLS-1$
1498
XForm.createXFormSubmit(PARAMETER_FORM, xformBody, Messages.getString("RuntimeContext.USER_PARAMETER_FORM_SUBMIT")); //$NON-NLS-1$
1499
xformBody.append("</td></tr></table></body>"); //$NON-NLS-1$
1500

1501                String JavaDoc html = XForm.completeXForm(XForm.OUTPUT_HTML_PAGE, PARAMETER_FORM, xformHeader, xformBody, getSession());
1502
1503                if (debug)
1504                    debug(Messages.getString("RuntimeContext.DEBUG_PARAMETER_HTML", html)); //$NON-NLS-1$
1505

1506                outputHandler.getFeedbackContentItem().setMimeType("text/html"); //$NON-NLS-1$
1507
OutputStream JavaDoc os = outputHandler.getFeedbackContentItem().getOutputStream(getActionName());
1508                os.write(html.getBytes());
1509
1510            } else if (parameterTemplate != null) {
1511                String JavaDoc html = XForm.completeXForm(XForm.OUTPUT_HTML_PAGE, PARAMETER_FORM, xformHeader, new StringBuffer JavaDoc(parameterTemplate), getSession());
1512
1513                if (debug)
1514                    debug(Messages.getString("RuntimeContext.DEBUG_PARAMETER_HTML", html)); //$NON-NLS-1$
1515

1516                outputHandler.getFeedbackContentItem().setMimeType("text/html"); //$NON-NLS-1$
1517
OutputStream JavaDoc os = outputHandler.getFeedbackContentItem().getOutputStream(getActionName());
1518                os.write(html.getBytes(LocaleHelper.getSystemEncoding()));
1519            } else if (parameterXsl.endsWith(".xsl")) { //$NON-NLS-1$
1520
String JavaDoc id = actionSequence.getSequenceName();
1521                int pos = id.indexOf('.');
1522                if (pos > -1) {
1523                    id = id.substring(0, pos);
1524                }
1525                // make sure the id can form a valid javascript variable or
1526
// function name
1527
id = id.replace('-', '_');
1528                id = id.replace(' ', '_');
1529                String JavaDoc actionUrl = urlFactory.getActionUrlBuilder().getUrl();
1530                String JavaDoc displayUrl = urlFactory.getDisplayUrlBuilder().getUrl();
1531                String JavaDoc target = (parameterTarget == null) ? "" : parameterTarget; //$NON-NLS-1$
1532
XForm.completeXFormHeader(PARAMETER_FORM, xformHeader);
1533                String JavaDoc xml = "<filters xmlns:xf=\"http://www.w3.org/2002/xforms\">" + //$NON-NLS-1$
1534
xformHeader + "<id><![CDATA[" + //$NON-NLS-1$
1535
id + "]]></id><title><![CDATA[" + //$NON-NLS-1$
1536
Messages.getEncodedString(actionSequence.getTitle()) + "]]></title><description><![CDATA[" + //$NON-NLS-1$
1537
Messages.getEncodedString(actionSequence.getDescription()) + "]]></description><icon><![CDATA[" + //$NON-NLS-1$
1538
actionSequence.getIcon() + "]]></icon><help><![CDATA[" + //$NON-NLS-1$
1539
Messages.getEncodedString(actionSequence.getHelp()) + "]]></help>" + //$NON-NLS-1$
1540
"<action><![CDATA[" + actionUrl + "]]></action>" + //$NON-NLS-1$ //$NON-NLS-2$
1541
"<display><![CDATA[" + displayUrl + "]]></display>" + //$NON-NLS-1$ //$NON-NLS-2$
1542
"<target><![CDATA[" + target + "]]></target>" + //$NON-NLS-1$ //$NON-NLS-2$
1543
xformBody.toString() + "</filters>"; //$NON-NLS-1$
1544
StringBuffer JavaDoc content = XmlHelper.transformXml(parameterXsl, getSolutionName() + File.separator + getSolutionPath(), xml, new HashMap JavaDoc(), getSession());
1545
1546                if (content == null) {
1547                    // TODO surface this error
1548
} else {
1549                    outputHandler.getFeedbackContentItem().setMimeType("text/html"); //$NON-NLS-1$
1550
OutputStream JavaDoc os = outputHandler.getFeedbackContentItem().getOutputStream(null);
1551                    os.write(content.toString().getBytes(LocaleHelper.getSystemEncoding()));
1552                }
1553            }
1554        } catch (Exception JavaDoc e) {
1555            error( Messages.getErrorString( "RuntimeContext.ERROR_0030_SEND_FEEDBACKFORM" ) ); //$NON-NLS-1$
1556
}
1557
1558    }
1559
1560    private void addXFormHeader() {
1561
1562        XForm.createXFormHeader(PARAMETER_FORM, xformHeader);
1563
1564        IActionResource resource = paramManager.getCurrentResource( parameterXsl );
1565
1566        if (!parameterXsl.endsWith(".xsl") && (resource != null)) { //$NON-NLS-1$
1567
// load the parameter page template
1568
try {
1569                parameterTemplate = getResourceAsString(resource);
1570            } catch (Exception JavaDoc e) {
1571                // TODO log this
1572
}
1573        }
1574
1575    }
1576
1577    /**
1578     * @deprecated
1579     * Unused
1580     */

1581    public void createFeedbackParameter(IActionParameter actionParam) {
1582        if (actionParam.hasSelections()) {
1583            // TODO support display styles
1584
// TODO support help hints
1585
createFeedbackParameter(actionParam.getName(), actionParam.getSelectionDisplayName(), "", actionParam.getStringValue(), actionParam.getSelectionValues(), actionParam.getSelectionNameMap(), null); //$NON-NLS-1$
1586
}
1587    }
1588
1589    public void createFeedbackParameter(SelectionMapper selMap, String JavaDoc fieldName, Object JavaDoc defaultValues) {
1590        if (selMap != null) {
1591            // TODO support help hints
1592
createFeedbackParameter(fieldName, selMap.getSelectionDisplayName(), "", defaultValues, selMap.getSelectionValues(), selMap.getSelectionNameMap(), selMap.getDisplayStyle()); //$NON-NLS-1$
1593
}
1594    }
1595
1596    public void createFeedbackParameter(String JavaDoc fieldName, String JavaDoc displayName, String JavaDoc hint, Object JavaDoc defaultValues, List JavaDoc values, Map JavaDoc dispNames, String JavaDoc displayStyle) {
1597        if (values == null) {
1598            return;
1599        }
1600        if ((xformHeader == null) || (xformHeader.length() == 0)) {
1601          // this is the first parameter, need to create the header...
1602
addXFormHeader();
1603        }
1604
1605        // See if the parameter is defined in the template. If so, then
1606
// don't add it to the XForm.
1607
if (checkForFieldInTemplate(fieldName)) {
1608          return;
1609        }
1610
1611        int type = (values.size() < 6) ? XForm.TYPE_RADIO : XForm.TYPE_SELECT;
1612        if (displayStyle != null) {
1613            if ("text-box".equals(displayStyle)) { //$NON-NLS-1$
1614
type = XForm.TYPE_TEXT;
1615            } else if ("radio".equals(displayStyle)) { //$NON-NLS-1$
1616
type = XForm.TYPE_RADIO;
1617            } else if ("select".equals(displayStyle)) { //$NON-NLS-1$
1618
type = XForm.TYPE_SELECT;
1619            } else if ("list".equals(displayStyle)) { //$NON-NLS-1$
1620
type = XForm.TYPE_LIST;
1621            } else if ("list-multi".equals(displayStyle)) { //$NON-NLS-1$
1622
type = XForm.TYPE_LIST_MULTI;
1623            } else if ("check-multi".equals(displayStyle)) { //$NON-NLS-1$
1624
type = XForm.TYPE_CHECK_MULTI;
1625            } else if ("check-multi-scroll".equals(displayStyle)) { //$NON-NLS-1$
1626
type = XForm.TYPE_CHECK_MULTI_SCROLL;
1627            } else if ("check-multi-scroll-2-column".equals(displayStyle)) { //$NON-NLS-1$
1628
type = XForm.TYPE_CHECK_MULTI_SCROLL_2_COLUMN;
1629            } else if ("check-multi-scroll-3-column".equals(displayStyle)) { //$NON-NLS-1$
1630
type = XForm.TYPE_CHECK_MULTI_SCROLL_3_COLUMN;
1631            } else if ("check-multi-scroll-4-column".equals(displayStyle)) { //$NON-NLS-1$
1632
type = XForm.TYPE_CHECK_MULTI_SCROLL_4_COLUMN;
1633            }
1634
1635        }
1636        fieldName = paramManager.getActualRequestParameterName(fieldName);
1637        if (hint == null) {
1638            hint = ""; //$NON-NLS-1$
1639
}
1640        if (parameterXsl == null) {
1641            // create some xform to represent this parameter...
1642
xformBody.append(Messages.getString("RuntimeContext.CODE_XFORM_CONTROL_LABEL_START", displayName)); //$NON-NLS-1$
1643
XForm.createXFormControl(type, fieldName, defaultValues, values, dispNames, PARAMETER_FORM, xformHeader, xformBody);
1644            xformBody.append(Messages.getString("RuntimeContext.CODE_XFORM_CONTROL_LABEL_END")); //$NON-NLS-1$
1645
} else if (parameterTemplate != null) {
1646            StringBuffer JavaDoc body = new StringBuffer JavaDoc();
1647            XForm.createXFormControl(type, fieldName, defaultValues, values, dispNames, PARAMETER_FORM, xformHeader, body);
1648            parameterTemplate = parameterTemplate.replaceAll("\\{" + fieldName + "\\}", body.toString()); //$NON-NLS-1$ //$NON-NLS-2$
1649
} else if (parameterXsl.endsWith(".xsl")) { //$NON-NLS-1$
1650
StringBuffer JavaDoc body = new StringBuffer JavaDoc();
1651            XForm.createXFormControl(type, fieldName, defaultValues, values, dispNames, PARAMETER_FORM, xformHeader, body);
1652            xformBody.append("<filter><id><![CDATA[" + fieldName + "]]></id>") //$NON-NLS-1$ //$NON-NLS-2$
1653
.append("<title><![CDATA[" + displayName + "]]></title>") //$NON-NLS-1$ //$NON-NLS-2$
1654
.append("<help><![CDATA[" + hint + "]]></help><control>") //$NON-NLS-1$ //$NON-NLS-2$
1655
.append(body).append("</control></filter>"); //$NON-NLS-1$
1656
}
1657
1658        xformFields.put(fieldName, fieldName);
1659
1660    }
1661
1662    public boolean checkForFieldInTemplate(String JavaDoc fieldName) {
1663      //
1664
// This pattern looks for:
1665
//
1666
// id="fieldname"
1667
// iD="fieldname"
1668
// Id="fieldname"
1669
// ID="fieldname"
1670
// id='fieldname'
1671
// iD='fieldname'
1672
// Id='fieldname'
1673
// ID='fieldname'
1674
//
1675
// TODO: This is actually optimistic searching as it's not looking for the
1676
// string within the form portion of the template. IMO, to be more robust,
1677
// this needs to at least look for something only within a form and only
1678
// within a control on a form.
1679
if ( (parameterTemplate == null) || (parameterTemplate.length()==0) ) {
1680        return false;
1681      }
1682      String JavaDoc regex = "[iI][dD]=[\'\"]" + fieldName + "[\'\"]"; //$NON-NLS-1$ //$NON-NLS-2$
1683
Pattern JavaDoc pattern = null;
1684      // Normally shouldn't need to synchronize. But, a Java bug in
1685
// pattern compilation on multi-processor machines results in the
1686
// need to synchronize a small block of code. If/when this problem
1687
// is fixed, we can remove this synchronization lock.
1688
// See: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6238699
1689
synchronized(PATTERN_COMPILE_LOCK) {
1690        pattern = Pattern.compile(regex);
1691      }
1692      Matcher JavaDoc matcher = pattern.matcher(parameterTemplate);
1693      if (matcher.find()) {
1694        return true;
1695      }
1696      return false;
1697    }
1698    
1699    public void createFeedbackParameter(String JavaDoc fieldName, String JavaDoc displayName, String JavaDoc hint, String JavaDoc defaultValue, boolean visible) {
1700
1701      if ((xformHeader == null) || (xformHeader.length() == 0)) {
1702        // this is the first parameter, need to create the header...
1703
addXFormHeader();
1704      }
1705      if (parameterTemplate != null) {
1706            // see if the parameter is defined in the HTML template
1707
if (checkForFieldInTemplate(fieldName)) {
1708            return;
1709          }
1710        }
1711        if (hint == null) {
1712            hint = ""; //$NON-NLS-1$
1713
}
1714        fieldName = paramManager.getActualRequestParameterName(fieldName);
1715        if (parameterXsl == null) {
1716            // create some xform to represent this parameter...
1717

1718            if (visible) {
1719                xformBody.append(Messages.getString("RuntimeContext.CODE_XFORM_CONTROL_LABEL_START", displayName)); //$NON-NLS-1$
1720
// xformBody.append( "<tr><td class=\"portlet-font\">").append(
1721
// displayName ).append("</td><td class=\"portlet-font\">"
1722
// );//$NON-NLS-1$ //$NON-NLS-2$
1723
}
1724            XForm.createXFormControl(fieldName, defaultValue, PARAMETER_FORM, xformHeader, xformBody, visible);
1725            if (visible) {
1726                xformBody.append(Messages.getString("RuntimeContext.CODE_XFORM_CONTROL_LABEL_END")); //$NON-NLS-1$
1727
// xformBody.append( "</td></tr>" ); //$NON-NLS-1$
1728
}
1729        } else if (parameterTemplate != null) {
1730            StringBuffer JavaDoc body = new StringBuffer JavaDoc();
1731            if (visible) {
1732                XForm.createXFormControl(fieldName, defaultValue, PARAMETER_FORM, xformHeader, body, visible);
1733            } else {
1734                try {
1735                    String JavaDoc value = defaultValue.replaceAll("&", "&amp;"); //$NON-NLS-1$//$NON-NLS-2$
1736
value = value.replaceAll("\"", "''"); //$NON-NLS-1$ //$NON-NLS-2$
1737
body.append("<input type=\"hidden\" name=\"" + fieldName + "\" value=\"" + value + "\"></input>"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
1738
} catch (Exception JavaDoc e) {
1739                    body.append("<input type=\"hidden\" name=\"" + fieldName + "\" value=\"" + defaultValue + "\"></input>"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
1740
}
1741            }
1742            parameterTemplate = parameterTemplate.replaceAll("\\{" + fieldName + "\\}", body.toString()); //$NON-NLS-1$ //$NON-NLS-2$
1743
} else {
1744            if (visible) {
1745                StringBuffer JavaDoc body = new StringBuffer JavaDoc();
1746                XForm.createXFormControl(fieldName, defaultValue, PARAMETER_FORM, xformHeader, body, visible);
1747                xformBody.append("<filter><id><![CDATA[" + fieldName + "]]></id>") //$NON-NLS-1$ //$NON-NLS-2$
1748
.append("<title><![CDATA[" + displayName + "]]></title>") //$NON-NLS-1$ //$NON-NLS-2$
1749
.append("<help><![CDATA[" + hint + "]]></help><control>") //$NON-NLS-1$ //$NON-NLS-2$
1750
.append(body).append("</control></filter>"); //$NON-NLS-1$
1751

1752            } else {
1753                try {
1754                    // String value = URLEncoder.encode(defaultValue, "UTF-8" );
1755
// //$NON-NLS-1$
1756
String JavaDoc value = defaultValue.replaceAll("&", "&amp;"); //$NON-NLS-1$//$NON-NLS-2$
1757
value = value.replaceAll("\"", "''"); //$NON-NLS-1$ //$NON-NLS-2$
1758
xformBody.append("<input type=\"hidden\" name=\"" + fieldName + "\" value=\"" + value + "\"></input>"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
1759
} catch (Exception JavaDoc e) {
1760                    xformBody.append("<input type=\"hidden\" name=\"" + fieldName + "\" value=\"" + defaultValue + "\"></input>"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
1761
}
1762            }
1763        }
1764        xformFields.put(fieldName, fieldName);
1765    }
1766
1767    public void setParameterXsl(String JavaDoc xsl) {
1768        this.parameterXsl = xsl;
1769    }
1770
1771    public void setParameterTarget(String JavaDoc target) {
1772        this.parameterTarget = target;
1773    }
1774
1775    public String JavaDoc getLogId() {
1776        return logId;
1777    }
1778
1779    /**
1780     * Forces the immediate write of runtime data to underlying persistence
1781     * mechanism. In the case of using Hibernate for the runtime data
1782     * persistence, this works out to a call to HibernateUtil.flush().
1783     */

1784    public void forceSaveRuntimeData() {
1785        if (runtimeData != null) {
1786            runtimeData.forceSave();
1787        }
1788    }
1789
1790    /**
1791     * Gets the output type prefered by the handler. Values are defined in
1792     * org.pentaho.core.solution.IOutputHander and are OUTPUT_TYPE_PARAMETERS,
1793     * OUTPUT_TYPE_CONTENT, or OUTPUT_TYPE_DEFAULT
1794     *
1795     * @return Output type
1796     */

1797    public int getOutputPreference() {
1798        return outputHandler.getOutputPreference();
1799    }
1800
1801    public void setOutputHandler(IOutputHandler outputHandler) {
1802        this.outputHandler = outputHandler;
1803    }
1804
1805}
1806
Popular Tags