KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > portal > coplet > adapter > impl > PortletAdapter


1 /*
2  * Copyright 2004,2004-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.coplet.adapter.impl;
17
18 import java.util.Map JavaDoc;
19 import java.util.Properties JavaDoc;
20
21 import javax.portlet.PortletMode;
22 import javax.portlet.WindowState;
23 import javax.servlet.ServletConfig JavaDoc;
24 import javax.servlet.http.HttpServletRequest JavaDoc;
25 import javax.servlet.http.HttpServletResponse JavaDoc;
26
27 import org.apache.avalon.framework.activity.Disposable;
28 import org.apache.avalon.framework.activity.Initializable;
29 import org.apache.avalon.framework.container.ContainerUtil;
30 import org.apache.avalon.framework.context.Context;
31 import org.apache.avalon.framework.context.ContextException;
32 import org.apache.avalon.framework.context.Contextualizable;
33 import org.apache.avalon.framework.parameters.Parameters;
34 import org.apache.avalon.framework.service.ServiceException;
35 import org.apache.avalon.framework.service.ServiceManager;
36 import org.apache.cocoon.ProcessingException;
37 import org.apache.cocoon.components.ContextHelper;
38 import org.apache.cocoon.environment.http.HttpEnvironment;
39 import org.apache.cocoon.portal.PortalManagerAspect;
40 import org.apache.cocoon.portal.PortalManagerAspectPrepareContext;
41 import org.apache.cocoon.portal.PortalManagerAspectRenderContext;
42 import org.apache.cocoon.portal.PortalService;
43 import org.apache.cocoon.portal.coplet.CopletInstanceData;
44 import org.apache.cocoon.portal.event.EventManager;
45 import org.apache.cocoon.portal.event.Receiver;
46 import org.apache.cocoon.portal.pluto.PortletContainerEnvironmentImpl;
47 import org.apache.cocoon.portal.pluto.PortletURLProviderImpl;
48 import org.apache.cocoon.portal.pluto.om.PortletDefinitionRegistry;
49 import org.apache.cocoon.portal.pluto.om.PortletEntityListImpl;
50 import org.apache.cocoon.portal.pluto.om.PortletWindowImpl;
51 import org.apache.cocoon.portal.pluto.om.common.ObjectIDImpl;
52 import org.apache.cocoon.portal.pluto.servlet.ServletRequestImpl;
53 import org.apache.cocoon.portal.pluto.servlet.ServletResponseImpl;
54 import org.apache.cocoon.portal.serialization.IncludingHTMLSerializer;
55 import org.apache.cocoon.portal.util.HtmlSaxParser;
56 import org.apache.cocoon.servlet.CocoonServlet;
57 import org.apache.cocoon.xml.AttributesImpl;
58 import org.apache.pluto.PortletContainer;
59 import org.apache.pluto.PortletContainerException;
60 import org.apache.pluto.PortletContainerImpl;
61 import org.apache.pluto.om.entity.PortletApplicationEntity;
62 import org.apache.pluto.om.entity.PortletEntity;
63 import org.apache.pluto.om.window.PortletWindow;
64 import org.apache.pluto.om.window.PortletWindowCtrl;
65 import org.apache.pluto.om.window.PortletWindowList;
66 import org.apache.pluto.om.window.PortletWindowListCtrl;
67 import org.apache.pluto.services.PortletContainerEnvironment;
68 import org.apache.pluto.services.information.DynamicInformationProvider;
69 import org.apache.pluto.services.information.InformationProviderService;
70 import org.apache.pluto.services.information.PortletActionProvider;
71 import org.xml.sax.ContentHandler JavaDoc;
72 import org.xml.sax.SAXException JavaDoc;
73
74
75 /**
76  * This is the adapter to use JSR-168 portlets as coplets
77  *
78  * @author <a HREF="mailto:cziegeler@apache.org">Carsten Ziegeler</a>
79  *
80  * @version CVS $Id: PortletAdapter.java 329454 2005-10-29 17:44:45Z cziegeler $
81  */

