KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > webapps > session > transformation > SessionPostTransformer


1 /*
2  * Copyright 1999-2004 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.webapps.session.transformation;
17
18 import java.io.ByteArrayInputStream JavaDoc;
19 import java.io.IOException JavaDoc;
20 import java.util.Map JavaDoc;
21 import java.util.Properties JavaDoc;
22
23 import javax.xml.transform.OutputKeys JavaDoc;
24
25 import org.apache.avalon.framework.configuration.Configuration;
26 import org.apache.avalon.framework.configuration.ConfigurationException;
27 import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
28 import org.apache.avalon.framework.configuration.SAXConfigurationHandler;
29 import org.apache.cocoon.ProcessingException;
30 import org.apache.cocoon.acting.ValidatorActionResult;
31 import org.apache.cocoon.components.source.SourceUtil;
32 import org.apache.cocoon.environment.Session;
33 import org.apache.cocoon.webapps.session.SessionConstants;
34 import org.apache.cocoon.xml.XMLUtils;
35 import org.apache.excalibur.source.Source;
36 import org.apache.excalibur.source.SourceException;
37 import org.apache.excalibur.source.SourceParameters;
38 import org.w3c.dom.DocumentFragment JavaDoc;
39 import org.w3c.dom.Node JavaDoc;
40 import org.xml.sax.Attributes JavaDoc;
41 import org.xml.sax.SAXException JavaDoc;
42 import org.xml.sax.helpers.AttributesImpl JavaDoc;
43
44 /**
45  * This is the session post transformer. It does all the setting and
46  * destroying. Thus it should be the last transformer (before the xsl) in
47  * the pipeline.
48  * For performance and simplicity reasons this transformer inherits from
49  * the SessionPreTransformer, although this is not needed (but then the
50  * implementation of the SessionTransformer would be very unperformant).
51  *
52  * @author <a HREF="mailto:cziegeler@s-und-n.de">Carsten Ziegeler</a>
53  * @version CVS $Id: SessionPostTransformer.java 30932 2004-07-29 17:35:38Z vgritsenko $
54  */

