KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > jpivot > jboss > portlet > JPivotPortlet


1 /*
2  * ====================================================================
3  * This software is subject to the terms of the Common Public License
4  * Agreement, available at the following URL:
5  * http://www.opensource.org/licenses/cpl.html .
6  * Copyright (C) 2005 SHERMAN WOOD.
7  * All Rights Reserved.
8  * You must accept the terms of that agreement to use this software.
9  * ====================================================================
10  */

11 package com.tonbeller.jpivot.jboss.portlet;
12
13 import java.io.IOException JavaDoc;
14 import java.io.PrintWriter JavaDoc;
15
16 import javax.portlet.ActionRequest;
17 import javax.portlet.ActionResponse;
18 import javax.portlet.GenericPortlet;
19 import javax.portlet.PortletConfig;
20 import javax.portlet.PortletException;
21 import javax.portlet.PortletRequest;
22 import javax.portlet.PortletRequestDispatcher;
23 import javax.portlet.PortletResponse;
24 import javax.portlet.PortletSecurityException;
25 import javax.portlet.PortletSession;
26 import javax.portlet.RenderRequest;
27 import javax.portlet.RenderResponse;
28 import javax.servlet.ServletContext JavaDoc;
29 import javax.servlet.http.HttpServletRequest JavaDoc;
30 import javax.servlet.http.HttpServletResponse JavaDoc;
31 import javax.servlet.http.HttpSession JavaDoc;
32 import javax.servlet.jsp.jstl.core.Config;
33
34 import org.apache.log4j.Logger;
35 import org.apache.log4j.MDC;
36 import org.apache.portals.bridges.common.ServletContextProvider;
37 import org.jboss.portal.common.context.DelegateContext;
38 import org.jboss.portal.core.servlet.jsp.PortalJsp;
39 import org.jboss.portal.server.WindowContext;
40 import org.jboss.portal.server.invocation.AttachmentKey;
41 import org.jboss.portal.server.invocation.Invocation;
42 import org.jboss.portal.server.invocation.component.ContextDispatcherInterceptor;
43 import org.jboss.portal.server.servlet.ServletCommand;
44
45 import com.tonbeller.tbutils.testenv.Environment;
46 import com.tonbeller.wcf.controller.Controller;
47 import com.tonbeller.wcf.controller.RequestContext;
48 import com.tonbeller.wcf.controller.RequestContextFactory;
49 import com.tonbeller.wcf.controller.RequestContextFactoryFinder;
50 import com.tonbeller.wcf.controller.RequestFilter;
51 import com.tonbeller.wcf.controller.RequestSynchronizer;
52 import com.tonbeller.wcf.controller.WcfController;
53 import com.tonbeller.wcf.utils.DomUtils;
54 import com.tonbeller.wcf.utils.JDK13Utils;
55 import com.tonbeller.wcf.utils.UrlUtils;
56
57 public class JPivotPortlet extends GenericPortlet {
58
59     private static Logger logger = Logger.getLogger(JPivotPortlet.class);
60     
61     static final String JavaDoc NEXTVIEW = RequestFilter.class.getName() + ".nextview";
62     static final String JavaDoc ISNEW = RequestFilter.class.getName() + ".isnew";
63     
64     static final String JavaDoc OPERATION_PARM = "op";
65     
66     static final String JavaDoc SCREEN_PARM = "screen";
67     static final String JavaDoc QUERY_PARM = "query";
68
69     /** Name of the Request Attribute containing the Request.getRequestURI */
70     public static final String JavaDoc CONTEXT = "context";
71
72     /** if the session attribute FORCE_INDEX_JSP exists, then the client will be redirected to index.jsp */
73     public static final String JavaDoc FORCE_INDEX_JSP = "com.tonbeller.wcf.controller.FORCE_INDEX_JSP";
74     
75     /**
76      * If this request parameter is present, the DomUtils.randomId()
77      * will be reset once.
78      */

79     public static final String JavaDoc RESET_RANDOM_SEED = "resetRandomSeed";
80     
81     /**
82      * Name of class implementing {@link ServletContextProvider}
83      */

84     public static final String JavaDoc PARAM_SERVLET_CONTEXT_PROVIDER = "ServletContextProvider";
85     
86     private ServletContextProvider servletContextProvider;
87
88     private String JavaDoc errorJSP = null;
89     private String JavaDoc busyJSP = null;
90     private String JavaDoc indexJSP = "/index.jsp";
91     private String JavaDoc[] passThru = null;
92     private String JavaDoc mainJSP = "/testpage.jsp";
93     
94     private String JavaDoc forceExtension = null;
95
96
97     public JPivotPortlet() {
98         super();
99     }
100     
101     public void init(PortletConfig config) throws PortletException {
102         super.init(config);
103         String JavaDoc contextProviderClassName = getContextProviderClassNameParameter(config);
104         if (contextProviderClassName == null)
105             throw new PortletException("Portlet " + config.getPortletName()
106                 + " is incorrectly configured. Init parameter "
107                 + PARAM_SERVLET_CONTEXT_PROVIDER + " not specified");
108         
109         if (contextProviderClassName != null)
110         {
111             try
112             {
113                 Class JavaDoc clazz = Class.forName(contextProviderClassName);
114                 if (clazz != null) {
115                     Object JavaDoc obj = clazz.newInstance();
116                     if (ServletContextProvider.class.isInstance(obj)) {
117                         servletContextProvider = (ServletContextProvider) obj;
118                     }
119                     else
120                         throw new PortletException("class not found");
121                 }
122             } catch (Exception JavaDoc e)
123             {
124                 if (e instanceof PortletException)
125                     throw (PortletException) e;
126                 e.printStackTrace();
127                 throw new PortletException("Cannot load", e);
128             }
129         }
130         if (servletContextProvider == null)
131             throw new PortletException("Portlet " + config.getPortletName()
132                     + " is incorrectly configured. Invalid init parameter "
133                     + PARAM_SERVLET_CONTEXT_PROVIDER + " value "
134                     + contextProviderClassName);
135     }
136     
137     public void processAction(ActionRequest request, ActionResponse response) throws PortletException, PortletSecurityException, IOException JavaDoc {
138         HttpServletRequest JavaDoc httpRequest = getHttpServletRequest(this, request, response);
139         HttpServletResponse JavaDoc httpResponse = getHttpServletResponse(this, request, response);
140
141         ContextDispatcherInterceptor.InvokeNextCommand cmd =
142             (ContextDispatcherInterceptor.InvokeNextCommand)httpRequest.getAttribute(ServletCommand.REQ_ATT_KEY);
143         Invocation inv = cmd.getInvocation();
144         WindowContext windowCtx = (WindowContext)inv.getAttachment(AttachmentKey.WINDOW_CONTEXT);
145
146         String JavaDoc op = request.getParameter(OPERATION_PARM);
147         if (op != null) {
148             if (op.equalsIgnoreCase("print")) {
149                 PrintTable.processRequest(httpRequest, httpResponse, windowCtx, response);
150                 return;
151             } else if (op.equalsIgnoreCase("getChartImage")) {
152                 GetChartImage.processRequest(httpRequest, httpResponse, windowCtx, response);
153                 return;
154             }
155         }
156     }
157     
158     protected void doView(RenderRequest request, RenderResponse response) throws PortletException, PortletSecurityException, IOException JavaDoc {
159         //ResourceBundle bundle = getResourceBundle(request.getLocale());
160

161         // log if necessary
162
if (logger.isInfoEnabled())
163           logRequest(request);
164         
165         DelegateContext root = new DelegateContext();
166 /*
167         if (request.getUser() != null)
168         {
169            root.next("switch_user_logged_in");
170         }
171 */

172         request.setAttribute(PortalJsp.CTX_REQUEST, root);
173
174         PortletSession session = request.getPortletSession(true);
175         MDC.put("SessionID", session.getId());
176
177         String JavaDoc cpath = request.getContextPath();
178         request.setAttribute(CONTEXT, cpath);
179         HttpServletRequest JavaDoc httpRequest = getHttpServletRequest(this, request, response);
180         HttpServletResponse JavaDoc httpResponse = getHttpServletResponse(this, request, response);
181         
182         response.setContentType("text/html");
183
184         RequestContext context = createContext(request, response);
185         // set locale for JSTL tags
186
Config.set(httpRequest, Config.FMT_LOCALE, context.getLocale());
187 /*
188  * Don't do passThru right now
189         if (passThru(req)) {
190           chain.doFilter(req, res);
191           return;
192         }
193 */

194         MyHandler handler = new MyHandler(this, context, request, response);
195         try {
196           long t1 = System.currentTimeMillis();
197           RequestSynchronizer.instance(httpRequest).handleRequest(handler);
198           long t2 = System.currentTimeMillis();
199           if (logger.isInfoEnabled())
200             logger.info("Request Execution total time: " + (t2 - t1) + " ms");
201         } catch (Throwable JavaDoc e) {
202           PrintWriter JavaDoc out = null;
203           try {
204             out = response.getWriter();
205           } catch (Exception JavaDoc e2) {
206             out = new PrintWriter JavaDoc(System.out);
207             logger.error("No output writer could be retrieved, logging to stdout");
208           }
209           while (e != null) {
210             logger.error("Error handling request", e);
211             out.println();
212             out.println("<h2>" + e.toString() + "</h2><pre>");
213             e.printStackTrace(out);
214             out.println("</pre>");
215
216             Throwable JavaDoc prev = e;
217             e = JDK13Utils.getCause(e);
218             if (e == prev)
219               break;
220           }
221         } finally {
222           if (context != null)
223             context.invalidate();
224         }
225     }
226
227     /** TODO EBIF: das sollte wieder verschwinden, wenn HH die $VARIABLEN im Mondrian eingebaut hat */
228 /*
229     private boolean passThru(ServletRequest req) {
230       if (passThru == null)
231         return false;
232       HttpServletRequest hsr = (HttpServletRequest) req;
233       return UrlUtils.matchPattern(hsr, passThru);
234     }
235 */

236     public void destroy() {
237     }
238
239     /** for testing */
240     void setForceExtension(String JavaDoc forceExtension) {
241       this.forceExtension = forceExtension;
242     }
243
244     private void logRequest(PortletRequest request) {
245       logger.info(">>> Request " + request.getScheme() + "://" + request.getServerName() + ":"
246           + request.getServerPort() + request.getContextPath() );
247     }
248
249     public RequestContext createContext(RenderRequest request, RenderResponse response) {
250       
251       HttpServletRequest JavaDoc httpRequest = getHttpServletRequest(this, request, response);
252       HttpServletResponse JavaDoc httpResponse = getHttpServletResponse(this, request, response);
253       //HttpSession session = httpRequest.getSession(true);
254
//RequestContextFactory rcf = RequestContextFactoryFinder.findFactory(session);
255

256       //return rcf.createContext(httpRequest, httpResponse);
257
return RequestContextFactoryFinder.createContext(httpRequest, httpResponse, true);
258     }
259     
260     protected String JavaDoc getContextProviderClassNameParameter(PortletConfig config) {
261         return config.getInitParameter(PARAM_SERVLET_CONTEXT_PROVIDER);
262     }
263     
264     protected ServletContextProvider getServletContextProvider() {
265         return servletContextProvider;
266     }
267     
268     protected ServletContext JavaDoc getServletContext(GenericPortlet portlet, PortletRequest request, PortletResponse response) {
269         return getServletContextProvider().getServletContext(portlet);
270     }
271     
272     protected HttpServletRequest JavaDoc getHttpServletRequest(GenericPortlet portlet, PortletRequest request, PortletResponse response) {
273         return getServletContextProvider().getHttpServletRequest(portlet, request);
274     }
275     
276     protected HttpServletResponse JavaDoc getHttpServletResponse(GenericPortlet portlet, PortletRequest request, PortletResponse response) {
277         return getServletContextProvider().getHttpServletResponse(portlet, response);
278     }
279
280     class MyHandler implements RequestSynchronizer.Handler {
281         protected GenericPortlet portlet;
282         protected RequestContext context;
283         protected RenderRequest request;
284         protected RenderResponse response;
285         protected HttpServletRequest JavaDoc httpRequest;
286         protected HttpServletResponse JavaDoc httpResponse;
287
288         public MyHandler(GenericPortlet portlet, RequestContext context, RenderRequest request, RenderResponse response) {
289           this.portlet = portlet;
290           this.context = context;
291           this.request = request;
292           this.response = response;
293           this.httpRequest = getHttpServletRequest(portlet, request, response);
294           this.httpResponse = getHttpServletResponse(portlet, request, response);
295         }
296
297         public String JavaDoc getResultURI() {
298           // did the controller change the view?
299
String JavaDoc uri = (String JavaDoc) request.getAttribute(NEXTVIEW);
300           if (uri != null) {
301             uri = UrlUtils.forceExtension(uri, forceExtension);
302             //uri = redirectURI(uri);
303
return uri;
304           }
305
306           // no, redisplay the current request
307
//return request.getRequestURI();
308
return request.getContextPath();
309         }
310
311         public void normalRequest() throws Exception JavaDoc {
312           try {
313
314             if (request.getParameter(RESET_RANDOM_SEED) != null)
315               DomUtils.setRandomSeed(123);
316
317             if (redirectToIndex())
318               return;
319
320             HttpSession JavaDoc session = httpRequest.getSession(true);
321
322             // fire events
323
Controller controller = WcfController.instance(session);
324             controller.request(context);
325             
326             // someone has called sendError() or sendRedirect() on the response?
327
if (context.isResponseComplete())
328               return;
329
330             // if the controller redirects to another page, thats fine.
331
// if not, the current page is redisplayed UNLESS there was an error
332
// in which case we go to the start page.
333
String JavaDoc uri = (String JavaDoc) request.getAttribute(NEXTVIEW);
334             if (session.getAttribute(FORCE_INDEX_JSP) != null) {
335               session.removeAttribute(FORCE_INDEX_JSP);
336               if (uri == null)
337                 uri = indexJSP;
338             }
339             
340             String JavaDoc query = request.getParameter(QUERY_PARM);
341             if (query != null) {
342                 include(query, request, response);
343             }
344             
345             // Assume we are given a screen and a query
346
String JavaDoc screen = request.getParameter(SCREEN_PARM);
347             if (screen != null) {
348                 uri = screen;
349             }
350             
351             if (uri != null)
352                 include(uri, request, response);
353             else
354                 include(mainJSP, request, response);
355           } catch (Exception JavaDoc e) {
356             logger.error(null, e);
357             if (errorJSP != null) {
358               try {
359                 logger.error("redirecting to error page " + errorJSP, e);
360                 request.setAttribute("javax.servlet.jsp.jspException", e);
361                 include(errorJSP, request, response);
362               } catch (Exception JavaDoc e2) {
363                 // there was an error displaying the error page. We
364
// ignore the second error and display the original error
365
// instead
366
throw e;
367               }
368             } else
369               throw e;
370           }
371         }
372
373         public void recursiveRequest() throws Exception JavaDoc {
374             include(mainJSP, request, response);
375         }
376
377         public void showBusyPage(boolean redirect) throws Exception JavaDoc {
378           if (redirectToIndex())
379             return;
380           if (busyJSP != null) {
381             if (redirect) {
382               request.setAttribute("isBusyPage", "true");
383               include(busyJSP, request, response);
384             }
385           } else
386             throw new IllegalStateException JavaDoc("concurrent requests and no busy.jsp defined in web.xml");
387         }
388
389         public boolean isBusyPage() {
390           return "true".equals(request.getParameter("isBusyPage"));
391         }
392
393         /**
394          * @param uri
395          * @throws IOException
396          */

397         private void include(String JavaDoc uri, RenderRequest request, RenderResponse response) throws PortletException, IOException JavaDoc {
398           //uri = redirectURI(uri);
399
uri = UrlUtils.forceExtension(uri, forceExtension);
400           if (logger.isInfoEnabled())
401             logger.info("including " + uri);
402           PortletRequestDispatcher rdisp = getPortletContext()
403             .getRequestDispatcher(uri);
404           rdisp.include(request, response);
405         }
406
407         /*
408         private String redirectURI(String uri) {
409
410             if (uri.startsWith("/")) {
411               StringBuffer sb = new StringBuffer();
412               sb.append(request.getContextPath());
413               sb.append(uri);
414               uri = sb.toString();
415             }
416             return uri;
417
418         }
419 */

420         /**
421          * true, if the current request was redirected to the index page
422          * because there is no valid session.
423          */

424         protected boolean redirectToIndex() throws Exception JavaDoc {
425           if (indexJSP != null) {
426             // do not redirect to index.jsp while testing
427
if (Environment.isTest())
428               return false;
429             
430             PortletSession session = request.getPortletSession();
431             boolean isNew = session.isNew();
432             if (!isNew && request.getParameter(OPERATION_PARM) != null)
433               isNew = request.getParameter(OPERATION_PARM).equalsIgnoreCase("index");
434             if (!isNew)
435               isNew = !"false".equals(session.getAttribute(ISNEW));
436             if (isNew) {
437               session.setAttribute(ISNEW, "false");
438               include(indexJSP, request, response);
439               return true;
440             }
441           }
442           return false;
443         }
444
445       }
446
447 }
448
Popular Tags