KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > webapps > portal > context > SessionContextImpl


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.portal.context;
17
18 import org.apache.cocoon.ProcessingException;
19 import org.apache.cocoon.environment.ObjectModelHelper;
20 import org.apache.cocoon.environment.Request;
21 import org.apache.cocoon.webapps.portal.PortalConstants;
22 import org.apache.cocoon.webapps.portal.components.PortalManager;
23 import org.apache.cocoon.webapps.portal.components.PortalManagerImpl;
24 import org.apache.cocoon.webapps.session.context.SessionContext;
25 import org.apache.cocoon.xml.IncludeXMLConsumer;
26 import org.apache.cocoon.xml.dom.DOMBuilder;
27 import org.apache.cocoon.xml.dom.DOMUtil;
28 import org.apache.excalibur.source.SourceParameters;
29 import org.apache.excalibur.xml.xpath.XPathProcessor;
30 import org.xml.sax.ContentHandler JavaDoc;
31 import org.xml.sax.SAXException JavaDoc;
32 import org.xml.sax.ext.LexicalHandler JavaDoc;
33 import org.w3c.dom.Document JavaDoc;
34 import org.w3c.dom.Element JavaDoc;
35 import org.w3c.dom.Node JavaDoc;
36 import org.w3c.dom.NodeList JavaDoc;
37 import org.w3c.dom.DocumentFragment JavaDoc;
38 import org.w3c.dom.Attr JavaDoc;
39
40 import java.io.IOException JavaDoc;
41 import java.util.HashMap JavaDoc;
42 import java.util.Map JavaDoc;
43
44 /**
45  * The portal context
46  *
47  * This context allows access to various parts of a portal profile.
48  * The context provides reading of the following xml, if the current
49  * resource is running inside a portal module:
50  * <layout>
51  * <portal>
52  * ...
53  * </portal>
54  * <coplets>
55  * ...
56  * </coplets>
57  * </layout>
58  * <configuration>
59  * ...
60  * </configuration>
61  *
62  * @author <a HREF="mailto:cziegeler@s-und-n.de">Carsten Ziegeler</a>
63  * @version CVS $Id: SessionContextImpl.java 30932 2004-07-29 17:35:38Z vgritsenko $
64 */