55 public class SessionPostTransformer extends SessionPreTransformer {
56
57     public static final String JavaDoc DELETECONTEXT_ELEMENT = "deletecontext";
58     public static final String JavaDoc DELETECONTEXT_NAME_ATTRIBUTE = "name";
59
60     public static final String JavaDoc SETXML_ELEMENT = "setxml";
61     public static final String JavaDoc SETXML_CONTEXT_ATTRIBUTE = "context";
62     public static final String JavaDoc SETXML_PATH_ATTRIBUTE = "path";
63
64     public static final String JavaDoc APPENDXML_ELEMENT = "appendxml";
65     public static final String JavaDoc APPENDXML_CONTEXT_ATTRIBUTE = "context";
66     public static final String JavaDoc APPENDXML_PATH_ATTRIBUTE = "path";
67
68     public static final String JavaDoc REMOVEXML_ELEMENT = "removexml";
69     public static final String JavaDoc REMOVEXML_CONTEXT_ATTRIBUTE = "context";
70     public static final String JavaDoc REMOVEXML_PATH_ATTRIBUTE = "path";
71
72     public static final String JavaDoc MERGEXML_ELEMENT = "mergexml";
73     public static final String JavaDoc MERGEXML_CONTEXT_ATTRIBUTE = "context";
74     public static final String JavaDoc MERGEXML_PATH_ATTRIBUTE = "path";
75
76     public static final String JavaDoc SAVECONTEXT_ELEMENT = "savexml";
77     public static final String JavaDoc SAVECONTEXT_CONTEXT_ATTRIBUTE = "context";
78     public static final String JavaDoc SAVECONTEXT_PATH_ATTRIBUTE = "path"; // optional
79

80     public static final String JavaDoc INPUTXML_ELEMENT = "inputxml";
81     public static final String JavaDoc INPUTXML_CONTEXT_ATTRIBUTE = "context";
82     public static final String JavaDoc INPUTXML_PATH_ATTRIBUTE = "path";
83     public static final String JavaDoc INPUTXML_NAME_ATTRIBUTE = "name";
84     public static final String JavaDoc INPUTXML_TYPE_ATTRIBUTE = "type"; // optional
85
public static final String JavaDoc INPUTXML_VALIDATIONRESULT_ATTRIBUTE = "valresult";
86
87     /** The form element */
88     public static final String JavaDoc FORM_ELEMENT = "form";
89
90     /** The form action element */
91     public static final String JavaDoc FORM_ACTION_ELEMENT = "action";
92
93     /** The form content element */
94     public static final String JavaDoc FORM_CONTENT_ELEMENT = "content";
95
96     /** The form validation rules */
97     public static final String JavaDoc FORM_VALIDATION_ELEMENT = "validate";
98     public static final String JavaDoc FORM_VALIDATION_SOURCE_ATTRIBUTE = "src";
99     public static final String JavaDoc FORM_VALIDATESET_ELEMENT = "constraint-set";
100
101     /** State: no element parsed */
102     private static final int STATE_OUTSIDE = 0;
103     /** State: form element */
104     private static final int STATE_FORM = 1;
105
106     /** The current state */
107     private int state;
108
109     /** The current form name */
110     private String JavaDoc formName;
111
112     /** The validation results */
113     private Map JavaDoc validationResultMap;
114
115     public void setupTransforming() throws ProcessingException, SAXException JavaDoc, IOException JavaDoc {
116         super.setupTransforming();
117         this.state = STATE_OUTSIDE;
118         this.formName = null;
119     }
120
121     /**
122      * This is the real implementation of the startElement event
123      * for the transformer
124      * The event is checked for a valid element and the corresponding command
125      * is executed.
126      */

127     public void startTransformingElement(String JavaDoc uri, String JavaDoc name, String JavaDoc raw, Attributes JavaDoc attr)
128             throws ProcessingException, IOException JavaDoc, SAXException JavaDoc {
129         if (this.getLogger().isDebugEnabled()) {
130             this.getLogger().debug("BEGIN startTransformingElement uri=" + uri + ", name=" + name
131                                                               + ", raw=" + raw + ", attr=" + attr);
132         }
133         if (name.equals(DELETECONTEXT_ELEMENT)) {
134             this.getContextManager().deleteContext(attr.getValue(DELETECONTEXT_NAME_ATTRIBUTE));
135
136         } else if (name.equals(SETXML_ELEMENT)) {
137             this.startRecording();
138             stack.push(attr.getValue(SETXML_CONTEXT_ATTRIBUTE));
139             stack.push(attr.getValue(SETXML_PATH_ATTRIBUTE));
140
141             // Element: mergexml
142
} else if (name.equals(MERGEXML_ELEMENT)) {
143             this.startRecording();
144             stack.push(attr.getValue(MERGEXML_CONTEXT_ATTRIBUTE));
145             stack.push(attr.getValue(MERGEXML_PATH_ATTRIBUTE));
146
147             // Element: appendxml
148
} else if (name.equals(APPENDXML_ELEMENT)) {
149             this.startRecording();
150             stack.push(attr.getValue(APPENDXML_CONTEXT_ATTRIBUTE));
151             stack.push(attr.getValue(APPENDXML_PATH_ATTRIBUTE));
152
153             // Element: removexml
154
} else if (name.equals(REMOVEXML_ELEMENT)) {
155             this.startTextRecording();
156             stack.push(attr.getValue(REMOVEXML_CONTEXT_ATTRIBUTE));
157             stack.push(attr.getValue(REMOVEXML_PATH_ATTRIBUTE));
158
159         } else if (name.equals(SAVECONTEXT_ELEMENT)) {
160             this.startParametersRecording();
161             stack.push(attr.getValue(SAVECONTEXT_CONTEXT_ATTRIBUTE));
162             if (attr.getValue(SAVECONTEXT_PATH_ATTRIBUTE) != null) {
163                 stack.push(attr.getValue(SAVECONTEXT_PATH_ATTRIBUTE));
164             } else {
165                 stack.push("/");
166             }
167
168             // Element: inputxml
169
} else if (name.equals(INPUTXML_ELEMENT)) {
170             stack.push(attr.getValue(INPUTXML_CONTEXT_ATTRIBUTE));
171             String JavaDoc fieldname = attr.getValue(INPUTXML_NAME_ATTRIBUTE);
172             stack.push(fieldname);
173             stack.push(attr.getValue(INPUTXML_PATH_ATTRIBUTE));
174
175             AttributesImpl JavaDoc newattr = new AttributesImpl JavaDoc();
176             newattr.addAttribute("", INPUTXML_NAME_ATTRIBUTE, INPUTXML_NAME_ATTRIBUTE, "CDATA", fieldname);
177             if (attr.getValue(INPUTXML_TYPE_ATTRIBUTE) != null) {
178                 newattr.addAttribute("", INPUTXML_TYPE_ATTRIBUTE, INPUTXML_TYPE_ATTRIBUTE, "CDATA",
179                                      attr.getValue(INPUTXML_TYPE_ATTRIBUTE));
180             }
181
182             ValidatorActionResult validationResult = null;
183             if (validationResultMap != null && validationResultMap.get(fieldname) != null) {
184                 validationResult = (ValidatorActionResult)validationResultMap.get(fieldname);
185                 newattr.addAttribute("", INPUTXML_VALIDATIONRESULT_ATTRIBUTE,
186                                      INPUTXML_VALIDATIONRESULT_ATTRIBUTE,"CDATA", validationResult.toString());
187             }
188
189             super.startTransformingElement("", name, name, newattr); // remove namespace
190
this.startRecording();
191
192             // Element form
193
} else if (name.equals(FORM_ELEMENT) && this.state == STATE_OUTSIDE) {
194             String JavaDoc formName = attr.getValue("name");
195             if (formName == null) {
196                 throw new ProcessingException("The name attribute of the form element is required.");
197             }
198             this.stack.push(new Integer JavaDoc(this.state));
199             this.state = STATE_FORM;
200             this.stack.push(new AttributesImpl JavaDoc(attr));
201
202             // Element form action
203
} else if (name.equals(FORM_ACTION_ELEMENT) && this.state == STATE_FORM) {
204             this.startTextRecording();
205
206             // Element form content
207
} else if (name.equals(FORM_CONTENT_ELEMENT) && this.state == STATE_FORM) {
208             // get validation results to be used for inputxml elements
209
validationResultMap = (Map JavaDoc)this.getSessionManager().getSession(true)
210                                                  .getAttribute(this.formName + "validation-result");
211
212             // Element form validation rules
213
} else if (name.equals(FORM_VALIDATION_ELEMENT) && this.state == STATE_FORM) {
214             this.startRecording();
215             if (attr.getValue(FORM_VALIDATION_SOURCE_ATTRIBUTE) != null) {
216                 stack.push(attr.getValue(FORM_VALIDATION_SOURCE_ATTRIBUTE));
217             } else {
218                 stack.push("EMPTY");
219             }
220
221         } else {
222             super.startTransformingElement(uri, name, raw, attr);
223         }
224         if (this.getLogger().isDebugEnabled()) {
225             this.getLogger().debug("END startTransformingElement");
226         }
227     }
228
229     public void endTransformingElement(String JavaDoc uri, String JavaDoc name, String JavaDoc raw)
230             throws ProcessingException, IOException JavaDoc, SAXException JavaDoc {
231         if (this.getLogger().isDebugEnabled()) {
232             this.getLogger().debug("BEGIN endTransformingElement uri=" + uri + ", name=" + name + ", raw=" + raw);
233         }
234         if (name.equals(DELETECONTEXT_ELEMENT)) {
235             // do nothing, the context was destroyed on the startElement event
236

237             // Element: setxml
238
} else if (name.equals(SETXML_ELEMENT)) {
239             String JavaDoc path = (String JavaDoc)stack.pop();
240             String JavaDoc contextName = (String JavaDoc)stack.pop();
241             this.getSessionManager().setContextFragment(contextName, path, this.endRecording());
242
243             // Element: mergexml
244
} else if (name.equals(MERGEXML_ELEMENT)) {
245             String JavaDoc path = (String JavaDoc)stack.pop();
246             String JavaDoc contextName = (String JavaDoc)stack.pop();
247             this.getSessionManager().mergeContextFragment(contextName, path, this.endRecording());
248
249             // Element: appendxml
250
} else if (name.equals(APPENDXML_ELEMENT)) {
251             String JavaDoc path = (String JavaDoc)stack.pop();
252             String JavaDoc contextName = (String JavaDoc)stack.pop();
253             this.getSessionManager().appendContextFragment(contextName, path, this.endRecording());
254
255             // Element: removexml
256
} else if (name.equals(REMOVEXML_ELEMENT)) {
257             String JavaDoc path = (String JavaDoc)stack.pop();
258             String JavaDoc contextName = (String JavaDoc)stack.pop();
259             // result is ignored
260
endTextRecording();
261             this.getSessionManager().removeContextFragment(contextName, path);
262
263             // Element: savexml
264
} else if (name.equals(SAVECONTEXT_ELEMENT)) {
265             String JavaDoc path = (String JavaDoc)stack.pop();
266             String JavaDoc contextName = (String JavaDoc)stack.pop();
267             SourceParameters pars = this.endParametersRecording((SourceParameters)null);
268             pars.setSingleParameterValue("contextname", contextName);
269             pars.setSingleParameterValue("path", path);
270
271             this.getContextManager().getContext(contextName).saveXML(path, pars);
272
273             // Element: inputxml
274
} else if (name.equals(INPUTXML_ELEMENT)) {
275             String JavaDoc path = (String JavaDoc)this.stack.pop();
276             String JavaDoc fieldname = (String JavaDoc)this.stack.pop();
277             String JavaDoc contextname = (String JavaDoc)this.stack.pop();
278             DocumentFragment JavaDoc defaultFragment = this.endRecording();
279
280             if (this.formName == null) {
281                 throw new ProcessingException("The inputxml must be contained inside a form.");
282             }
283             DocumentFragment JavaDoc value = this.getFormManager().registerInputField(contextname, path,
284                                                                               fieldname, formName);
285             if (value == null) {
286                 value = defaultFragment;
287             }
288             this.sendEvents(value);
289             super.endTransformingElement("", name, name);
290
291             // Element form
292
} else if (name.equals(FORM_ELEMENT) && this.state == STATE_FORM) {
293             this.state = ((Integer JavaDoc)this.stack.pop()).intValue();
294             this.sendEndElementEvent("form");
295             this.formName = null;
296
297             // Element form action
298
} else if (name.equals(FORM_ACTION_ELEMENT) && this.state == STATE_FORM) {
299             String JavaDoc action = this.endTextRecording();
300             AttributesImpl JavaDoc a = (AttributesImpl JavaDoc)this.stack.pop();
301             this.formName = a.getValue("name");
302             boolean hasPars = (action.indexOf("?") != -1);
303             action = this.response.encodeURL(action + (hasPars ? '&' : '?')
304                                              + SessionConstants.SESSION_FORM_PARAMETER + '=' + this.formName);
305             a.addAttribute("", "action", "action", "CDATA", action);
306             if (a.getValue("method") == null) {
307                 a.addAttribute("", "method", "method", "CDATA", "POST");
308             }
309             this.sendStartElementEvent("form", a);
310
311             // Element form content
312
} else if (name.equals(FORM_CONTENT_ELEMENT) && this.state == STATE_FORM) {
313             // ignore this
314

315             // Element form validation rules
316
} else if (name.equals(FORM_VALIDATION_ELEMENT) && this.state == STATE_FORM) {
317             if (this.formName == null) {
318                 throw new ProcessingException("The validate element must be contained inside a form.");
319             }
320             DocumentFragment JavaDoc validationDoc = this.endRecording();
321             String JavaDoc source = (String JavaDoc)stack.pop();
322             if (!source.equals("EMPTY")) {
323                 // get configuration from external file
324
// referenced by "src" attribute of "validate" element
325
try {
326                     Source resource = this.resolver.resolveURI(source);
327                     SAXConfigurationHandler saxBuilder = new SAXConfigurationHandler();
328                     SourceUtil.parse(this.manager, resource, saxBuilder);
329
330                     Configuration conf = saxBuilder.getConfiguration();
331                     Session session = this.getSessionManager().getSession(true);
332                     session.setAttribute(this.formName, conf);
333
334                     if (validationDoc != null) {
335                         //validationDoc contains "constraint-set" element
336
validationDoc.normalize();
337                         Node JavaDoc validationNode = validationDoc.getFirstChild();
338                         while (validationNode.getNodeType() != Node.ELEMENT_NODE) {
339                             validationNode = validationNode.getNextSibling();
340                             if (validationNode == null) {
341                                 break;
342                             }
343                         }
344                         if (validationNode != null && validationNode.getNodeType() == Node.ELEMENT_NODE
345                                 && validationNode.getNodeName().equals(FORM_VALIDATESET_ELEMENT)) {
346                             Properties JavaDoc props = XMLUtils.createPropertiesForXML(false);
347                             props.put(OutputKeys.ENCODING, "ISO-8859-1");
348                             String JavaDoc validationXML = XMLUtils.serializeNode(validationNode, props);
349                             DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
350                             conf = builder.build(new ByteArrayInputStream JavaDoc(validationXML.getBytes()));
351                             session.setAttribute(this.formName + "constraint-set", conf);
352                         }
353                     }
354
355                 } catch (SourceException se) {
356                     throw new ProcessingException("Cannot resolve" + source, se);
357                 } catch (ConfigurationException ce) {
358                     throw new ProcessingException("Error building Configuration out of constraint-set element", ce);
359                 }
360
361             } else if (validationDoc != null) {
362                 //validationDoc contains the validation rules inline
363
try {
364                     validationDoc.normalize();
365                     Node JavaDoc validationNode = validationDoc.getFirstChild();
366                     while (validationNode.getNodeType() != Node.ELEMENT_NODE) {
367                         validationNode = validationNode.getNextSibling();
368                         if (validationNode == null) {
369                             break;
370                         }
371                     }
372                     if (validationNode != null && validationNode.getNodeType() == Node.ELEMENT_NODE
373                             && validationNode.getNodeName().equals("root")) {
374                         Properties JavaDoc props = XMLUtils.createPropertiesForXML(false);
375                         props.put(OutputKeys.ENCODING, "ISO-8859-1");
376                         String JavaDoc validationXML = XMLUtils.serializeNode(validationNode, props);
377                         DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
378                         Configuration conf = builder.build(new ByteArrayInputStream JavaDoc(validationXML.getBytes()));
379                         Session session = this.getSessionManager().getSession(true);
380                         session.setAttribute(this.formName, conf);
381                         //the constraint-set to validate is the first and single one
382
session.setAttribute(this.formName + "constraint-set", conf.getChildren("constraint-set")[0]);
383
384                     }
385                 } catch (ConfigurationException ce) {
386                     throw new ProcessingException("Error building Configuration out of validation XML", ce);
387                 }
388             }
389
390         } else {
391             super.endTransformingElement(uri, name, raw);
392         }
393         if (this.getLogger().isDebugEnabled()) {
394             this.getLogger().debug("END endTransformingElement");
395         }
396     }
397 }
398
Popular Tags