82 public class PortletAdapter
83     extends AbstractCopletAdapter
84     implements Contextualizable, Initializable, PortalManagerAspect, Receiver, Disposable {
85     
86     /** The avalon context */
87     protected Context context;
88     
89     /** The servlet configuration for pluto */
90     protected ServletConfig JavaDoc servletConfig;
91
92     /** The Portlet Container */
93     protected PortletContainer portletContainer;
94
95     /** The Portlet Container environment */
96     protected PortletContainerEnvironmentImpl portletContainerEnvironment;
97
98     /**
99      * @see org.apache.avalon.framework.context.Contextualizable#contextualize(org.apache.avalon.framework.context.Context)
100      */

101     public void contextualize(Context context) throws ContextException {
102         this.context = context;
103         try {
104             // TODO - we could lookup the component from the adapter selector
105
this.servletConfig = (ServletConfig JavaDoc) context.get(CocoonServlet.CONTEXT_SERVLET_CONFIG);
106             // we have to somehow pass this component down to other components!
107
// This is ugly, but it's the only chance for sofisticated component containers
108
// that wrap component implementations!
109
this.servletConfig.getServletContext().setAttribute(PortletAdapter.class.getName(), this);
110         } catch (ContextException ignore) {
111             // we ignore the context exception
112
// this avoids startup errors if the portal is configured for the CLI
113
// environment
114
this.getLogger().warn("The JSR-168 support is disabled as the servlet context is not available.", ignore);
115         }
116     }
117     
118     /* (non-Javadoc)
119      * @see org.apache.cocoon.portal.coplet.adapter.CopletAdapter#login(org.apache.cocoon.portal.coplet.CopletInstanceData)
120      */

121     public void login(CopletInstanceData coplet) {
122         super.login(coplet);
123
124         if ( this.portletContainer == null ) {
125             return;
126         }
127         PortletDefinitionRegistry registry = (PortletDefinitionRegistry) portletContainerEnvironment.getContainerService(PortletDefinitionRegistry.class);
128         
129         final String JavaDoc portletEntityId = (String JavaDoc) getConfiguration(coplet, "portlet");
130         
131         PortletApplicationEntity pae = registry.getPortletApplicationEntityList().get(ObjectIDImpl.createFromString("cocoon"));
132         PortletEntity portletEntity = ((PortletEntityListImpl)pae.getPortletEntityList()).add(pae, portletEntityId, coplet, registry);
133         
134         if ( portletEntity.getPortletDefinition() != null ) {
135             // create the window
136
PortletWindow portletWindow = new PortletWindowImpl(portletEntityId);
137             ((PortletWindowCtrl)portletWindow).setId(coplet.getId());
138             ((PortletWindowCtrl)portletWindow).setPortletEntity(portletEntity);
139             PortletWindowList windowList = portletEntity.getPortletWindowList();
140             ((PortletWindowListCtrl)windowList).add(portletWindow);
141             coplet.setTemporaryAttribute("window", portletWindow);
142             
143             // load the portlet
144
final Map JavaDoc objectModel = ContextHelper.getObjectModel(this.context);
145             ServletRequestImpl req = (ServletRequestImpl) objectModel.get("portlet-request");
146             if ( req == null ) {
147                 final HttpServletResponse JavaDoc res = (HttpServletResponse JavaDoc) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
148                 objectModel.put("portlet-response", new ServletResponseImpl(res));
149                 req = new ServletRequestImpl((HttpServletRequest JavaDoc) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT), null);
150                 objectModel.put("portlet-request", req);
151             }
152             final HttpServletResponse JavaDoc res = (HttpServletResponse JavaDoc) objectModel.get("portlet-response");
153             try {
154                 this.portletContainer.portletLoad(portletWindow, req.getRequest(portletWindow),
155                                                   res);
156             } catch (Exception JavaDoc e) {
157                 this.getLogger().error("Error loading portlet " + portletEntityId, e);
158                 // remove portlet entity
159
coplet.removeTemporaryAttribute("window");
160                 ((PortletEntityListImpl)pae.getPortletEntityList()).remove(portletEntity);
161             }
162         }
163     }
164
165     /**
166      * @see org.apache.cocoon.portal.coplet.adapter.impl.AbstractCopletAdapter#streamContent(org.apache.cocoon.portal.coplet.CopletInstanceData, org.xml.sax.ContentHandler)
167      */