65 public final class SessionContextImpl
66 implements SessionContext {
67
68     /* This contains all information about the currently processed coplet */
69     public static ThreadLocal JavaDoc copletInfo = new ThreadLocal JavaDoc();
70
71     /** The context name */
72     private String JavaDoc name;
73
74     /** The attributes */
75     private Map JavaDoc attributes = new HashMap JavaDoc();
76
77     /** The cached layoutDOM */
78     private Document JavaDoc layoutDOM;
79
80     /** The cached configurationDOM */
81     private Document JavaDoc configurationDOM;
82
83     /** The current profile */
84     private Map JavaDoc profile;
85
86     /** All coplet parameters */
87
88     private SourceParameters copletPars;
89
90     /** The status profile */
91     private Element JavaDoc statusProfile;
92
93     /** the coplet id */
94     private String JavaDoc copletID;
95
96     /** The number of the coplet */
97     private String JavaDoc copletNumber;
98
99     /** The profile ID */
100     private String JavaDoc profileID;
101
102     /** The portal URI */
103     private String JavaDoc portalURI;
104
105     /** The media type */
106     private String JavaDoc mediaType;
107
108     /** The current request */
109     private Request request;
110     
111     /** The XPath Processor */
112     private XPathProcessor xpathProcessor;
113     
114     public SessionContextImpl(String JavaDoc name,
115                               Map JavaDoc objectModel,
116                               PortalManager portal,
117                               XPathProcessor xpathProcessor)
118     throws IOException JavaDoc, SAXException JavaDoc, ProcessingException {
119         this.xpathProcessor = xpathProcessor;
120         this.setup(name, null, null);
121
122         // try to get the resource connector info
123
Map JavaDoc info = (Map JavaDoc)SessionContextImpl.copletInfo.get();
124         if (info != null) {
125             SessionContextImpl.copletInfo.set(null);
126             this.copletPars = (SourceParameters)info.get(PortalConstants.COPLETINFO_PARAMETERS);
127             this.portalURI = (String JavaDoc)info.get(PortalConstants.COPLETINFO_PORTALURI);
128             if (this.copletPars != null) {
129                 this.copletID = this.copletPars.getParameter(PortalConstants.PARAMETER_ID);
130                 this.copletNumber = this.copletPars.getParameter(PortalConstants.PARAMETER_NUMBER);
131                 if (this.copletID != null && this.copletNumber != null) {
132                     this.portalURI = this.portalURI + (this.portalURI.indexOf('?') == -1 ? '?' : '&')
133                           + "portalcmd=update_" + this.copletID + "_" + this.copletNumber;
134                 }
135             }
136             this.statusProfile = (Element JavaDoc)info.get(PortalConstants.COPLETINFO_STATUSPROFILE);
137         }
138         this.mediaType = (this.copletPars != null ? (String JavaDoc)copletPars.getParameter(PortalConstants.PARAMETER_MEDIA)
139                                                   : portal.getMediaType());
140         // get the profile
141

142         SessionContext context = portal.getContext(false);
143         if (context != null) {
144             if (context.getAttribute(PortalManager.ATTRIBUTE_PORTAL_ROLE) != null) {
145                 this.profileID = portal.getProfileID(PortalManager.BUILDTYPE_VALUE_ID,
146                   (String JavaDoc)context.getAttribute(PortalManager.ATTRIBUTE_PORTAL_ROLE),
147                   (String JavaDoc)context.getAttribute(PortalManager.ATTRIBUTE_PORTAL_ID), false);
148                 this.profile = portal.retrieveProfile(this.profileID);
149             }
150         }
151         this.getConfigurationDOM(portal);
152         this.request = ObjectModelHelper.getRequest( objectModel );
153     }
154
155     /**
156      * Get the name of the context
157      */

158     public String JavaDoc getName() {
159         return this.name;
160     }
161
162     public Request getRequest() {
163         return this.request;
164     }
165     
166     /**
167      * Get the layout DOM
168      */

169     private void getLayoutDOM()
170     throws ProcessingException {
171         if (this.layoutDOM == null && this.profile != null) {
172             try {
173                 Map JavaDoc portalLayouts = (Map JavaDoc)this.profile.get(PortalConstants.PROFILE_PORTAL_LAYOUTS);
174                 Map JavaDoc copletLayouts = (Map JavaDoc)this.profile.get(PortalConstants.PROFILE_COPLET_LAYOUTS);
175                 DOMBuilder builder = new DOMBuilder();
176                 builder.startDocument();
177                 PortalManagerImpl.streamLayoutProfile(builder, portalLayouts, copletLayouts, this.mediaType);
178                 builder.endDocument();
179                 this.layoutDOM = builder.getDocument();
180             } catch (SAXException JavaDoc local) {
181                 throw new ProcessingException("Unable to get portal." + local, local);
182             }
183         }
184     }
185
186     /**
187      * Get the configuration DOM
188      */

189     private void getConfigurationDOM(PortalManager portal)
190     throws ProcessingException, IOException JavaDoc {
191         if (this.configurationDOM == null && portal != null) {
192             try {
193                 String JavaDoc contextID = null;
194                 if (this.copletID != null && this.copletNumber != null) {
195                     contextID = "coplet_"+copletID+"_"+copletNumber;
196                 }
197                 DOMBuilder builder = new DOMBuilder();
198                 builder.startDocument();
199                 portal.streamConfiguration(builder,
200                                             this.portalURI,
201                                             this.profileID,
202                                             this.mediaType,
203                                             contextID);
204                 builder.endDocument();
205                 this.configurationDOM = builder.getDocument();
206             } catch (SAXException JavaDoc local) {
207                 throw new ProcessingException("Unable to get portal." + local, local);
208             }
209         }
210     }
211
212     /* Set the context name */
213     public void setup(String JavaDoc value, String JavaDoc load, String JavaDoc save) {
214         name = value;
215     }
216
217     /**
218      * Get the xml fragment
219      */

220     public synchronized DocumentFragment JavaDoc getXML(String JavaDoc path)
221     throws ProcessingException {
222         DocumentFragment JavaDoc result = null;
223
224         if (path.startsWith("/")) path = path.substring(1);
225         NodeList JavaDoc list = null;
226
227         if (path == null || path.equals("")) {
228             Document JavaDoc doc = DOMUtil.createDocument();
229             result = doc.createDocumentFragment();
230             this.getLayoutDOM();
231             if (this.layoutDOM != null) {
232                 result.appendChild(doc.importNode(this.layoutDOM.getDocumentElement(), true));
233             }
234             if (this.configurationDOM != null) {
235                 result.appendChild(doc.importNode(this.configurationDOM.getDocumentElement(), true));
236             }
237
238             if (this.statusProfile != null) {
239                 if (this.copletID != null && this.copletNumber != null) {
240                     String JavaDoc statusPath = "customization/coplet[@id='"+copletID+"' and @number='"+copletNumber+"']";
241                     try {
242                         Node JavaDoc node = DOMUtil.getSingleNode(this.statusProfile, statusPath, this.xpathProcessor);
243                         if (node != null) {
244                             Element JavaDoc copletData = doc.createElementNS(null, "coplet-data");
245                             NodeList JavaDoc childs = node.getChildNodes();
246                             if (childs != null) {
247                                 for(int l=0; l<childs.getLength(); l++) {
248                                     copletData.appendChild(doc.importNode(childs.item(l), true));
249                                 }
250                             }
251                             result.appendChild(copletData);
252                         }
253                     } catch (javax.xml.transform.TransformerException JavaDoc localException) {
254                         throw new ProcessingException("TransformerException: " + localException, localException);
255                     }
256                 }
257             }
258         }
259
260         if (path.equals("layout") || path.startsWith("layout/") ) {
261             try {
262                 this.getLayoutDOM();
263                 if (this.layoutDOM != null) list = DOMUtil.selectNodeList(this.layoutDOM, path, this.xpathProcessor);
264             } catch (javax.xml.transform.TransformerException JavaDoc localException) {
265                 throw new ProcessingException("TransformerException: " + localException, localException);
266             }
267         }
268
269         if (path.equals("configuration") || path.startsWith("configuration/") ) {
270             try {
271                 if (this.configurationDOM != null) list = DOMUtil.selectNodeList(this.configurationDOM, path, this.xpathProcessor);
272             } catch (javax.xml.transform.TransformerException JavaDoc localException) {
273                 throw new ProcessingException("TransformerException: " + localException, localException);
274             }
275         }
276
277         if (path.startsWith("coplet-data/") || path.equals("coplet-data") ) {
278
279             if (this.statusProfile != null) {
280                 if (this.copletID != null && this.copletNumber != null) {
281                     String JavaDoc statusPath = "customization/coplet[@id='"+copletID+"' and @number='"+copletNumber+"']";
282                     if (path.startsWith("coplet-data/")) {
283                         statusPath = statusPath + path.substring(11);
284                     }
285                     try {
286                         list = DOMUtil.selectNodeList(this.statusProfile, statusPath, this.xpathProcessor);
287                     } catch (javax.xml.transform.TransformerException JavaDoc localException) {
288                         throw new ProcessingException("TransformerException: " + localException, localException);
289                     }
290                 }
291             }
292         }
293
294         if (list != null && list.getLength() > 0) {
295             Document JavaDoc doc = DOMUtil.createDocument();
296             result = doc.createDocumentFragment();
297
298             for(int i = 0; i < list.getLength(); i++) {
299
300                 // the found node is either an attribute or an element
301
if (list.item(i).getNodeType() == Node.ATTRIBUTE_NODE) {
302                     // if it is an attribute simple create a new text node with the value of the attribute
303
result.appendChild(doc.createTextNode(list.item(i).getNodeValue()));
304                 } else {
305                     // now we have an element
306
// copy all children of this element in the resulting tree
307
NodeList JavaDoc childs = list.item(i).getChildNodes();
308                     if (childs != null) {
309                         for(int m = 0; m < childs.getLength(); m++) {
310                             result.appendChild(doc.importNode(childs.item(m), true));
311                         }
312                     }
313                 }
314             }
315         }
316
317         return result;
318     }
319
320
321     /**
322      * Set the xml
323      */

324     public synchronized void setXML(String JavaDoc path, DocumentFragment JavaDoc fragment)
325     throws ProcessingException {
326         if (path != null) {
327             if (path.startsWith("/") ) path = path.substring(1);
328             if (path.startsWith("coplet-data/") || path.equals("coplet-data") ) {
329
330                 if (this.statusProfile != null) {
331                     if (this.copletID != null && this.copletNumber != null) {
332                         String JavaDoc statusPath = "customization/coplet[@id='"+copletID+"' and @number='"+copletNumber+"']";
333                         if (path.startsWith("coplet-data/")) {
334                             statusPath = statusPath + path.substring(11);
335                         }
336
337                         Node JavaDoc node = DOMUtil.selectSingleNode(this.statusProfile, statusPath, this.xpathProcessor);
338                         if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
339                             // now we have to serialize the fragment to a string and insert this
340
Attr JavaDoc attr = (Attr JavaDoc)node;
341                             attr.setNodeValue(DOMUtil.getValueOfNode(fragment));
342                         } else {
343
344                             // remove old childs
345
while (node.hasChildNodes()) {
346                                 node.removeChild(node.getFirstChild());
347                             }
348
349                             // Insert new childs
350
NodeList JavaDoc childs = fragment.getChildNodes();
351                             if (childs != null && childs.getLength() > 0) {
352                                 for(int i = 0; i < childs.getLength(); i++) {
353                                     Node JavaDoc n = this.statusProfile.getOwnerDocument().importNode(childs.item(i), true);
354                                     node.appendChild(n);
355                                 }
356                             }
357                         }
358
359                         if (this.copletPars.getParameter(PortalConstants.PARAMETER_PERSISTENT, "false").equals("true") ) {
360                             this.profile.put(PortalConstants.PROFILE_SAVE_STATUS_FLAG, "true");
361                         }
362                     }
363                 }
364             }
365         }
366
367     }
368
369     /**
370      * Append a document fragment at the given path. The implementation of this
371      * method is context specific.
372      * Usually the children of the fragment are appended as new children of the
373      * node specified by the path.
374      * If the path is not existent it is created.
375      */

