KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > forms > transformation > FormsPipelineConfig


1 /*
2  * Copyright 1999-2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.cocoon.forms.transformation;
17
18 import org.apache.avalon.framework.parameters.Parameters;
19
20 import org.apache.cocoon.components.flow.FlowHelper;
21 import org.apache.cocoon.components.flow.WebContinuation;
22 import org.apache.cocoon.environment.ObjectModelHelper;
23 import org.apache.cocoon.environment.Request;
24 import org.apache.cocoon.environment.Session;
25 import org.apache.cocoon.forms.formmodel.Form;
26 import org.apache.cocoon.i18n.I18nUtils;
27 import org.apache.cocoon.util.Deprecation;
28
29 import org.apache.commons.jxpath.JXPathContext;
30 import org.apache.commons.jxpath.JXPathException;
31 import org.apache.commons.jxpath.Variables;
32 import org.xml.sax.Attributes JavaDoc;
33 import org.xml.sax.SAXException JavaDoc;
34 import org.xml.sax.helpers.AttributesImpl JavaDoc;
35
36 import java.io.IOException JavaDoc;
37 import java.io.StringReader JavaDoc;
38 import java.util.ArrayList JavaDoc;
39 import java.util.HashMap JavaDoc;
40 import java.util.List JavaDoc;
41 import java.util.Locale JavaDoc;
42 import java.util.Map JavaDoc;
43
44 /**
45  * @version $Id: FormsPipelineConfig.java 289538 2005-09-16 13:46:22Z sylvain $
46  */

