KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > components > flow > apples > samples > BindingWoodyApple


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.components.flow.apples.samples;
17
18 import java.io.IOException JavaDoc;
19 import java.io.OutputStream JavaDoc;
20 import java.util.HashMap JavaDoc;
21 import java.util.Locale JavaDoc;
22 import java.util.Map JavaDoc;
23
24 import javax.xml.transform.OutputKeys JavaDoc;
25 import javax.xml.transform.Transformer JavaDoc;
26 import javax.xml.transform.TransformerFactory JavaDoc;
27 import javax.xml.transform.sax.SAXTransformerFactory JavaDoc;
28 import javax.xml.transform.sax.TransformerHandler JavaDoc;
29 import javax.xml.transform.stream.StreamResult JavaDoc;
30
31 import org.apache.avalon.framework.logger.AbstractLogEnabled;
32 import org.apache.avalon.framework.service.ServiceException;
33 import org.apache.avalon.framework.service.ServiceManager;
34 import org.apache.avalon.framework.service.Serviceable;
35 import org.apache.cocoon.ProcessingException;
36 import org.apache.cocoon.components.flow.apples.AppleController;
37 import org.apache.cocoon.components.flow.apples.AppleRequest;
38 import org.apache.cocoon.components.flow.apples.AppleResponse;
39 import org.apache.cocoon.forms.FormContext;
40 import org.apache.cocoon.forms.FormManager;
41 import org.apache.cocoon.forms.binding.Binding;
42 import org.apache.cocoon.forms.binding.BindingManager;
43 import org.apache.cocoon.forms.formmodel.Form;
44 import org.apache.cocoon.forms.transformation.FormsPipelineConfig;
45 import org.apache.cocoon.xml.dom.DOMStreamer;
46 import org.apache.excalibur.source.ModifiableSource;
47 import org.apache.excalibur.source.Source;
48 import org.apache.excalibur.source.SourceResolver;
49 import org.apache.excalibur.xml.dom.DOMParser;
50 import org.w3c.dom.Document JavaDoc;
51 import org.xml.sax.InputSource JavaDoc;
52
53 /**
54  * BindingWoodyApple
55  */