376     public synchronized void appendXML(String JavaDoc path, DocumentFragment JavaDoc fragment)
377     throws ProcessingException {
378         throw new ProcessingException("appendXML() not implemented.");
379     }
380
381     /**
382      * Remove nodes
383      */

384     public synchronized void removeXML(String JavaDoc path)
385     throws ProcessingException {
386         throw new ProcessingException("removeXML() not implemented.");
387     }
388
389     /**
390      * Get a copy the first node specified by the path.
391      */

392     public synchronized Node JavaDoc getSingleNode(String JavaDoc path)
393     throws ProcessingException {
394         // Node result = null;
395
throw new ProcessingException("getSingleNode() not implemented.");
396         // return result;
397
}
398
399     /**
400      * Get a copy all the nodes specified by the path.
401      */

402     public synchronized NodeList JavaDoc getNodeList(String JavaDoc path)
403     throws ProcessingException {
404         // NodeList result = null;
405
throw new ProcessingException("getNodeList() not implemented.");
406         // return result;
407
}
408
409     /**
410      * Set the value of a node. The node is copied before insertion.
411      */

412     public synchronized void setNode(String JavaDoc path, Node JavaDoc node)
413     throws ProcessingException {
414         throw new ProcessingException("setNode() not implemented.");
415     }
416
417
418     /**
419      * Set a context attribute. If value is null the attribute is removed.
420      */