168     public void streamContent(CopletInstanceData coplet,
169                               ContentHandler JavaDoc contentHandler)
170     throws SAXException JavaDoc {
171         if ( this.portletContainer == null ) {
172             throw new SAXException JavaDoc("Unable to execute JSR-168 portlets because of missing servlet context.");
173         }
174         try {
175             final String JavaDoc portlet = (String JavaDoc)super.getConfiguration(coplet, "portlet");
176             if ( portlet == null ) {
177                 throw new SAXException JavaDoc("Portlet configuration is missing.");
178             }
179             // get the window
180
final PortletWindow window = (PortletWindow)coplet.getTemporaryAttribute("window");
181             if ( window == null ) {
182                 throw new SAXException JavaDoc("Portlet couldn't be loaded: " + portlet);
183             }
184             final Map JavaDoc objectModel = ContextHelper.getObjectModel(this.context);
185             final ServletRequestImpl req = (ServletRequestImpl) objectModel.get("portlet-request");
186             final HttpServletResponse JavaDoc res = (HttpServletResponse JavaDoc) objectModel.get("portlet-response");
187             
188             // TODO - for parallel processing we have to clone the response!
189
this.portletContainer.renderPortlet(window, req.getRequest(window), res);
190             final String JavaDoc value = res.toString();
191
192             final Boolean JavaDoc usePipeline = (Boolean JavaDoc)this.getConfiguration(coplet, "use-pipeline", Boolean.FALSE);
193             if ( usePipeline.booleanValue() ) {
194                 HtmlSaxParser.parseString(value, HtmlSaxParser.getContentFilter(contentHandler));
195             } else {
196                 // stream out the include for the serializer
197
IncludingHTMLSerializer.addPortlet(portlet, value);
198                 contentHandler.startPrefixMapping("portal", IncludingHTMLSerializer.NAMESPACE);
199                 AttributesImpl attr = new AttributesImpl();
200                 attr.addCDATAAttribute("portlet", portlet);
201                 contentHandler.startElement(IncludingHTMLSerializer.NAMESPACE,
202                                             "include", "portal:include", attr);
203                 contentHandler.endElement(IncludingHTMLSerializer.NAMESPACE,
204                                           "include", "portal:include");
205                 contentHandler.endPrefixMapping("portal");
206             }
207         } catch (SAXException JavaDoc se) {
208             throw se;
209         } catch (Exception JavaDoc e) {
210             throw new SAXException JavaDoc(e);
211         }
212     }
213
214     /**
215      * @see org.apache.cocoon.portal.coplet.adapter.CopletAdapter#logout(org.apache.cocoon.portal.coplet.CopletInstanceData)
216      */

217     public void logout(CopletInstanceData coplet) {
218         super.logout(coplet);
219         if ( this.portletContainer == null ) {
220             return;
221         }
222         PortletWindow window = (PortletWindow)coplet.getTemporaryAttribute("window");
223         if ( window != null ) {
224             coplet.removeTemporaryAttribute("window");
225             PortletDefinitionRegistry registry = (PortletDefinitionRegistry) portletContainerEnvironment.getContainerService(PortletDefinitionRegistry.class);
226         
227             PortletApplicationEntity pae = registry.getPortletApplicationEntityList().get(ObjectIDImpl.createFromString("cocoon"));
228             ((PortletEntityListImpl)pae.getPortletEntityList()).remove(window.getPortletEntity());
229         }
230     }
231
232     /**
233      * @see org.apache.avalon.framework.service.Serviceable#service(org.apache.avalon.framework.service.ServiceManager)
234      */

235     public void service(ServiceManager manager) throws ServiceException {
236         super.service(manager);
237         EventManager eventManager = null;
238         try {
239             eventManager = (EventManager)this.manager.lookup(EventManager.ROLE);
240             eventManager.subscribe(this);
241         } finally {
242             this.manager.release(eventManager);
243         }
244     }
245
246     /**
247      * @see org.apache.avalon.framework.activity.Disposable#dispose()
248      */

249     public void dispose() {
250         if ( this.manager != null ) {
251             EventManager eventManager = null;
252             try {
253                 eventManager = (EventManager)this.manager.lookup(EventManager.ROLE);
254                 eventManager.unsubscribe(this);
255             } catch (Exception JavaDoc ignore) {
256                 // let's ignore it
257
} finally {
258                 this.manager.release(eventManager);
259             }
260             this.manager = null;
261         }
262         try {
263             if (this.portletContainer != null ) {
264                 this.portletContainer.shutdown();
265                 this.portletContainer = null;
266             }
267             ContainerUtil.dispose(this.portletContainerEnvironment);
268             this.portletContainerEnvironment = null;
269         } catch (Throwable JavaDoc t) {
270             this.getLogger().error("Destruction failed!", t);
271         }
272         if ( this.servletConfig != null ) {
273             this.servletConfig.getServletContext().removeAttribute(PortletAdapter.class.getName());
274             this.servletConfig = null;
275         }
276     }
277
278     /**
279      * @see org.apache.avalon.framework.activity.Initializable#initialize()
280      */

281     public void initialize() throws Exception JavaDoc {
282         if ( this.servletConfig != null ) {
283             this.initContainer();
284         }
285     }
286
287     /**
288      * Return the portlet container
289      */

290     public PortletContainer getPortletContainer() {
291         return this.portletContainer;
292     }
293
294     /**
295      * Return the portlet container environment
296      */

297     public PortletContainerEnvironment getPortletContainerEnvironment() {
298         return this.portletContainerEnvironment;
299     }
300
301     /**
302      * Initialize the container
303      */