47 public class FormsPipelineConfig {
48
49     /**
50      * Default key under which the Cocoon Forms form instance is stored in the JXPath context.
51      */

52     public static final String JavaDoc CFORMSKEY = "CocoonFormsInstance";
53
54     /**
55      * Name of the request attribute under which the Cocoon Form is stored (optional). */

56     private final String JavaDoc attributeName;
57
58     /**
59      * Pointer to the current request object.
60      */

61     private final Request request;
62
63     /**
64      * Initialized jxpathcontext to evaluate passed expressions with.
65      */

66     private final JXPathContext jxpathContext;
67
68     /**
69      * Containts locale specified as a parameter to the transformer, if any.
70      */

71     private final Locale JavaDoc localeParameter;
72
73     /**
74      * The locale currently used by the transformer.
75      */

76     private Locale JavaDoc locale;
77
78     /**
79      * Value for the action attribute of the form.
80      */

81     private String JavaDoc formAction;
82
83     /**
84      * Value for the method attribute of the form.
85      */

86     private String JavaDoc formMethod;
87
88
89     private FormsPipelineConfig(JXPathContext jxpc, Request req, Locale JavaDoc localeParam,
90                                 String JavaDoc attName, String JavaDoc actionExpression, String JavaDoc method) {
91         this.attributeName = attName;
92         this.request = req;
93         this.jxpathContext =jxpc;
94         this.localeParameter = localeParam;
95         this.formAction = translateText(actionExpression);
96         this.formMethod = method;
97     }
98
99     /**
100      * Creates and initializes a FormsPipelineConfig object based on the passed
101      * arguments of the setup() of the specific Pipeline-component.
102      *
103      * @param objectModel the objectmodel as passed in the setup()
104      * @param parameters the parameters as passed in the setup()
105      * @return an instance of FormsPipelineConfig initialized according to the
106      * settings in the sitemap.
107      */

108     public static FormsPipelineConfig createConfig(Map JavaDoc objectModel, Parameters parameters) {
109         // create and set the jxpathContext...
110
Object JavaDoc flowContext = FlowHelper.getContextObject(objectModel);
111         WebContinuation wk = FlowHelper.getWebContinuation(objectModel);
112         JXPathContext jxpc = JXPathContext.newContext(flowContext);
113         // We manually create a cocoon object here to provide the same way
114
// of accessing things as in the jxtg
115
// as soon as we have our unified om, we should use that
116
Request request = ObjectModelHelper.getRequest(objectModel);
117         Session session = request.getSession(false);
118         final Map JavaDoc cocoonOM = new HashMap JavaDoc();
119         cocoonOM.put("continuation", wk);
120         cocoonOM.put("request", request);
121         if ( session != null ) {
122             cocoonOM.put("session", session);
123         }
124         cocoonOM.put("parameters", parameters);
125
126         FormsVariables vars = new FormsVariables();
127         vars.declareVariable("cocoon", cocoonOM);
128         // These four are deprecated!
129
vars.declareVariable("continuation", wk);
130         vars.declareVariable("request", request);
131         vars.declareVariable("session", session);
132         vars.declareVariable("parameters", parameters);
133         vars.addDeprecatedVariable("continuation");
134         vars.addDeprecatedVariable("request");
135         vars.addDeprecatedVariable("session");
136         vars.addDeprecatedVariable("parameters");
137         jxpc.setVariables(vars);
138
139         Locale JavaDoc localeParameter = null;
140         String JavaDoc localeStr = parameters.getParameter("locale", null);
141         if (localeStr != null) {
142             localeParameter = I18nUtils.parseLocale(localeStr);
143         }
144
145         String JavaDoc attributeName = parameters.getParameter("attribute-name", null);
146         String JavaDoc actionExpression = parameters.getParameter("form-action", null);
147         String JavaDoc formMethod = parameters.getParameter("form-method", null);
148         //TODO (20031223 mpo)think about adding form-encoding for the Generator.
149
// Note generator will also need some text to go on the submit-button?
150
// Alternative to adding more here is to apply xinclude ?
151

152         return new FormsPipelineConfig(jxpc, request, localeParameter,
153                 attributeName, actionExpression, formMethod);
154     }
155
156     /**
157      * Overloads {@link #findForm(String)} by setting the jxpath-expression to null
158      */

159     public Form findForm() throws SAXException JavaDoc {
160         return this.findForm(null);
161     }
162
163     /**
164      * Finds the form from the current request-context based on the settings of
165      * this configuration object. The fall-back search-procedure is as follows:
166      * <ol><li>Use the provided jxpathExpression (if not null)</li>
167      * <li>Use the setting of the 'attribute-name' parameter on the request</li>
168      * <li>Obtain the form from it's default location in the flow context</li>
169      * </ol>
170      *
171      * @param jxpathExpression that should be pointing to the form
172      * @return the found form if found
173      * @throws SAXException in any of the following cases:
174      * <ul><li>The provided jxpathExpression (if not null) not point to a
175      * {@link Form} instance.</li>
176      * <li>The request is not holding a {@link Form} instance under the key
177      * specified by 'attribute-name' (if specified)</li>
178      * <li>Both jxpathExpression and 'attribute-name' were not specified AND
179      * also the default location was not holding a valid {@link Form} instance.</li>
180      * </ol>
181      */

182     public Form findForm(String JavaDoc jxpathExpression) throws SAXException JavaDoc {
183         Object JavaDoc form = null;
184         if (jxpathExpression != null) {
185             form = this.jxpathContext.getValue(jxpathExpression);
186             if (form == null) {
187                 throw new SAXException JavaDoc("No Cocoon Form found at location \"" + jxpathExpression + "\".");
188             } else if (!(form instanceof Form)) {
189                 throw new SAXException JavaDoc("Object returned by expression \"" + jxpathExpression + "\" is not a Cocoon Form.");
190             }
191         } else if (this.attributeName != null) { // then see if an attribute-name was specified
192
form = this.request.getAttribute(this.attributeName);
193             if (form == null) {
194                 throw new SAXException JavaDoc("No Cocoon Form found in request attribute with name \"" + this.attributeName + "\"");
195             } else if (!(form instanceof Form)) {
196                 throw new SAXException JavaDoc("Object found in request (attribute = '" + this.attributeName + "') is not a Cocoon Form.");
197             }
198         } else { // and then see if we got a form from the flow
199
jxpathExpression = "/" + FormsPipelineConfig.CFORMSKEY;
200             try {
201                 form = this.jxpathContext.getValue(jxpathExpression);
202             } catch (JXPathException e) { /* do nothing */ }
203             if (form == null) {
204                 throw new SAXException JavaDoc("No Cocoon Form found.");
205             }
206         }
207         return (Form)form;
208     }
209
210     /**
211      * Replaces JXPath expressions embedded inside #{ and } by their value.
212      * This will parse the passed String looking for #{} occurences and then
213      * uses the {@link #evaluateExpression(String)} to evaluate the found expression.
214      *
215      * @return the original String with it's #{}-parts replaced by the evaulated results.
216      */

217     public String JavaDoc translateText(String JavaDoc original) {
218         if (original==null) {
219             return null;
220         }
221
222         StringBuffer JavaDoc expression;
223         StringBuffer JavaDoc translated = new StringBuffer JavaDoc();
224         StringReader JavaDoc in = new StringReader JavaDoc(original);
225         int chr;
226         try {
227             while ((chr = in.read()) != -1) {
228                 char c = (char) chr;
229                 if (c == '#') {
230                     chr = in.read();
231                     if (chr != -1) {
232                         c = (char) chr;
233                         if (c == '{') {
234                             expression = new StringBuffer JavaDoc();
235                             boolean more = true;
236                             while ( more ) {
237                                 more = false;
238                                 if ((chr = in.read()) != -1) {
239                                     c = (char)chr;
240                                     if (c != '}') {
241                                         expression.append(c);
242                                         more = true;
243                                     } else {
244                                         translated.append(evaluateExpression(expression.toString()).toString());
245                                     }
246                                 } else {
247                                     translated.append('#').append('{').append(expression);
248                                 }
249                             }
250                         }
251                     } else {
252                         translated.append((char) chr);
253                     }
254                 } else {
255                     translated.append(c);
256                 }
257             }
258         } catch (IOException JavaDoc ignored) {
259             ignored.printStackTrace();
260         }
261         return translated.toString();
262     }
263
264     /**
265      * Evaluates the passed xpath expression using the internal jxpath context
266      * holding the declared variables:
267      * <ol><li>continuation: as made available by flowscript</li>
268      * <li>request: as present in the cocoon processing environment</li>
269      * <li>session: as present in the cocoon processing environment</li>
270      * <li>parameters: as present in the cocoon sitemap node of the pipeline component</li></ol>
271      *
272      * @param expression
273      * @return the object-value resulting the expression evaluation.
274      */

275     public Object JavaDoc evaluateExpression(String JavaDoc expression) {
276         return this.jxpathContext.getValue(expression);
277     }
278
279     public Locale JavaDoc getLocale() {
280         return locale;
281     }
282
283     public void setLocale(Locale JavaDoc locale) {
284         this.locale = locale;
285     }
286
287     public Locale JavaDoc getLocaleParameter() {
288         return localeParameter;
289     }
290
291     /**
292      * The value for the wi:form-generated/@action.
293      * Note: wi:form-template copies this from its wt:form-template counterpart.
294      *
295      * @return the {@link #translateText(String)} result of the 'form-action' sitemap
296      * parameter to the pipeline component, or null if that parameter was not set.
297      */

298     public String JavaDoc getFormAction() {
299         return formAction;
300     }
301
302     /**
303      * The value for the wi:form-generated/@method.
304      * Note: wi:form-template copies this from its wt:form-template counterpart.
305      *
306      * @return the value of the 'form-method' sitemap parameter to the pipeline
307      * component. (or 'null' if it was not set.)
308      */

309     public String JavaDoc getFormMethod() {
310         return formMethod;
311     }
312
313
314     /**
315      * Sets the form method to use in the generator/transformer that uses this.
316      *
317      * @param method to use in the generated form should be "POST", "GET" or null
318      */

319     public void setFormMethod(String JavaDoc method) {
320         this.formMethod = method;
321     }
322
323     /**
324      * The grouped attributes to set on the wi:form-generated element.
325      * Note: wi:form-template copies this from its wt:form-template counterpart.
326      *
327      * @see #getFormAction()
328      * @see #getFormMethod()
329      */

330     public Attributes JavaDoc getFormAttributes() {
331         AttributesImpl JavaDoc attrs = new org.apache.cocoon.xml.AttributesImpl();
332         addFormAttributes(attrs);
333         return attrs;
334     }
335
336     public void addFormAttributes(AttributesImpl JavaDoc attrs) {
337         if (getFormAction() != null) {
338             attrs.addAttribute("", "action", "action", "CDATA", getFormAction());
339         }
340         if (getFormMethod() != null){
341             attrs.addAttribute("", "method", "method", "CDATA", getFormMethod());
342         }
343     }
344
345     public static final class FormsVariables implements Variables {
346
347         final Map JavaDoc vars = new HashMap JavaDoc();
348         final List JavaDoc deprecatedNames = new ArrayList JavaDoc();
349
350         public void addDeprecatedVariable(String JavaDoc name) {
351             this.deprecatedNames.add(name);
352         }
353
354         /* (non-Javadoc)
355          * @see org.apache.commons.jxpath.Variables#declareVariable(java.lang.String, java.lang.Object)
356          */

357         public void declareVariable(String JavaDoc name, Object JavaDoc value) {
358             this.vars.put(name, value);
359         }
360
361         /* (non-Javadoc)
362          * @see org.apache.commons.jxpath.Variables#getVariable(java.lang.String)
363          */

364         public Object JavaDoc getVariable(String JavaDoc name) {
365             Object JavaDoc value = this.vars.get(name);
366             if ( deprecatedNames.contains(name) ) {
367                 Deprecation.logger.warn("CForms: usage of the variable '" + name + "' is deprecated."+
368                                         "Please use 'cocoon/" + name + "' instead. The usage of just '"+
369                                         name+"' will be removed in Cocoon 2.2.");
370             }
371             return value;
372         }
373
374         /* (non-Javadoc)
375          * @see org.apache.commons.jxpath.Variables#isDeclaredVariable(java.lang.String)
376          */

377         public boolean isDeclaredVariable(String JavaDoc name) {
378             return this.vars.containsKey(name);
379         }
380
381         /* (non-Javadoc)
382          * @see org.apache.commons.jxpath.Variables#undeclareVariable(java.lang.String)
383          */

384         public void undeclareVariable(String JavaDoc name) {
385             this.vars.remove(name);
386         }
387     }
388 }
389
Popular Tags