56 public class BindingWoodyApple extends AbstractLogEnabled implements AppleController, Serviceable {
57
58     private static final boolean CONTINUE = false;
59     private static final boolean FINISHED = true;
60
61     private Form form;
62     private Binding binding;
63     private Document JavaDoc document;
64     private ServiceManager serviceManager;
65     private String JavaDoc formPipeURI;
66     private String JavaDoc validPipeURI;
67     private String JavaDoc backendURI;
68     private Map JavaDoc wrapperContextMap;
69     private State state;
70
71     private interface State {
72         public void processRequest(AppleRequest req, AppleResponse res) throws ProcessingException;
73     }
74
75     private final State initializationDelegate = new State() {
76         public void processRequest(AppleRequest req, AppleResponse res) throws ProcessingException {
77             BindingWoodyApple.this.processInitialization(req, res);
78         }
79     };
80
81     private final State validationDelegate = new State() {
82         public void processRequest(AppleRequest req, AppleResponse res) throws ProcessingException {
83             BindingWoodyApple.this.processValidation(req, res);
84         }
85     };
86
87     {
88         state = initializationDelegate;
89     }
90
91
92     public void process(AppleRequest req, AppleResponse res) throws ProcessingException {
93         this.state.processRequest(req, res);
94     }
95
96     protected void processInitialization(AppleRequest req, AppleResponse res) throws ProcessingException {
97
98         String JavaDoc formURI = req.getSitemapParameter("form-src");
99         String JavaDoc bindURI = req.getSitemapParameter("binding-src");
100         this.backendURI = req.getSitemapParameter("documentURI");
101         this.formPipeURI = req.getSitemapParameter("form-pipe");
102         this.validPipeURI = req.getSitemapParameter("valid-pipe");
103
104         FormManager formManager = null;
105         BindingManager binderManager = null;
106         SourceResolver resolver = null;
107         Source formSource = null;
108         Source bindSource = null;
109         Source documentSource = null;
110
111         try {
112             formManager = (FormManager) this.serviceManager.lookup(FormManager.ROLE);
113             binderManager = (BindingManager) this.serviceManager.lookup(BindingManager.ROLE);
114             resolver = (SourceResolver) this.serviceManager.lookup(SourceResolver.ROLE);
115
116             formSource = resolver.resolveURI(formURI);
117             this.form = formManager.createForm(formSource);
118
119             bindSource = resolver.resolveURI(bindURI);
120             this.binding = binderManager.createBinding(bindSource);
121
122             documentSource = resolver.resolveURI(this.backendURI);
123             this.document = loadDocumentFromSource(documentSource);
124             this.binding.loadFormFromModel(this.form, this.document);
125
126             this.getLogger().debug("apple initialisation finished .. ");
127             this.state = validationDelegate;
128
129             completeResult(res, this.formPipeURI, CONTINUE);
130         } catch (Exception JavaDoc e) {
131             throw new ProcessingException("Failed to initialize BindingWoodyApple. ", e);
132         } finally {
133             if (formManager != null) {
134                 this.serviceManager.release(formManager);
135             }
136             if (binderManager != null) {
137                 this.serviceManager.release(binderManager);
138             }
139             if (resolver != null) {
140                 if (formSource != null) {
141                     resolver.release(formSource);
142                 }
143                 if (bindSource != null) {
144                     resolver.release(bindSource);
145                 }
146                 if (documentSource != null) {
147                     resolver.release(documentSource);
148                 }
149                 this.serviceManager.release(resolver);
150             }
151         }
152     }
153
154     protected void processValidation(AppleRequest req, AppleResponse res) throws ProcessingException {
155
156         Source documentTarget = null;
157         SourceResolver resolver = null;
158
159         try {
160             FormContext formContext = new FormContext(req.getCocoonRequest(), Locale.US);
161
162             if (!this.form.process(formContext)) {
163                 // form is not valid or there was just an event handled
164
completeResult(res, this.formPipeURI, CONTINUE);
165             } else {
166
167                 resolver = (SourceResolver) this.serviceManager.lookup(SourceResolver.ROLE);
168                 documentTarget = resolver.resolveURI(makeTargetURI(this.backendURI));
169
170                 this.binding.saveFormToModel(this.form, this.document);
171                 saveDocumentToSource(documentTarget, this.document);
172
173                 completeResult(res, this.validPipeURI, FINISHED);
174             }
175
176             getLogger().debug("apple processing done .. ");
177         } catch (Exception JavaDoc e) {
178             throw new ProcessingException("Error processing BindingWoodyApple", e);
179         } finally {
180             if (resolver != null) {
181                 if (documentTarget != null) {
182                     resolver.release(documentTarget);
183                 }
184                 this.serviceManager.release(resolver);
185             }
186         }
187     }
188
189     private void completeResult(AppleResponse res, String JavaDoc uri, boolean finished) {
190         res.sendPage(uri, getContextMap());
191         // TODO think about transferring the fact that the use case has ended.
192
}
193
194     private Map JavaDoc getContextMap() {
195         if (this.wrapperContextMap == null) {
196             if (this.form != null) {
197                 this.wrapperContextMap = new HashMap JavaDoc();
198                 this.wrapperContextMap.put(FormsPipelineConfig.CFORMSKEY, this.form);
199             }
200         }
201         return this.wrapperContextMap;
202     }
203
204
205     /**
206      * Translate source path into target path so we keep a clean source XML
207      *
208      * @param path
209      * @return
210      */

211     private String JavaDoc makeTargetURI(String JavaDoc path) {
212         final String JavaDoc sfx = ".xml";
213         final String JavaDoc newSfx = "-result.xml";
214         if (path.endsWith(sfx)) {
215             path = path.substring(0, path.length() - sfx.length());
216         }
217         return path + newSfx;
218     }
219
220
221     /**
222      * Saves (and serializes) the given Document to the path indicated by the
223      * specified Source.
224      *
225      * @param docTarget must be the ModifieableSource where the doc will be
226      * serialized to.
227      * @param doc org.w3c.dom.Document to save
228      * @throws ProcessingException
229      */

230     private void saveDocumentToSource(Source docTarget, Document JavaDoc doc)
231         throws ProcessingException {
232         DOMParser parser = null;
233         OutputStream JavaDoc os = null;
234         String JavaDoc uri = docTarget.getURI();
235
236         try {
237             parser =
238                 (DOMParser) this.serviceManager.lookup(DOMParser.ROLE);
239             getLogger().debug("request to save file " + uri);
240             TransformerFactory JavaDoc tf = TransformerFactory.newInstance();
241
242             if (docTarget instanceof ModifiableSource
243                 && tf.getFeature(SAXTransformerFactory.FEATURE)) {
244
245                 ModifiableSource ws = (ModifiableSource) docTarget;
246                 os = ws.getOutputStream();
247                 SAXTransformerFactory JavaDoc stf = (SAXTransformerFactory JavaDoc) tf;
248                 TransformerHandler JavaDoc th = stf.newTransformerHandler();
249                 Transformer JavaDoc t = th.getTransformer();
250                 t.setOutputProperty(OutputKeys.INDENT, "true");
251                 t.setOutputProperty(OutputKeys.METHOD, "xml");
252                 th.setResult(new StreamResult JavaDoc(os));
253
254                 DOMStreamer streamer = new DOMStreamer(th);
255                 streamer.stream(doc);
256             } else {
257                 getLogger().error("Cannot not write to source " + uri);
258             }
259         } catch (Exception JavaDoc e) {
260             getLogger().error("Error parsing mock file " + uri, e);
261             throw new ProcessingException(
262                 "Error parsing mock file " + uri,
263                 e);
264         } finally {
265             if (parser != null) {
266                 this.serviceManager.release(parser);
267             }
268             if (os != null) {
269                 try {
270                     os.flush();
271                     os.close();
272                 } catch (IOException JavaDoc e1) {
273                     getLogger().warn(
274                         "Failed to flush/close the outputstream. ",
275                         e1);
276                 }
277             }
278         }
279     }
280
281
282     /**
283      * Loads (and parses) the Document from the specified Source
284      *
285      * @param documentSrc
286      * @return
287      * @throws ProcessingException
288      */

289     private Document JavaDoc loadDocumentFromSource(Source documentSrc)
290         throws ProcessingException {
291         DOMParser parser = null;
292         try {
293             parser =
294                 (DOMParser) this.serviceManager.lookup(DOMParser.ROLE);
295             getLogger().debug(
296                 "request to load file " + documentSrc.getURI());
297             InputSource JavaDoc input = new InputSource JavaDoc(documentSrc.getURI());
298             return parser.parseDocument(input);
299         } catch (Exception JavaDoc e) {
300             throw new ProcessingException(
301                 "failed to load file to bind to: ",
302                 e);
303         } finally {
304             if (parser != null) {
305                 this.serviceManager.release(parser);
306             }
307         }
308     }
309
310
311     public void service(ServiceManager serviceManager) throws ServiceException {
312         this.serviceManager = serviceManager;
313     }
314 }
315
Popular Tags