304     public void initContainer() throws Exception JavaDoc {
305         this.portletContainer = new PortletContainerImpl();
306
307         if (!portletContainer.isInitialized()) {
308             this.getLogger().debug ("Initializing PortletContainer...");
309
310             final String JavaDoc uniqueContainerName = "cocoon-portal";
311
312             this.portletContainerEnvironment = new PortletContainerEnvironmentImpl();
313             ContainerUtil.enableLogging(this.portletContainerEnvironment, this.getLogger());
314             ContainerUtil.contextualize(this.portletContainerEnvironment, this.context);
315             ContainerUtil.service(this.portletContainerEnvironment, this.manager);
316             ContainerUtil.initialize(this.portletContainerEnvironment);
317
318             Properties JavaDoc properties = new Properties JavaDoc();
319
320             try {
321                 portletContainer.init(uniqueContainerName, servletConfig, this.portletContainerEnvironment, properties);
322             } catch (PortletContainerException exc) {
323                 throw new ProcessingException("Initialization of the portlet container failed.", exc);
324             }
325         } else {
326             this.getLogger().debug("PortletContainer already initialized.");
327         }
328
329         this.getLogger().debug("PortletContainer initialized.");
330         
331     }
332
333     /**
334      * @see Receiver
335      */

336     public void inform(PortletURLProviderImpl event, PortalService service) {
337         final Map JavaDoc objectModel = ContextHelper.getObjectModel(this.context);
338         final ServletRequestImpl req = new ServletRequestImpl((HttpServletRequest JavaDoc) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT), event);
339         final HttpServletResponse JavaDoc res = new ServletResponseImpl((HttpServletResponse JavaDoc) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT));
340         objectModel.put("portlet-response", res);
341         objectModel.put("portlet-request", req);
342
343         if ( event.isAction() ) {
344             // This means we can only have ONE portlet event per request!
345
objectModel.put("portlet-event", event);
346         } else {
347             DynamicInformationProvider dynProv;
348             InformationProviderService ips;
349             PortletActionProvider pap;
350
351             ips = (InformationProviderService)this.portletContainerEnvironment.getContainerService(InformationProviderService.class);
352             dynProv = ips.getDynamicProvider(req);
353             pap = dynProv.getPortletActionProvider(event.getPortletWindow());
354             final PortletMode mode = event.getPortletMode();
355             if ( mode != null ) {
356                 pap.changePortletMode(mode);
357             }
358             final WindowState state = event.getWindowState();
359             if ( state != null ) {
360                 pap.changePortletWindowState(state);
361             }
362         }
363     }
364
365     /**
366      * @see org.apache.cocoon.portal.PortalManagerAspect#prepare(org.apache.cocoon.portal.PortalManagerAspectPrepareContext, org.apache.cocoon.portal.PortalService)
367      */

368     public void prepare(PortalManagerAspectPrepareContext aspectContext,
369                         PortalService service)
370     throws ProcessingException {
371         // process the events
372
aspectContext.invokeNext();
373         
374         // if we aren't running in a servlet environment, just skip the JSR-168 part
375
if ( this.servletConfig == null ) {
376             return;
377         }
378         
379         // do we already have an environment?
380
// if not, create one
381
final Map JavaDoc objectModel = aspectContext.getObjectModel();
382
383         PortletURLProviderImpl event = (PortletURLProviderImpl) objectModel.get("portlet-event");
384         if ( event != null ) {
385             PortletWindow actionWindow = event.getPortletWindow();
386             try {
387                 final ServletRequestImpl req = (ServletRequestImpl) objectModel.get("portlet-request");
388                 final ServletResponseImpl res= (ServletResponseImpl)objectModel.get("portlet-response");
389                 this.portletContainer.processPortletAction(actionWindow, req.getRequest(actionWindow), res);
390             } catch (Exception JavaDoc ignore) {
391                 this.getLogger().error("Error during processing of portlet action.", ignore);
392             }
393         } else if ( objectModel.get("portlet-response") == null ) {
394             final HttpServletResponse JavaDoc res = (HttpServletResponse JavaDoc) objectModel.get(HttpEnvironment.HTTP_RESPONSE_OBJECT);
395             objectModel.put("portlet-response", new ServletResponseImpl(res));
396             final ServletRequestImpl req = new ServletRequestImpl((HttpServletRequest JavaDoc) objectModel.get(HttpEnvironment.HTTP_REQUEST_OBJECT), null);
397             objectModel.put("portlet-request", req);
398         }
399     }
400
401     /**
402      * @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)
403      */

404     public void render(PortalManagerAspectRenderContext aspectContext,
405                        PortalService service,
406                        ContentHandler JavaDoc ch,
407                        Parameters parameters)
408     throws SAXException JavaDoc {
409         final Map JavaDoc objectModel = aspectContext.getObjectModel();
410
411         // don't generate a response, if we issued a redirect
412
if (objectModel.remove("portlet-event") == null) {
413             aspectContext.invokeNext(ch, parameters);
414         }
415     }
416
417 }
418
Popular Tags