KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > lenya > cms > cocoon > acting > ParentChildCreatorAction


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  */

17
18 /* $Id: ParentChildCreatorAction.java 170279 2005-05-15 23:30:10Z michi $ */
19
20 package org.apache.lenya.cms.cocoon.acting;
21
22 import org.apache.avalon.framework.configuration.Configurable;
23 import org.apache.avalon.framework.configuration.Configuration;
24 import org.apache.avalon.framework.configuration.ConfigurationException;
25 import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
26 import org.apache.avalon.framework.parameters.ParameterException;
27 import org.apache.avalon.framework.parameters.Parameters;
28
29 import org.apache.cocoon.ProcessingException;
30 import org.apache.cocoon.acting.AbstractComplementaryConfigurableAction;
31 import org.apache.cocoon.environment.ObjectModelHelper;
32 import org.apache.cocoon.environment.Redirector;
33 import org.apache.cocoon.environment.Request;
34 import org.apache.cocoon.environment.Session;
35 import org.apache.cocoon.environment.SourceResolver;
36
37 import org.apache.excalibur.source.Source;
38
39 import org.apache.lenya.cms.authoring.ParentChildCreatorInterface;
40
41 import org.dom4j.Attribute;
42 import org.dom4j.Document;
43 import org.dom4j.DocumentHelper;
44 import org.dom4j.Element;
45 import org.dom4j.XPath;
46
47 import org.dom4j.io.SAXReader;
48
49 import java.io.File JavaDoc;
50
51 import java.util.Enumeration JavaDoc;
52 import java.util.HashMap JavaDoc;
53 import java.util.List JavaDoc;
54 import java.util.Map JavaDoc;
55 import java.util.StringTokenizer JavaDoc;
56
57 public class ParentChildCreatorAction extends AbstractComplementaryConfigurableAction
58     implements Configurable {
59     private String JavaDoc treeAuthoringPath = null;
60     private String JavaDoc docsPath = null;
61     private String JavaDoc doctypesPath = null;
62
63     /**
64      * DOCUMENT ME!
65      *
66      * @param conf DOCUMENT ME!
67      *
68      * @throws ConfigurationException DOCUMENT ME!
69      */

70     public void configure(Configuration conf) throws ConfigurationException {
71         super.configure(conf);
72
73         treeAuthoringPath = conf.getChild("tree-authoring").getAttribute("href");
74         docsPath = conf.getChild("docs").getAttribute("href");
75         doctypesPath = conf.getChild("doctypes").getAttribute("href");
76         getLogger().debug("CONFIGURATION:\nAUTHORING PATH OF TREE=" + treeAuthoringPath);
77     }
78
79     /**
80      * DOCUMENT ME!
81      *
82      * @param redirector DOCUMENT ME!
83      * @param resolver DOCUMENT ME!
84      * @param objectModel DOCUMENT ME!
85      * @param src DOCUMENT ME!
86      * @param parameters DOCUMENT ME!
87      *
88      * @return DOCUMENT ME!
89      *
90      * @throws Exception DOCUMENT ME!
91      */

92     public Map JavaDoc act(Redirector redirector, SourceResolver resolver, Map JavaDoc objectModel, String JavaDoc src,
93         Parameters parameters) throws Exception JavaDoc {
94         Source input_source = resolver.resolveURI("");
95         String JavaDoc sitemapParentPath = input_source.getURI();
96         sitemapParentPath = sitemapParentPath.substring(5); // Remove "file:" protocol
97

98         getLogger().debug(".act(): PARENT PATH OF SITEMAP: " + sitemapParentPath);
99
100         // Get request object
101
Request request = ObjectModelHelper.getRequest(objectModel);
102
103         if (request == null) {
104             getLogger().error("No request object");
105
106             return null;
107         }
108
109         // Get parameters
110
String JavaDoc parentid = request.getParameter("parentid");
111         if (parentid == null) {
112             getLogger().warn("No parentid parameter defined! It might be necessary to specify a parentid request parameter.");
113         }
114         String JavaDoc childid = request.getParameter("childid");
115         if (childid == null) {
116             getLogger().error("No childid parameter defined! Please specify childid as request parameter.");
117             throw new Exception JavaDoc("No childname defined!");
118         }
119         String JavaDoc childname = request.getParameter("childname");
120         if (childname == null) {
121             getLogger().error("No childname defined! Please specify childname as request parameter which is being used as label within a sitetree or topic map.");
122             throw new Exception JavaDoc("No childname defined!");
123         }
124         String JavaDoc childtype = request.getParameter("childtype");
125         if (childtype == null) {
126             getLogger().error("No childtype defined! Please specify childtype as request parameter with value either \"branch\" or \"leaf\".");
127             throw new Exception JavaDoc("No childname defined!");
128         }
129         short childType;
130
131         if (childtype.equals("branch")) {
132             childType = ParentChildCreatorInterface.BRANCH_NODE;
133         } else if (childtype.equals("leaf")) {
134             childType = ParentChildCreatorInterface.LEAF_NODE;
135         } else {
136             getLogger().error("No such child type: " + childtype);
137             return null;
138         }
139
140         String JavaDoc doctype = request.getParameter("doctype");
141         if (doctype == null) {
142             getLogger().warn("No doctype defined! Please specify doctype as request parameter, which is being used to resolve the creator within doctypes.xconf. Otherwise the DefaultCreator class is being used (see below)!");
143         }
144         String JavaDoc language = request.getParameter("language");
145
146         if (!validate(parentid, childid, childname, childtype, doctype)) {
147             getLogger().error("Exception: Validation of parameters failed");
148
149             return null;
150         }
151
152         // Get session
153
Session session = request.getSession(true);
154
155         if (session == null) {
156             getLogger().error("No session object");
157
158             return null;
159         }
160
161         // Get creator
162
ParentChildCreatorInterface creator = null;
163         String JavaDoc absoluteDoctypesPath = sitemapParentPath + doctypesPath;
164         Document doctypesDoc = new SAXReader().read("file:" + absoluteDoctypesPath +
165                 "doctypes.xconf");
166         Attribute creator_src = (Attribute) doctypesDoc.selectSingleNode("/doctypes/doc[@type='" +
167                 doctype + "']/creator/@src");
168
169         if (creator_src != null) {
170             getLogger().info(".act(): Creator found for \"" + doctype + "\": " +
171                 creator_src.getName() + " " + creator_src.getPath() + " " + creator_src.getValue());
172
173             // now get the constructor that accepts the configuration
174
Class JavaDoc creatorClass = Class.forName(creator_src.getValue());
175             creator = (ParentChildCreatorInterface) creatorClass.newInstance();
176         } else {
177             getLogger().warn("No creator found for \"" + doctype +
178                 "\". DefaultParentChildreator will be taken.");
179             creator = new org.apache.lenya.cms.authoring.DefaultCreator();
180         }
181
182         getLogger().debug(".act(): Creator : " + creator.getClass().getName());
183
184         // Init creator
185
// "Read" the configuration from the DOM node
186
DefaultConfigurationBuilder defaultConfigBuilder = new DefaultConfigurationBuilder();
187         Configuration[] docTypeConfigs = defaultConfigBuilder.buildFromFile(absoluteDoctypesPath +
188                 "doctypes.xconf").getChildren();
189
190         Configuration doctypeConf = null;
191
192         for (int i = 0; i < docTypeConfigs.length; i++) {
193             String JavaDoc typeName = docTypeConfigs[i].getAttribute("type");
194
195             if (typeName.equals(doctype)) {
196                 doctypeConf = docTypeConfigs[i].getChild("creator", false);
197             }
198         }
199
200         creator.init(doctypeConf);
201
202         // Transaction should actually be started here!
203
String JavaDoc treefilename = sitemapParentPath + treeAuthoringPath;
204         getLogger().debug(".act(): Filename of tree: " + treefilename);
205
206         if (!new File JavaDoc(treefilename).exists()) {
207             getLogger().warn("No sitetree or topic map: " + treefilename);
208         } else {
209             if (!updateTree(childtype, childType, childid, childname, parentid, doctype, creator, treefilename)) return null;
210         }
211         // Transaction should actually be finished here!
212

213
214         // Create actual document
215
// grab all the parameters from session, request params and
216
// sitemap params
217
HashMap JavaDoc allParameters = new HashMap JavaDoc();
218         String JavaDoc[] names = parameters.getNames();
219
220         for (int i = 0; i < names.length; i++) {
221             String JavaDoc name = names[i];
222             String JavaDoc value = null;
223
224             try {
225                 value = parameters.getParameter(name);
226             } catch (ParameterException pe) {
227                 value = null;
228             }
229
230             allParameters.put(name, value);
231         }
232
233         Enumeration JavaDoc requestParameters = request.getParameterNames();
234
235         while (requestParameters.hasMoreElements()) {
236             String JavaDoc requestParameterName = (String JavaDoc) requestParameters.nextElement();
237
238             if (allParameters.containsKey(requestParameterName)) {
239                 // we do not allow name clashes
240
throw new ProcessingException("Name clash in request parameter " +
241                     "and sitemap parameter: " + requestParameterName);
242             }
243
244             allParameters.put(requestParameterName, request.getParameter(requestParameterName));
245         }
246
247         Enumeration JavaDoc sessionAttributeNames = session.getAttributeNames();
248
249         while (sessionAttributeNames.hasMoreElements()) {
250             String JavaDoc sessionAttributeName = (String JavaDoc) sessionAttributeNames.nextElement();
251
252             if (allParameters.containsKey(sessionAttributeName)) {
253                 // we do not allow name clashes
254
throw new ProcessingException("Name clash in session attribute " +
255                     "and request parameter or sitemap parameter: " + sessionAttributeName);
256             }
257
258             allParameters.put(sessionAttributeName, session.getAttribute(sessionAttributeName));
259         }
260
261         try {
262             creator.create(new File JavaDoc(absoluteDoctypesPath + "samples"),
263                 new File JavaDoc(sitemapParentPath + docsPath + parentid), childid, childType, childname, language,
264                 allParameters);
265         } catch (Exception JavaDoc e) {
266             getLogger().error("Creator threw exception: " + e);
267         }
268
269         // Redirect to referer
270
String JavaDoc parent_uri = (String JavaDoc) session.getAttribute(
271                 "org.apache.lenya.cms.cocoon.acting.ParentChildCreatorAction.parent_uri");
272         getLogger().info(".act(): Child added");
273
274         HashMap JavaDoc actionMap = new HashMap JavaDoc();
275         actionMap.put("parent_uri", parent_uri);
276         session.removeAttribute(
277             "org.apache.lenya.cms.cocoon.acting.ParentChildCreatorAction.parent_uri");
278
279         return actionMap;
280     }
281
282     /**
283      * DOCUMENT ME!
284      *
285      * @param parentid DOCUMENT ME!
286      * @param childid DOCUMENT ME!
287      * @param childname DOCUMENT ME!
288      * @param childtype DOCUMENT ME!
289      * @param doctype DOCUMENT ME!
290      *
291      * @return DOCUMENT ME!
292      */

293     public boolean validate(String JavaDoc parentid, String JavaDoc childid, String JavaDoc childname, String JavaDoc childtype,
294         String JavaDoc doctype) {
295         getLogger().debug(".validate(): parentid=" + parentid + " ; childid=" + childid +
296             " ; childname=" + childname + " ; childtype=" + childtype + " ; doctype=" + doctype);
297
298         if ((childid.indexOf(" ") >= 0) || (childid.length() == 0)) {
299             return false;
300         }
301
302         if (childname.length() == 0) {
303             return false;
304         }
305
306         return true;
307     }
308
309     /**
310      *
311      */

312     private boolean updateTree(String JavaDoc childtype, short childType, String JavaDoc childid, String JavaDoc childname, String JavaDoc parentid, String JavaDoc doctype, ParentChildCreatorInterface creator, String JavaDoc treefilename) throws Exception JavaDoc {
313         Document doc = new SAXReader().read("file:" + treefilename);
314
315         // Get parent element
316
StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(parentid, "/");
317         String JavaDoc xpath_string = "/tree/branch"; // Trunk of tree
318

319         while (st.hasMoreTokens()) {
320             xpath_string = xpath_string + "/branch[@relURI='" + st.nextToken() + "']";
321         }
322
323         getLogger().debug("XPATH: " + xpath_string);
324
325         XPath xpathSelector = DocumentHelper.createXPath(xpath_string);
326         List JavaDoc nodes = xpathSelector.selectNodes(doc);
327
328         if (nodes.isEmpty()) {
329             getLogger().error(".act(): No nodes: " + xpath_string);
330             getLogger().error(".act(): No child added!");
331
332             return false;
333         }
334
335         Element parent_element = (Element) nodes.get(0);
336         getLogger().debug("PARENT ELEMENT: " + parent_element.getPath());
337
338         // Set child type: branch or leaf
339
childType = creator.getChildType(childType);
340
341         if (childType == ParentChildCreatorInterface.BRANCH_NODE) {
342             childtype = "branch";
343         } else {
344             childtype = "leaf";
345         }
346
347         // Check if child already exists
348
String JavaDoc newChildXPath = xpath_string + "/" + childtype;
349         getLogger().debug("CHECK: " + newChildXPath);
350
351         if (doc.selectSingleNode(newChildXPath + "[@relURI='" +
352                     creator.generateTreeId(childid, childType) + "']") != null) {
353             getLogger().error("Exception: XPath exists: " + newChildXPath + "[@relURI='" +
354                 creator.generateTreeId(childid, childType) + "']");
355             getLogger().error("No child added");
356
357             return false;
358         }
359
360         // Add node: branch or leaf
361
parent_element.addElement(childtype)
362                       .addAttribute("relURI", creator.generateTreeId(childid, childType))
363                       .addAttribute("doctype", doctype).addAttribute("menuName",
364             creator.getChildName(childname));
365         getLogger().debug("Tree has been modified: " + doc.asXML());
366
367         // Write new tree
368
java.io.FileWriter JavaDoc fileWriter = new java.io.FileWriter JavaDoc(treefilename);
369         doc.write(fileWriter);
370         fileWriter.close();
371
372         return true;
373     }
374 }
375
Popular Tags