KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > portal > wsrp > adapter > WSRPAdapter


1 /*
2  * Copyright 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.portal.wsrp.adapter;
17
18 import java.io.IOException JavaDoc;
19 import java.util.Enumeration JavaDoc;
20 import java.util.HashMap JavaDoc;
21 import java.util.Iterator JavaDoc;
22 import java.util.Map JavaDoc;
23
24 import javax.servlet.ServletConfig JavaDoc;
25
26 import oasis.names.tc.wsrp.v1.types.BlockingInteractionResponse;
27 import oasis.names.tc.wsrp.v1.types.MarkupContext;
28 import oasis.names.tc.wsrp.v1.types.MarkupResponse;
29 import oasis.names.tc.wsrp.v1.types.MarkupType;
30 import oasis.names.tc.wsrp.v1.types.PortletContext;
31 import oasis.names.tc.wsrp.v1.types.PortletDescription;
32 import oasis.names.tc.wsrp.v1.types.SessionContext;
33 import oasis.names.tc.wsrp.v1.types.UpdateResponse;
34
35 import org.apache.avalon.framework.activity.Disposable;
36 import org.apache.avalon.framework.activity.Initializable;
37 import org.apache.avalon.framework.configuration.Configuration;
38 import org.apache.avalon.framework.configuration.ConfigurationException;
39 import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
40 import org.apache.avalon.framework.container.ContainerUtil;
41 import org.apache.avalon.framework.context.Context;
42 import org.apache.avalon.framework.context.ContextException;
43 import org.apache.avalon.framework.context.Contextualizable;
44 import org.apache.avalon.framework.parameters.ParameterException;
45 import org.apache.avalon.framework.parameters.Parameterizable;
46 import org.apache.avalon.framework.parameters.Parameters;
47 import org.apache.avalon.framework.service.ServiceException;
48 import org.apache.avalon.framework.service.ServiceManager;
49 import org.apache.avalon.framework.service.Serviceable;
50 import org.apache.cocoon.ProcessingException;
51 import org.apache.cocoon.environment.ObjectModelHelper;
52 import org.apache.cocoon.environment.Session;
53 import org.apache.cocoon.environment.wrapper.RequestParameters;
54 import org.apache.cocoon.portal.PortalManagerAspect;
55 import org.apache.cocoon.portal.PortalManagerAspectPrepareContext;
56 import org.apache.cocoon.portal.PortalManagerAspectRenderContext;
57 import org.apache.cocoon.portal.PortalService;
58 import org.apache.cocoon.portal.coplet.CopletData;
59 import org.apache.cocoon.portal.coplet.CopletInstanceData;
60 import org.apache.cocoon.portal.coplet.adapter.impl.AbstractCopletAdapter;
61 import org.apache.cocoon.portal.coplet.status.SizingStatus;
62 import org.apache.cocoon.portal.event.EventManager;
63 import org.apache.cocoon.portal.event.Receiver;
64 import org.apache.cocoon.portal.event.impl.ChangeCopletInstanceAspectDataEvent;
65 import org.apache.cocoon.portal.event.impl.FullScreenCopletEvent;
66 import org.apache.cocoon.portal.layout.Layout;
67 import org.apache.cocoon.portal.serialization.IncludingHTMLSerializer;
68 import org.apache.cocoon.portal.util.HtmlSaxParser;
69 import org.apache.cocoon.portal.wsrp.consumer.ConsumerEnvironmentImpl;
70 import org.apache.cocoon.portal.wsrp.consumer.ProducerDescription;
71 import org.apache.cocoon.portal.wsrp.consumer.ProducerRegistryImpl;
72 import org.apache.cocoon.portal.wsrp.consumer.Request;
73 import org.apache.cocoon.portal.wsrp.consumer.RequestImpl;
74 import org.apache.cocoon.portal.wsrp.consumer.RequiresConsumerEnvironment;
75 import org.apache.cocoon.portal.wsrp.consumer.RequiresPortalService;
76 import org.apache.cocoon.portal.wsrp.consumer.RequiresWSRPAdapter;
77 import org.apache.cocoon.portal.wsrp.consumer.SimplePortletWindowSession;
78 import org.apache.cocoon.portal.wsrp.consumer.UserContextProvider;
79 import org.apache.cocoon.portal.wsrp.consumer.WSRPRequestImpl;
80 import org.apache.cocoon.portal.wsrp.logging.WSRPLogManager;
81 import org.apache.cocoon.portal.wsrp.logging.WSRPLogger;
82 import org.apache.cocoon.servlet.CocoonServlet;
83 import org.apache.cocoon.util.ClassUtils;
84 import org.apache.cocoon.xml.AbstractXMLPipe;
85 import org.apache.cocoon.xml.AttributesImpl;
86 import org.apache.cocoon.xml.XMLUtils;
87 import org.apache.commons.lang.exception.NestableRuntimeException;
88 import org.apache.excalibur.source.Source;
89 import org.apache.excalibur.source.SourceResolver;
90 import org.apache.wsrp4j.consumer.GroupSession;
91 import org.apache.wsrp4j.consumer.PortletDriver;
92 import org.apache.wsrp4j.consumer.PortletKey;
93 import org.apache.wsrp4j.consumer.PortletSession;
94 import org.apache.wsrp4j.consumer.Producer;
95 import org.apache.wsrp4j.consumer.SessionHandler;
96 import org.apache.wsrp4j.consumer.User;
97 import org.apache.wsrp4j.consumer.UserSession;
98 import org.apache.wsrp4j.consumer.WSRPPortlet;
99 import org.apache.wsrp4j.consumer.driver.PortletKeyImpl;
100 import org.apache.wsrp4j.consumer.driver.UserImpl;
101 import org.apache.wsrp4j.consumer.driver.WSRPPortletImpl;
102 import org.apache.wsrp4j.exception.ErrorCodes;
103 import org.apache.wsrp4j.exception.WSRPException;
104 import org.apache.wsrp4j.log.LogManager;
105 import org.apache.wsrp4j.util.Constants;
106 import org.apache.wsrp4j.util.WindowStates;
107 import org.xml.sax.Attributes JavaDoc;
108 import org.xml.sax.ContentHandler JavaDoc;
109 import org.xml.sax.SAXException JavaDoc;
110 import org.xml.sax.ext.LexicalHandler JavaDoc;
111
112 /**
113  * Adapter to use wsrp-portlets as coplets <br/>
114  * It provides the wsrp support by initializing wsrp4j <br/>
115  * The aspect/adapter can be configured at the portal manager.<br/>
116  *
117  * @author <a HREF="mailto:cziegeler@s-und-n.de">Carsten Ziegeler</a>
118  * @author <a HREF="mailto:malessandrini@s-und-n.de">Michel Alessandrini</a>
119  *
120  * @version $Id: WSRPAdapter.java 329454 2005-10-29 17:44:45Z cziegeler $
121  */