421     public synchronized void setAttribute(String JavaDoc key, Object JavaDoc value) {
422         if (value == null) {
423             attributes.remove(key);
424         } else {
425             attributes.put(key, value);
426         }
427     }
428
429     /**
430      * Get a context attribute. If the attribute is not available return null
431      */

432     public synchronized Object JavaDoc getAttribute(String JavaDoc key) {
433         return attributes.get(key);
434     }
435
436     /**
437      * Get a context attribute. If the attribute is not available the defaultObject is returned
438      */

439     public synchronized Object JavaDoc getAttribute(String JavaDoc key, Object JavaDoc defaultObject) {
440         Object JavaDoc value = attributes.get(key);
441         if (value == null) value = defaultObject;
442         return value;
443     }
444
445     /**
446      * Get the value of this node. This is similiar to the xsl:value-of
447      * function. If the node does not exist, <code>null</code> is returned.
448      */

449     public synchronized String JavaDoc getValueOfNode(String JavaDoc path)
450     throws ProcessingException {
451         // String value = null;
452
throw new ProcessingException("getValueOfNode() not implemented.");
453         // return value;
454
}
455
456     /**
457      * Set the value of a node.
458      */

459     public synchronized void setValueOfNode(String JavaDoc path, String JavaDoc value)
460     throws ProcessingException {
461         throw new ProcessingException("setValueOfNode() not implemented.");
462     }
463
464     /**
465      * Stream the XML directly to the handler. This streams the contents of getXML()
466      * to the given handler without creating a DocumentFragment containing a copy
467      * of the data
468      */

469     public synchronized boolean streamXML(String JavaDoc path,
470                            ContentHandler JavaDoc contentHandler,
471                            LexicalHandler JavaDoc lexicalHandler)
472     throws SAXException JavaDoc, ProcessingException {
473         boolean streamed = false;
474         DocumentFragment JavaDoc fragment = this.getXML(path);
475         if (fragment != null) {
476             streamed = true;
477             IncludeXMLConsumer.includeNode(fragment, contentHandler, lexicalHandler);
478         }
479         return streamed;
480     }
481
482     /**
483      * Try to load XML into the context.
484      * If the context does not provide the ability of loading,
485      * an exception is thrown.
486      */

487     public void loadXML(String JavaDoc path,
488                         SourceParameters parameters)
489     throws SAXException JavaDoc, ProcessingException, IOException JavaDoc {
490         throw new ProcessingException("The context " + this.name + " does not support loading.");
491     }
492
493     /**
494      * Try to save XML from the context.
495      * If the context does not provide the ability of saving,
496      * an exception is thrown.
497      */

498     public void saveXML(String JavaDoc path,
499                         SourceParameters parameters)
500     throws SAXException JavaDoc, ProcessingException, IOException JavaDoc {
501         throw new ProcessingException("The context " + this.name + " does not support saving.");
502     }
503 }
504
505
Popular Tags