122 public class WSRPAdapter
123     extends AbstractCopletAdapter
124     implements Contextualizable,
125                PortalManagerAspect,
126                Serviceable,
127                Initializable,
128                Disposable,
129                Parameterizable,
130                Receiver {
131
132     /** Key to store the consumer map into the coplet instance data object as a temporary attribute. */
133     public static final String JavaDoc ATTRIBUTE_NAME_CONSUMER_MAP = "wsrp-consumer-map";
134
135     /** Key to store the portlet instance key into the coplet instance data object as a temporary attribute. */
136     public static final String JavaDoc ATTRIBUTE_NAME_PORTLET_INSTANCE_KEY = "wsrp-portlet-instance-key";
137
138     /** Key to store the portlet key into the coplet instance data objectt as a temporary attribute. */
139     public static final String JavaDoc ATTRIBUTE_NAME_PORTLET_KEY = "wsrp-portletkey";
140
141     /** Key to store the wsrp user into the coplet instance data object as a temporary attribute. */
142     public static final String JavaDoc ATTRIBUTE_NAME_USER = "wsrp-user";
143
144     /** Key to store the layout for the wsrp portlet into the coplet instance data object as a temporary attribute. */
145     public static final String JavaDoc ATTRIBUTE_NAME_LAYOUT = "wsrp-layout";
146
147     /** Key to store the wsrp title into the coplet instance data object as a temporary attribute. */
148     public static final String JavaDoc ATTRIBUTE_NAME_PORTLET_TITLE = "wsrp-title";
149
150     /** Key to store the wsrp modes into the coplet instance data object as a temporary attribute. */
151     public static final String JavaDoc ATTRIBUTE_NAME_PORTLET_MODES = "wsrp-modes";
152
153     /** Key to store the window states into the coplet instance data object as a temporary attribute. */
154     public static final String JavaDoc ATTRIBUTE_NAME_PORTLET_WINDOWSTATES = "wsrp-window-states";
155
156     /** Unique name of the consumer. */
157     public static final String JavaDoc CONSUMER_URL = "http://cocoon.apache.org/portal/wsrp-consumer";
158     
159     /** Name of the service. */
160     public static final String JavaDoc consumerAgent = "Apache Cocoon Portal." + org.apache.cocoon.Constants.VERSION;
161     
162     /** The avalon context. */
163     protected Context context;
164     
165     /** The consumer environment implementation. */
166     protected ConsumerEnvironmentImpl consumerEnvironment;
167     
168     /** Stores the current coplet instance data per thread. */
169     protected final ThreadLocal JavaDoc copletInstanceData = new ThreadLocal JavaDoc();
170
171     /** The servlet configuration. */
172     protected ServletConfig JavaDoc servletConfig;
173
174     /** The service locator. */
175     protected ServiceManager manager;
176
177     /** The portal service. */
178     protected PortalService service;
179
180     /** The user context provider. */
181     protected UserContextProvider userContextProvider;
182
183     /** Location of the wsrp configuration. */
184     protected String JavaDoc wsrpConfigLocation;
185
186     /** Initialized? */
187     protected boolean initialized = false;
188
189     /** The wsrp configuration. */
190     protected Configuration wsrpConfiguration;
191
192     /** The configuration for this adapter. */
193     protected Parameters parameters;
194
195     /**
196      * @see org.apache.avalon.framework.context.Contextualizable#contextualize(org.apache.avalon.framework.context.Context)
197      */

198     public void contextualize(Context context) throws ContextException {
199         this.context = context;
200         try {
201             this.servletConfig = (ServletConfig JavaDoc) context.get(CocoonServlet.CONTEXT_SERVLET_CONFIG);
202             // we have to somehow pass this component down to other components!
203
// This is ugly, but it's the only chance for sofisticated component containers
204
// that wrap component implementations!
205
this.servletConfig.getServletContext().setAttribute(WSRPAdapter.class.getName(), this);
206         } catch (ContextException ignore) {
207             // we ignore the context exception
208
// this avoids startup errors if the portal is configured for the CLI
209
// environment
210
this.getLogger().warn("The wsrp support is disabled as the servlet context is not available.", ignore);
211         }
212     }
213
214     /**
215      * @see org.apache.avalon.framework.service.Serviceable#service(org.apache.avalon.framework.service.ServiceManager)
216      */

217     public void service(ServiceManager manager) throws ServiceException {
218         this.manager = manager;
219         EventManager eventManager = null;
220         try {
221             eventManager = (EventManager)this.manager.lookup(EventManager.ROLE);
222             eventManager.subscribe(this);
223         } finally {
224             this.manager.release(eventManager);
225         }
226         this.service = (PortalService)this.manager.lookup(PortalService.ROLE);
227         this.userContextProvider = (UserContextProvider)this.manager.lookup(UserContextProvider.ROLE);
228     }
229
230     /**
231      * @see org.apache.avalon.framework.parameters.Parameterizable#parameterize(org.apache.avalon.framework.parameters.Parameters)
232      */

233     public void parameterize(Parameters params) throws ParameterException {
234         this.wsrpConfigLocation = params.getParameter("wsrp-config");
235         this.parameters = params;
236     }
237
238     /**
239      * Sets the <tt>WSRPLogger</tt>, the <tt>producerConfig</tt> and the <tt>consumerEnvironment</tt><br/>
240      *
241      * @see org.apache.avalon.framework.activity.Initializable#initialize()
242      */

243     public void initialize() throws Exception JavaDoc {
244         LogManager.setLogManager(new WSRPLogManager(new WSRPLogger(this.getLogger())));
245         this.consumerEnvironment = new ConsumerEnvironmentImpl();
246         this.consumerEnvironment.init(this.service,
247                                       this);
248         consumerEnvironment.setConsumerAgent(consumerAgent);
249     }
250
251     /**
252      * Removes all portlets, producers and users out of the <tt>consumerEnvironment</tt>-registries<br/>
253      *
254      * @see org.apache.avalon.framework.activity.Disposable#dispose()
255      */

256     public void dispose() {
257         
258         consumerEnvironment.getPortletRegistry().removeAllPortlets();
259         
260         Iterator JavaDoc producers = consumerEnvironment.getProducerRegistry().getAllProducers();
261         Producer producer;
262         while (producers.hasNext()) {
263             producer = (Producer) producers.next();
264             try {
265                 producer.deregister();
266             } catch (WSRPException e) {
267                 this.getLogger().error("deregister() producer: " + producer.getName());
268             }
269         }
270         consumerEnvironment.getProducerRegistry().removeAllProducers();
271         
272         consumerEnvironment.getUserRegistry().removeAllUsers();
273         
274         if ( this.manager != null ) {
275             EventManager eventManager = null;
276             try {
277                 eventManager = (EventManager)this.manager.lookup(EventManager.ROLE);
278                 eventManager.unsubscribe(this);
279             } catch (Exception JavaDoc ignore) {
280                 // let's ignore it
281
} finally {
282                 this.manager.release(eventManager);
283             }
284             this.manager.release(this.service);
285             this.manager.release(this.userContextProvider);
286             this.service = null;
287             this.userContextProvider = null;
288             this.manager = null;
289         }
290         try {
291             ContainerUtil.dispose(this.consumerEnvironment);
292             this.consumerEnvironment = null;
293         } catch (Throwable JavaDoc t) {
294             this.getLogger().error("Destruction failed!", t);
295         }
296         
297         if ( this.servletConfig != null ) {
298             this.servletConfig.getServletContext().removeAttribute(WSRPAdapter.class.getName());
299             this.servletConfig = null;
300         }
301     }
302
303     /**
304      * Gets the required information of the producer, user, wsrp-portlet, window-states, window-modes<br/>
305      * and stores its into the copletInstanceData<br/>
306      * After that it initiates the <tt>getServiceDescription()</tt>-call<br/>
307      *
308      * @see org.apache.cocoon.portal.coplet.adapter.impl.AbstractCopletAdapter#login(org.apache.cocoon.portal.coplet.CopletInstanceData)
309      */

310     public void login(CopletInstanceData coplet) {
311         super.login(coplet);
312
313         final CopletData copletData = coplet.getCopletData();
314
315         // get the producer
316
final String JavaDoc producerId = (String JavaDoc) copletData.getAttribute("producer-id");
317         if ( producerId == null ) {
318             // if the producer can't be found, we simply return
319
this.getLogger().error("Producer not configured in wsrp coplet " + copletData.getId());
320             return;
321         }
322         final Producer producer = consumerEnvironment.getProducerRegistry().getProducer(producerId);
323         if ( producer == null ) {
324             // if the producer can't be found, we simply return
325
this.getLogger().error("Producer with id " + producerId + " not found.");
326             return;
327         }
328
329         // get the wsrp user and store it as an attribute on the instance
330
final String JavaDoc currentUserID = this.service.getComponentManager().getProfileManager().getUser().getUserName();
331         User user = this.consumerEnvironment.getUserRegistry().getUser(currentUserID);
332         if ( user == null ) {
333             // create a new user
334
user = new UserImpl(currentUserID);
335             user.setUserContext(this.userContextProvider.createUserContext(currentUserID));
336             this.consumerEnvironment.getUserRegistry().addUser(user);
337         }
338         coplet.setTemporaryAttribute(ATTRIBUTE_NAME_USER, user);
339
340         // get the portlet handle
341
final String JavaDoc portletHandle = (String JavaDoc) copletData.getAttribute("portlet-handle");
342         if ( portletHandle == null ) {
343             // if the portlet handle can't be found, we simply return
344
this.getLogger().error("Portlet handle not configured in wsrp coplet " + copletData.getId());
345             return;
346         }
347
348         // get the wsrp portlet
349
final PortletKey portletKey = new PortletKeyImpl(portletHandle, producerId);
350         WSRPPortlet wsrpportlet = this.consumerEnvironment.getPortletRegistry().getPortlet(portletKey);
351         if ( wsrpportlet == null ) {
352             wsrpportlet = new WSRPPortletImpl(portletKey);
353             final PortletContext portletContext = new PortletContext(null, portletKey.getPortletHandle(), null);
354             wsrpportlet.setPortletContext(portletContext);
355             try {
356                 consumerEnvironment.getPortletRegistry().addPortlet(wsrpportlet);
357             } catch (WSRPException we) {
358                 this.getLogger().error("Exception adding wsrp portlet.", we);
359                 return;
360             }
361         }
362         coplet.setTemporaryAttribute(ATTRIBUTE_NAME_PORTLET_KEY, portletKey);
363         final Session session = ObjectModelHelper.getRequest(this.service.getObjectModel()).getSession();
364         final String JavaDoc portletInstanceKey = this.getPortletInstanceKey(portletKey, coplet, session.getId());
365         coplet.setTemporaryAttribute(ATTRIBUTE_NAME_PORTLET_INSTANCE_KEY, portletInstanceKey);
366
367         // create consumer parameters
368
final Map JavaDoc addParams = new HashMap JavaDoc();
369         addParams.put(Constants.PORTLET_INSTANCE_KEY, portletInstanceKey);
370         coplet.setTemporaryAttribute(ATTRIBUTE_NAME_CONSUMER_MAP, addParams);
371
372         // get the window-state and -mode
373
SimplePortletWindowSession windowSession;
374         wsrpportlet = consumerEnvironment.getPortletRegistry().getPortlet(portletKey);
375
376         try {
377             // this call includes the getServiceDescription()-Invocation
378
// additionally register() initCookie() and so on will be handled
379
// (within ProducerImpl and PortletDriverImpl)
380
windowSession = getSimplePortletWindowSession(wsrpportlet,
381                                                           portletInstanceKey,
382                                                           user);
383             final PortletDescription desc = producer.getPortletDescription(portletHandle);
384             coplet.setTemporaryAttribute(ATTRIBUTE_NAME_PORTLET_TITLE,
385                                          desc.getTitle());
386             final MarkupType markupType = desc.getMarkupTypes(0);
387             coplet.setTemporaryAttribute(ATTRIBUTE_NAME_PORTLET_MODES, markupType.getModes());
388             coplet.setTemporaryAttribute(ATTRIBUTE_NAME_PORTLET_WINDOWSTATES, markupType.getWindowStates());
389
390         } catch (WSRPException e) {
391             this.getLogger().error("Invoking getServiceDescription()", e);
392         }
393     }
394
395     /**
396      * Checks the values of the <tt>portlet-key</tt> and the <tt>user</tt> for current portlet-instance<br/>
397      * After that all passed the <tt>getMarkup()</tt>-call will be initiated<br />
398      *
399      * @see org.apache.cocoon.portal.coplet.adapter.impl.AbstractCopletAdapter#streamContent(org.apache.cocoon.portal.coplet.CopletInstanceData, org.xml.sax.ContentHandler)
400      */

401     public void streamContent(CopletInstanceData coplet, ContentHandler JavaDoc contentHandler)
402     throws SAXException JavaDoc {
403         try {
404             // set the coplet in the thread local variable to give other components access to
405
// the instance
406
this.setCurrentCopletInstanceData(coplet);
407
408             // get the portlet key and the user
409
final PortletKey portletKey = (PortletKey)coplet.getTemporaryAttribute(ATTRIBUTE_NAME_PORTLET_KEY);
410             if ( portletKey == null ) {
411                 throw new SAXException JavaDoc("WSRP configuration is missing: portlet key.");
412             }
413             final User user = (User)coplet.getTemporaryAttribute(ATTRIBUTE_NAME_USER);
414             if ( user == null ) {
415                 throw new SAXException JavaDoc("WSRP configuration is missing: user.");
416             }
417             
418             final String JavaDoc portletInstanceKey = (String JavaDoc)coplet.getTemporaryAttribute(ATTRIBUTE_NAME_PORTLET_INSTANCE_KEY);
419
420             // getMarkup()
421
final WSRPPortlet wsrpportlet = consumerEnvironment.getPortletRegistry().getPortlet(portletKey);
422
423             SimplePortletWindowSession windowSession = getSimplePortletWindowSession(wsrpportlet, portletInstanceKey, user);
424             final MarkupContext markupContext = this.getMarkupContext(wsrpportlet, windowSession, user);
425             if ( markupContext == null || markupContext.getMarkupString() == null ) {
426                 throw new SAXException JavaDoc("No markup received from wsrp coplet " + coplet.getId());
427             }
428             final String JavaDoc content = markupContext.getMarkupString();
429
430             final Boolean JavaDoc usePipeline;
431             final boolean usesGet;
432             // If the portlet uses the method get we always have to rewrite form elements
433
final Producer producer = this.consumerEnvironment.getProducerRegistry().getProducer(portletKey.getProducerId());
434             final PortletDescription desc = producer.getPortletDescription(portletKey.getPortletHandle());
435             if ( desc.getUsesMethodGet() != null && desc.getUsesMethodGet().booleanValue() ) {
436                 usePipeline = Boolean.TRUE;
437                 usesGet = true;
438             } else {
439                 usePipeline = (Boolean JavaDoc)this.getConfiguration(coplet, "use-pipeline", Boolean.FALSE);
440                 usesGet = false;
441             }
442             if ( usePipeline.booleanValue() ) {
443                 if ( usesGet ) {
444                     contentHandler = new FormRewritingHandler(contentHandler);
445                 }
446                 HtmlSaxParser.parseString(content, HtmlSaxParser.getContentFilter(contentHandler));
447             } else {
448                 // stream out the include for the serializer
449
IncludingHTMLSerializer.addPortlet(portletInstanceKey, content);
450                 contentHandler.startPrefixMapping("portal", IncludingHTMLSerializer.NAMESPACE);
451                 final AttributesImpl attr = new AttributesImpl();
452                 attr.addCDATAAttribute("portlet", portletInstanceKey);
453                 contentHandler.startElement(IncludingHTMLSerializer.NAMESPACE,
454                                             "include",
455                                             "portal:include",
456                                             attr);
457                 contentHandler.endElement(IncludingHTMLSerializer.NAMESPACE,
458                                           "include",
459                                           "portal:include");
460                 contentHandler.endPrefixMapping("portal");
461             }
462         } catch (WSRPException e) {
463             throw new SAXException JavaDoc("Exception during getMarkup of wsrp coplet: " + coplet.getId(), e);
464         } catch (SAXException JavaDoc se) {
465             throw se;
466         } finally {
467             this.setCurrentCopletInstanceData(null);
468         }
469     }
470     
471     /**
472      * Releases all sessions (<tt>userSession, groupSession, portletSession</tt>)<br/>
473      *
474      * @see org.apache.cocoon.portal.coplet.adapter.impl.AbstractCopletAdapter#logout(org.apache.cocoon.portal.coplet.CopletInstanceData)
475      */

476     public void logout(CopletInstanceData coplet) {
477         super.logout(coplet);
478
479         PortletKey portletKey = (PortletKey)coplet.getTemporaryAttribute(ATTRIBUTE_NAME_PORTLET_KEY);
480         User user = (User)coplet.getTemporaryAttribute(ATTRIBUTE_NAME_USER);
481         final String JavaDoc portletInstanceKey = (String JavaDoc)coplet.getTemporaryAttribute(ATTRIBUTE_NAME_PORTLET_INSTANCE_KEY);
482         Producer producer = consumerEnvironment.getProducerRegistry().getProducer(portletKey.getProducerId());
483         
484         // releaseSession()
485
try {
486             UserSession userSession = consumerEnvironment.getSessionHandler().getUserSession(portletKey.getProducerId(), user.getUserID());
487             PortletDescription portletDescription = producer.getPortletDescription(portletKey.getPortletHandle());
488             GroupSession groupSession = userSession.getGroupSession(portletDescription.getGroupID());
489             PortletSession portletSession = groupSession.getPortletSession(portletInstanceKey);
490             SessionContext sessionContext = portletSession.getSessionContext();
491             WSRPPortlet wsrpportlet = consumerEnvironment.getPortletRegistry().getPortlet(portletKey);
492             PortletDriver portletDriver = consumerEnvironment.getPortletDriverRegistry().getPortletDriver(wsrpportlet);
493     
494             if (sessionContext != null) {
495                 String JavaDoc[] sessions = new String JavaDoc[1];
496                 sessions[0] = new String JavaDoc (sessionContext.getSessionID());
497                 portletDriver.releaseSessions(sessions, user.getUserID());
498             }
499             
500             userSession.removeGroupSession(portletDescription.getGroupID());
501         } catch (WSRPException e) {
502             this.getLogger().error("session deregister()", e);
503         }
504     }
505     
506     /**
507      * After getting the <tt>userSession</tt> and <tt>groupSession</tt> it performs the <tt>getServiceDescription()</tt>-call<br/>
508      *
509      * @param portlet
510      * @param portletInstanceKey
511      * @param user
512      * @return SimplePortletWindowSession
513      * @throws WSRPException
514      */

515     public SimplePortletWindowSession getSimplePortletWindowSession(WSRPPortlet portlet,
516                                                                     String JavaDoc portletInstanceKey,
517                                                                     User user)
518     throws WSRPException {
519         SimplePortletWindowSession windowSession = null;
520
521         // get the user session
522
SessionHandler sessionHandler = consumerEnvironment.getSessionHandler();
523         UserSession userSession = sessionHandler.getUserSession(portlet.getPortletKey().getProducerId(), user.getUserID());
524
525         if (userSession != null) {
526             // get the group session
527
String JavaDoc groupID = null;
528             try {
529                 Producer producer = consumerEnvironment.getProducerRegistry().getProducer(portlet.getPortletKey().getProducerId());
530                 // *********************************
531
// getServiceDescription()
532
// *********************************
533
PortletDescription portletDescription = producer.getPortletDescription(portlet.getPortletKey().getPortletHandle());
534
535                 if (portletDescription != null) {
536                     groupID = portletDescription.getGroupID();
537                 }
538             } catch (WSRPException e) {
539                 groupID = "default_group_id";
540                 this.getLogger().info("using default-group");
541             }
542
543             GroupSession groupSession = userSession.getGroupSession(groupID);
544
545             if (groupSession != null) {
546                 PortletSession portletSession = groupSession.getPortletSession(portlet.getPortletKey().getPortletHandle());
547
548                 if (portletSession != null) {
549                     windowSession = (SimplePortletWindowSession) portletSession.getPortletWindowSession(portletInstanceKey);
550                 } else {
551                     this.getLogger().error("WSRP-Errorcode: " + Integer.toString(ErrorCodes.PORTLET_SESSION_NOT_FOUND));
552                 }
553             } else {
554                 this.getLogger().error("WSRP-Errorcode: " + Integer.toString(ErrorCodes.GROUP_SESSION_NOT_FOUND));
555             }
556         } else {
557             this.getLogger().error("WSRP-Errorcode: " + Integer.toString(ErrorCodes.USER_SESSION_NOT_FOUND));
558         }
559         return windowSession;
560     }
561
562     /**
563      * Performs an blocking interaction with the given portlet and session.<br/>
564      * If the response to this call is a redirect URL's it won't be followed.<br/>
565      *
566      * An optionally returned markup context is store in the window session<br/>
567      * and should be processed by the portlet driver instead of making a new<br/>
568      * getMarkup() call.<br/>
569      *
570      * @param portlet The portlet on which this action should be performed
571      * @param windowSession The window session of the portlet on which the action should
572      * be performed
573      * @param user The user on which this action should be performed
574      * @param request The request with all required information for the call
575      **/

576     protected void performBlockingInteraction(WSRPPortlet portlet,
577                                               SimplePortletWindowSession windowSession,
578                                               User user,
579                                               Request request) {
580         try {
581             PortletDriver portletDriver = consumerEnvironment.getPortletDriverRegistry().getPortletDriver(portlet);
582             BlockingInteractionResponse response = portletDriver.performBlockingInteraction(
583                     new WSRPRequestImpl(windowSession, request, consumerEnvironment), user.getUserID());
584
585             if (response != null) {
586                 UpdateResponse update = response.getUpdateResponse();
587                 if (update != null) {
588                     //update the WSRP portlet sessionContext
589
windowSession.getPortletSession().setSessionContext(update.getSessionContext());
590
591                     MarkupContext markupContext = update.getMarkupContext();
592                     if (markupContext != null) {
593                         windowSession.updateMarkupCache(markupContext);
594                     }
595
596                     windowSession.setNavigationalState(update.getNavigationalState());
597
598                     String JavaDoc windowState = null;
599                     if ((windowState = update.getNewWindowState()) != null) {
600                         windowSession.setWindowState(windowState);
601                     }
602
603                     String JavaDoc windowMode = null;
604                     if ((windowMode = update.getNewMode()) != null) {
605                         windowSession.setMode(windowMode);
606                     }
607                 } else if (response.getRedirectURL() != null) {
608                     this.getLogger().debug("response.getRedirectURL() != null");
609                 }
610             }
611         } catch (WSRPException e) {
612             this.getLogger().error("Error occured during performInteraction!", e);
613         }
614     }
615
616     /**
617      * Retrieves the markup generated by the portlet.
618      *
619      * @param portlet
620      * @param windowSession
621      * @param user
622      * @return The markup context.
623      **/

624     protected MarkupContext getMarkupContext(WSRPPortlet portlet,
625                                              SimplePortletWindowSession windowSession,
626                                              User user)
627     throws WSRPException {
628         WSRPRequestImpl wsrpRequest = new WSRPRequestImpl(windowSession, null, this.consumerEnvironment);
629
630         PortletDriver portletDriver = consumerEnvironment.getPortletDriverRegistry().getPortletDriver(portlet);
631         MarkupResponse response = portletDriver.getMarkup(wsrpRequest, user.getUserID());
632
633         if (response != null) {
634             SessionContext sessionContext = response.getSessionContext();
635             if (sessionContext != null && windowSession != null) {
636                 windowSession.getPortletSession().setSessionContext(sessionContext);
637             }
638
639             return response.getMarkupContext();
640         }
641         return null;
642     }
643
644     /**
645      * Creates a <tt>String</tt> consists of the producer-id_portlet-handle_coplet-id_user-name <br/>
646      *
647      * @param key includes the essential values
648      * @param coplet current <tt>CopletInstanceData</tt>-object
649      * @param userName
650      * @return the unique string which represents the portlet-instance
651      * */

652     protected String JavaDoc getPortletInstanceKey(PortletKey key,
653                                            CopletInstanceData coplet,
654                                            String JavaDoc userName) {
655         final StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(key.getProducerId());
656         buffer.append('_').append(key.getPortletHandle()).append('_');
657         buffer.append(coplet.getId()).append('_').append(userName);
658         return buffer.toString();
659     }
660     
661     /**
662      * Gets all required information like <tt>portletKey, portletInstanceKey, userName, portletModes, windowStates,
663      * interactionState</tt> and the <tt>navigationalStat</tt><br/>
664      *
665      * After that it decides with the <tt>URL_TYPE</tt> to perform the <tt>performBlockingInteraction()</tt>-call or
666      * do some render- alternatively some resource-specific things<br/>
667      *
668      * @see Receiver
669      */

670     public void inform(WSRPEvent event, PortalService service) {
671         final CopletInstanceData coplet = (CopletInstanceData)event.getTarget();
672         this.setCurrentCopletInstanceData(coplet);
673         
674         try {
675             PortletKey portletKey = (PortletKey)coplet.getTemporaryAttribute(ATTRIBUTE_NAME_PORTLET_KEY);
676             final String JavaDoc portletInstanceKey = (String JavaDoc)coplet.getTemporaryAttribute(ATTRIBUTE_NAME_PORTLET_INSTANCE_KEY);
677             WSRPPortlet wsrpPortlet = consumerEnvironment.getPortletRegistry().getPortlet(portletKey);
678             User user = (User) coplet.getTemporaryAttribute(ATTRIBUTE_NAME_USER);
679             
680             org.apache.cocoon.environment.Request requestObject = ObjectModelHelper.getRequest(service.getObjectModel());
681             java.util.Enumeration JavaDoc formParameter = requestObject.getParameterNames();
682
683             Request request = new RequestImpl();
684             String JavaDoc portletMode = requestObject.getParameter(Constants.PORTLET_MODE);
685             String JavaDoc windowState = requestObject.getParameter(Constants.WINDOW_STATE);
686             
687             request.setInteractionState(requestObject.getParameter(Constants.INTERACTION_STATE));
688             SimplePortletWindowSession windowSession = getSimplePortletWindowSession(wsrpPortlet, portletInstanceKey, user);
689             windowSession.setNavigationalState(requestObject.getParameter(Constants.NAVIGATIONAL_STATE));
690
691             if (portletMode != null) {
692                 windowSession.setMode(portletMode);
693             }
694             if (windowState != null) {
695                 if ( !windowState.equals(windowSession.getWindowState()) ) {
696                     final Layout layout = (Layout)coplet.getTemporaryAttribute(ATTRIBUTE_NAME_LAYOUT);
697                     final Layout fullScreenLayout = service.getEntryLayout(null);
698                     if ( fullScreenLayout != null
699                          && fullScreenLayout.equals( layout )
700                          && !windowState.equals(WindowStates._maximized) ) {
701                         FullScreenCopletEvent e = new FullScreenCopletEvent( coplet, null );
702                         service.getComponentManager().getEventManager().send(e);
703                     }
704                     if ( windowState.equals(WindowStates._minimized) ) {
705                         ChangeCopletInstanceAspectDataEvent e = new ChangeCopletInstanceAspectDataEvent(coplet, "size", SizingStatus.STATUS_MINIMIZED);
706                         service.getComponentManager().getEventManager().send(e);
707                     }
708                     if ( windowState.equals(WindowStates._normal) ) {
709                         ChangeCopletInstanceAspectDataEvent e = new ChangeCopletInstanceAspectDataEvent(coplet, "size", SizingStatus.STATUS_MAXIMIZED);
710                         service.getComponentManager().getEventManager().send(e);
711                     }
712                     if ( windowState.equals(WindowStates._maximized) ) {
713                         FullScreenCopletEvent e = new FullScreenCopletEvent( coplet, layout );
714                         service.getComponentManager().getEventManager().send(e);
715                     }
716                     windowSession.setWindowState(windowState);
717                 }
718             }
719             if (requestObject.getParameter(Constants.URL_TYPE).equals(Constants.URL_TYPE_BLOCKINGACTION)) {
720             // performBlockingInteraction()
721
String JavaDoc parameter;
722                 while (formParameter.hasMoreElements()) {
723                     parameter = (String JavaDoc) formParameter.nextElement();
724                     request.addFormParameter(parameter, requestObject.getParameter(parameter));
725                 }
726                 performBlockingInteraction(wsrpPortlet, windowSession, user, request);
727             
728             }
729                 
730         } catch (WSRPException e) {
731             this.getLogger().error("Error during processing wsrp event.", e);
732         } finally {
733             this.setCurrentCopletInstanceData(null);
734         }
735     }
736
737     /**
738      * @see org.apache.cocoon.portal.PortalManagerAspect#prepare(org.apache.cocoon.portal.PortalManagerAspectPrepareContext, org.apache.cocoon.portal.PortalService)
739      */

740     public void prepare(PortalManagerAspectPrepareContext aspectContext,
741                         PortalService service)
742     throws ProcessingException {
743         // process the events
744
aspectContext.invokeNext();
745     }
746
747     /**
748      * @see org.apache.cocoon.portal.PortalManagerAspect#render(org.apache.cocoon.portal.PortalManagerAspectRenderContext, org.apache.cocoon.portal.PortalService, org.xml.sax.ContentHandler, org.apache.avalon.framework.parameters.Parameters)
749      */

750     public void render(PortalManagerAspectRenderContext aspectContext,
751                        PortalService service,
752                        ContentHandler JavaDoc ch,
753                        Parameters parameters)
754     throws SAXException JavaDoc {
755         aspectContext.invokeNext(ch, parameters);
756     }
757
758     /**
759      * @return Returns the <tt>consumerEnvironmentImpl</tt>
760      */

761     public ConsumerEnvironmentImpl getConsumerEnvironment() {
762         return consumerEnvironment;
763     }
764
765     /**
766      * Add a new producer<br/>
767      *
768      * @param desc The producer description.
769      * @return Returns true if the producer could be added.
770      */

771     public boolean addProducer(ProducerDescription desc) {
772         return ((ProducerRegistryImpl)this.consumerEnvironment.getProducerRegistry()).addProducer(desc);
773     }
774
775     /**
776      * This sets the current coplet instance data for the thread <br/>
777      *
778      * @param coplet The coplet instance data or null to clear the information.
779      */

780     public void setCurrentCopletInstanceData(CopletInstanceData coplet) {
781         this.copletInstanceData.set(coplet);
782     }
783
784     /**
785      * Return the current coplet instance data<br/>
786      *
787      * @return Returns the instance or null.
788      */

789     public CopletInstanceData getCurrentCopletInstanceData() {
790         return (CopletInstanceData)this.copletInstanceData.get();
791     }
792
793     /**
794      * This handler is triggered by a form element. It rewrites the
795      * action if the method get is used. In this case all request parameters
796      * of the action are added as hidden fields.
797      */

798     public static final class FormRewritingHandler extends AbstractXMLPipe {
799
800         public FormRewritingHandler(ContentHandler JavaDoc ch) {
801             this.setContentHandler(ch);
802             if ( ch instanceof LexicalHandler JavaDoc ) {
803                 this.setLexicalHandler((LexicalHandler JavaDoc)ch);
804             }
805         }
806
807         /**
808          * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
809          */

810         public void startElement(String JavaDoc uri, String JavaDoc loc, String JavaDoc raw, Attributes JavaDoc a) throws SAXException JavaDoc {
811             if ( loc.equalsIgnoreCase("form") && a.getValue("method").equalsIgnoreCase("get") ) {
812                 final String JavaDoc action = a.getValue("action");
813                 int pos = action.indexOf('?');
814                 if ( pos != -1 ) {
815                     AttributesImpl ai = new AttributesImpl(a);
816                     a = ai;
817                     final String JavaDoc queryString = action.substring(pos+1);
818                     ai.removeAttribute("action");
819                     ai.addCDATAAttribute("action", action.substring(0, pos));
820                     super.startElement(uri, loc, raw, a);
821                     RequestParameters rp = new RequestParameters(queryString);
822
823                     final Enumeration JavaDoc e = rp.getParameterNames();
824                     while ( e.hasMoreElements() ) {
825                         final String JavaDoc key = (String JavaDoc)e.nextElement();
826                         final String JavaDoc value = rp.getParameter(key);
827                         AttributesImpl attributes = new AttributesImpl();
828                         attributes.addCDATAAttribute("type", "hidden");
829                         attributes.addCDATAAttribute("name", key);
830                         attributes.addCDATAAttribute("value", value);
831                         XMLUtils.createElement(this.contentHandler, "input", attributes);
832                     }
833                     return;
834                 }
835             }
836             super.startElement(uri, loc, raw, a);
837         }
838
839     }
840
841     /**
842      * Check if we have read our configuration already.
843      * If not, read the config and invoke the configure method.
844      */

845     protected void checkInitialized() {
846         if ( !this.initialized ) {
847             synchronized (this) {
848                 if (! this.initialized ) {
849                     this.initialized = true;
850                     SourceResolver resolver = null;
851                     Source source = null;
852                     try {
853                         resolver = (SourceResolver)this.manager.lookup(SourceResolver.ROLE);
854                         source = resolver.resolveURI(this.wsrpConfigLocation);
855                         DefaultConfigurationBuilder dcb = new DefaultConfigurationBuilder();
856                         this.wsrpConfiguration = dcb.build(source.getInputStream());
857                     } catch (ConfigurationException ce) {
858                         this.getLogger().error("Unable to read wsrp configuration: " + this.wsrpConfigLocation, ce);
859                     } catch (IOException JavaDoc ioe) {
860                         this.getLogger().error("Unable to read wsrp configuration: " + this.wsrpConfigLocation, ioe);
861                     } catch (SAXException JavaDoc sae) {
862                         this.getLogger().error("Unable to read wsrp configuration: " + this.wsrpConfigLocation, sae);
863                     } catch (ServiceException se) {
864                         throw new NestableRuntimeException("Unable to get source resolver.", se);
865                     } finally {
866                         if ( resolver != null ) {
867                             resolver.release(source);
868                         }
869                         this.manager.release(resolver);
870                     }
871                 }
872             }
873         }
874     }
875
876     /**
877      * Get the wsrp configuration.
878      */

879     public Configuration getWsrpConfiguration() {
880         this.checkInitialized();
881         return this.wsrpConfiguration;
882     }
883
884     /**
885      * Get the adapter configuration.
886      */

887     public Parameters getAdapterConfiguration() {
888         return this.parameters;
889     }
890
891     /**
892      * Create a component.
893      */

894     public Object JavaDoc createObject(String JavaDoc className)
895     throws Exception JavaDoc {
896         final Object JavaDoc component = ClassUtils.newInstance(className);
897         ContainerUtil.enableLogging(component, this.getLogger());
898         if (component instanceof RequiresConsumerEnvironment) {
899             ((RequiresConsumerEnvironment)component).setConsumerEnvironment(this.consumerEnvironment);
900         }
901         if (component instanceof RequiresWSRPAdapter) {
902             ((RequiresWSRPAdapter)component).setWSRPAdapter(this);
903         }
904         if (component instanceof RequiresPortalService) {
905             ((RequiresPortalService)component).setPortalService(this.service);
906         }
907         ContainerUtil.contextualize(component, context);
908         ContainerUtil.service(component, manager);
909         ContainerUtil.initialize(component);
910
911         return component;
912     }
913
914 }
915
Popular Tags