KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > infoglue > deliver > applications > filters > ViewPageFilter


1 /* ===============================================================================
2 *
3 * Part of the InfoGlue Content Management Platform (www.infoglue.org)
4 *
5 * ===============================================================================
6 *
7 * Copyright (C)
8 *
9 * This program is free software; you can redistribute it and/or modify it under
10 * the terms of the GNU General Public License version 2, as published by the
11 * Free Software Foundation. See the file LICENSE.html for more information.
12 *
13 * This program is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along with
18 * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
19 * Place, Suite 330 / Boston, MA 02111-1307 / USA.
20 *
21 * ===============================================================================
22 */

23
24 package org.infoglue.deliver.applications.filters;
25
26 import java.io.IOException JavaDoc;
27 import java.net.URLDecoder JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.Collections JavaDoc;
30 import java.util.Enumeration JavaDoc;
31 import java.util.HashMap JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.List JavaDoc;
34 import java.util.Locale JavaDoc;
35 import java.util.Map JavaDoc;
36 import java.util.StringTokenizer JavaDoc;
37
38 import javax.servlet.Filter JavaDoc;
39 import javax.servlet.FilterChain JavaDoc;
40 import javax.servlet.FilterConfig JavaDoc;
41 import javax.servlet.ServletException JavaDoc;
42 import javax.servlet.ServletRequest JavaDoc;
43 import javax.servlet.ServletResponse JavaDoc;
44 import javax.servlet.http.HttpServletRequest JavaDoc;
45 import javax.servlet.http.HttpServletRequestWrapper JavaDoc;
46 import javax.servlet.http.HttpServletResponse JavaDoc;
47 import javax.servlet.http.HttpSession JavaDoc;
48
49 import org.apache.log4j.Logger;
50 import org.exolab.castor.jdo.Database;
51 import org.infoglue.cms.controllers.kernel.impl.simple.CastorDatabaseService;
52 import org.infoglue.cms.controllers.kernel.impl.simple.RedirectController;
53 import org.infoglue.cms.entities.management.LanguageVO;
54 import org.infoglue.cms.entities.management.RepositoryVO;
55 import org.infoglue.cms.exception.SystemException;
56 import org.infoglue.cms.security.InfoGluePrincipal;
57 import org.infoglue.cms.util.CmsPropertyHandler;
58 import org.infoglue.deliver.applications.databeans.DeliveryContext;
59 import org.infoglue.deliver.controllers.kernel.impl.simple.BaseDeliveryController;
60 import org.infoglue.deliver.controllers.kernel.impl.simple.ExtranetController;
61 import org.infoglue.deliver.controllers.kernel.impl.simple.LanguageDeliveryController;
62 import org.infoglue.deliver.controllers.kernel.impl.simple.NodeDeliveryController;
63 import org.infoglue.deliver.controllers.kernel.impl.simple.RepositoryDeliveryController;
64 import org.infoglue.deliver.util.CacheController;
65 import org.infoglue.deliver.util.RequestAnalyser;
66
67 /**
68  *
69  *
70  * @author Lars Borup Jensen (lbj@atira.dk)
71  */

72
73 public class ViewPageFilter implements Filter JavaDoc
74 {
75     public final static Logger logger = Logger.getLogger(ViewPageFilter.class.getName());
76
77     private FilterConfig JavaDoc filterConfig = null;
78     private URIMatcher uriMatcher = null;
79     private URIMapperCache uriCache = null;
80     public static String JavaDoc attributeName = null;
81     public static boolean caseSensitive = false;
82
83     public void init(FilterConfig JavaDoc filterConfig) throws ServletException JavaDoc
84     {
85         this.filterConfig = filterConfig;
86         String JavaDoc filterURIs = filterConfig.getInitParameter(FilterConstants.FILTER_URIS_PARAMETER);
87
88         String JavaDoc caseSensitiveString = CmsPropertyHandler.getCaseSensitiveRedirects();
89         logger.info("caseSensitiveString:" + caseSensitiveString);
90         caseSensitive = Boolean.getBoolean(caseSensitiveString);
91         
92         uriMatcher = URIMatcher.compilePatterns(splitString(filterURIs, ","), caseSensitive);
93
94         attributeName = CmsPropertyHandler.getNiceURIAttributeName();
95         logger.info("attributeName from properties:" + attributeName);
96         
97         if(attributeName == null || attributeName.indexOf("@") > -1)
98             attributeName = filterConfig.getInitParameter(FilterConstants.ATTRIBUTE_NAME_PARAMETER);
99         
100         logger.info("attributeName from web.xml, filter parameters:" + attributeName);
101         if(attributeName == null || attributeName.equals(""))
102             attributeName = "NavigationTitle";
103
104         logger.info("attributeName used:" + attributeName);
105
106         uriCache = new URIMapperCache();
107     }
108
109     public void doFilter(ServletRequest JavaDoc servletRequest, ServletResponse JavaDoc servletResponse, FilterChain JavaDoc filterChain) throws IOException JavaDoc, ServletException JavaDoc
110     {
111         long end, start = System.currentTimeMillis();
112         HttpServletRequest JavaDoc httpRequest = (HttpServletRequest JavaDoc) servletRequest;
113         HttpServletResponse JavaDoc httpResponse = (HttpServletResponse JavaDoc) servletResponse;
114
115         /*
116         if(RequestAnalyser.getBlockRequests() &&
117            httpRequest.getRequestURI().indexOf("UpdateCache") == -1 &&
118            httpRequest.getRequestURI().indexOf("ViewApplicationState") == -1)
119         {
120             logger.info("Maximum number of clients reached in ViewPageFilter. Responding with an error.");
121             httpResponse.setContentType("text/html; charset=UTF-8");
122             httpRequest.setAttribute("responseCode", "503");
123             httpRequest.getRequestDispatcher("/ErrorPage!busy.action").forward(httpRequest, httpResponse);
124
125             return;
126         }
127         */

128         
129         String JavaDoc enableNiceURI = CmsPropertyHandler.getEnableNiceURI();
130         if (enableNiceURI == null)
131             enableNiceURI = "false";
132
133         validateCmsProperties(httpRequest);
134         String JavaDoc requestURI = URLDecoder.decode(getContextRelativeURI(httpRequest), "UTF-8");
135         logger.info("requestURI:" + requestURI);
136
137         try
138         {
139             if (enableNiceURI.equalsIgnoreCase("true") && !uriMatcher.matches(requestURI))
140             {
141                 /*
142                 synchronized(RequestAnalyser.getCurrentRequests())
143                 {
144                     httpRequest.setAttribute("startTime", new Long(start));
145                     RequestAnalyser.getCurrentRequests().add(httpRequest);
146                 }
147                 */

148                 RequestAnalyser.getRequestAnalyser().incNumberOfCurrentRequests();
149
150                 HttpSession JavaDoc httpSession = httpRequest.getSession(true);
151     
152                 List JavaDoc repositoryVOList = null;
153                 Integer JavaDoc languageId = null;
154     
155                 Database db = CastorDatabaseService.getDatabase();
156                 
157                 BaseDeliveryController.beginTransaction(db);
158                 
159                 try
160                 {
161                     repositoryVOList = getRepositoryId(httpRequest, db);
162                     logger.info("repositoryVOList:" + repositoryVOList.size());
163                     
164                     languageId = getLanguageId(httpRequest, httpSession, repositoryVOList, db);
165                 
166                     Integer JavaDoc siteNodeId = null;
167                     if(languageId != null)
168                     {
169                         String JavaDoc[] nodeNames = splitString(requestURI, "/");
170                         logger.info("nodeNames:" + nodeNames.length);
171                         //logger.info("RepositoryId.: "+repositoryId);
172
//logger.info("LanguageId...: "+languageId);
173
//logger.info("RequestURI...: "+requestURI);
174

175                         InfoGluePrincipal infoGluePrincipal = (InfoGluePrincipal) httpSession.getAttribute("infogluePrincipal");
176                         if (infoGluePrincipal == null)
177                         {
178                             try
179                             {
180                                 infoGluePrincipal = (InfoGluePrincipal) CacheController.getCachedObject("userCache", "anonymous");
181                                 if (infoGluePrincipal == null)
182                                 {
183                                     Map JavaDoc arguments = new HashMap JavaDoc();
184                                     arguments.put("j_username", CmsPropertyHandler.getAnonymousUser());
185                                     arguments.put("j_password", CmsPropertyHandler.getAnonymousPassword());
186                                     infoGluePrincipal = (InfoGluePrincipal)ExtranetController.getController().getAuthenticatedPrincipal(db, arguments);
187                                     if(infoGluePrincipal != null)
188                                         CacheController.cacheObject("userCache", "anonymous", infoGluePrincipal);
189                                 }
190                                 //this.principal = ExtranetController.getController().getAuthenticatedPrincipal("anonymous", "anonymous");
191

192                             }
193                             catch (Exception JavaDoc e)
194                             {
195                                 BaseDeliveryController.rollbackTransaction(db);
196                                 throw new SystemException("There was no anonymous user found in the system. There must be - add the user anonymous/anonymous and try again.", e);
197                             }
198                         }
199         
200                         Iterator JavaDoc repositorVOListIterator = repositoryVOList.iterator();
201                         while(repositorVOListIterator.hasNext())
202                         {
203                             RepositoryVO repositoryVO = (RepositoryVO)repositorVOListIterator.next();
204                             logger.info("Getting node from:" + repositoryVO.getName());
205                             siteNodeId = NodeDeliveryController.getSiteNodeIdFromPath(infoGluePrincipal, repositoryVO, nodeNames, attributeName, languageId, DeliveryContext.getDeliveryContext());
206                             if(siteNodeId != null)
207                                 break;
208                         }
209                     }
210                     
211                     BaseDeliveryController.rollbackTransaction(db);
212
213                     end = System.currentTimeMillis();
214                     
215                     if(siteNodeId == null)
216                     {
217                         String JavaDoc redirectUrl = RedirectController.getController().getRedirectUrl(httpRequest);
218                         if(redirectUrl != null && redirectUrl.length() > 0)
219                         {
220                             httpResponse.sendRedirect(redirectUrl);
221                             return;
222                         }
223                         
224                         logger.warn("Could not map URI " + requestURI + " --> " + siteNodeId);
225                         throw new ServletException JavaDoc("Could not map URI " + requestURI + " --> " + siteNodeId);
226                     }
227                     else
228                         logger.info("Mapped URI " + requestURI + " --> " + siteNodeId + " in " + (end - start) + "ms");
229                     
230                     HttpServletRequest JavaDoc wrappedHttpRequest = prepareRequest(httpRequest, siteNodeId, languageId);
231                     wrappedHttpRequest.getRequestDispatcher("/ViewPage.action").forward(wrappedHttpRequest, httpResponse);
232                 }
233                 catch (SystemException e)
234                 {
235                     BaseDeliveryController.rollbackTransaction(db);
236                     logger.error("Failed to resolve siteNodeId", e);
237                     throw new ServletException JavaDoc(e);
238                 }
239                 catch (Exception JavaDoc e)
240                 {
241                     BaseDeliveryController.rollbackTransaction(db);
242                     throw new ServletException JavaDoc(e);
243                 }
244                 finally
245                 {
246                     BaseDeliveryController.closeDatabase(db);
247                     
248                     RequestAnalyser.getRequestAnalyser().decNumberOfCurrentRequests();
249                 }
250                 
251             }
252             else
253             {
254                 filterChain.doFilter(httpRequest, httpResponse);
255             }
256         }
257         catch (SystemException se)
258         {
259             httpRequest.setAttribute("responseCode", "500");
260             httpRequest.setAttribute("error", se);
261             httpRequest.getRequestDispatcher("/ErrorPage.action").forward(httpRequest, httpResponse);
262         }
263         catch (Exception JavaDoc e)
264         {
265             httpRequest.setAttribute("responseCode", "404");
266             httpRequest.setAttribute("error", e);
267             httpRequest.getRequestDispatcher("/ErrorPage.action").forward(httpRequest, httpResponse);
268         }
269
270     }
271
272     public void destroy()
273     {
274         this.filterConfig = null;
275     }
276
277     private void validateCmsProperties(HttpServletRequest JavaDoc request)
278     {
279         if (CmsPropertyHandler.getProperty(FilterConstants.CMS_PROPERTY_SERVLET_CONTEXT) == null) {
280             CmsPropertyHandler.setProperty(
281                 FilterConstants.CMS_PROPERTY_SERVLET_CONTEXT,
282                 request.getContextPath());
283         }
284     }
285
286     private List JavaDoc getRepositoryId(HttpServletRequest JavaDoc request, Database db) throws ServletException JavaDoc, SystemException, Exception JavaDoc
287     {
288         /*
289         if (session.getAttribute(FilterConstants.REPOSITORY_ID) != null)
290         {
291             logger.info("Fetching repositoryId from session");
292             return (Integer) session.getAttribute(FilterConstants.REPOSITORY_ID);
293         }
294         */

295
296         logger.info("Trying to lookup repositoryId");
297         String JavaDoc serverName = request.getServerName();
298         String JavaDoc portNumber = new Integer JavaDoc(request.getServerPort()).toString();
299         String JavaDoc repositoryName = request.getParameter("repositoryName");
300         logger.info("serverName:" + serverName);
301         logger.info("repositoryName:" + repositoryName);
302
303         String JavaDoc repCacheKey = "" + serverName + "_" + portNumber + "_" + repositoryName;
304         List JavaDoc repositoryVOList = (List JavaDoc)CacheController.getCachedObject(uriCache.CACHE_NAME, repCacheKey);
305         if (repositoryVOList != null)
306         {
307             logger.info("Using cached repositoryVOList");
308             return repositoryVOList;
309         }
310
311         
312         List JavaDoc repositories = RepositoryDeliveryController.getRepositoryDeliveryController().getRepositoryVOListFromServerName(db, serverName, portNumber, repositoryName);
313         logger.info("repositories:" + repositories);
314                 
315
316         if (repositories.size() == 0)
317         {
318             String JavaDoc redirectUrl = RedirectController.getController().getRedirectUrl(request);
319             logger.info("redirectUrl:" + redirectUrl);
320             if(redirectUrl == null || redirectUrl.length() == 0)
321             {
322                 if (repositories.size() == 0)
323                 {
324                     try
325                     {
326                         logger.info("Adding master repository instead - is this correct?");
327                         
328                         repositories.add(RepositoryDeliveryController.getRepositoryDeliveryController().getMasterRepository(db));
329                     }
330                     catch (Exception JavaDoc e1)
331                     {
332                         logger.error("Failed to lookup master repository");
333                     }
334                 }
335                 
336                 if (repositories.size() == 0)
337                     throw new ServletException JavaDoc("Unable to find a repository for server-name " + serverName);
338             }
339         }
340         
341         CacheController.cacheObject(uriCache.CACHE_NAME, repCacheKey, repositories);
342         //session.setAttribute(FilterConstants.REPOSITORY_ID, repository.getRepositoryId());
343
return repositories;
344     }
345
346     private Integer JavaDoc getLanguageId(HttpServletRequest JavaDoc request, HttpSession JavaDoc session, List JavaDoc repositoryVOList, Database db) throws ServletException JavaDoc, Exception JavaDoc
347     {
348         Integer JavaDoc languageId = null;
349         if (request.getParameter("languageId") != null)
350         {
351             logger.info("Language is explicitely given in request");
352             try
353             {
354                 languageId = Integer.valueOf(request.getParameter("languageId"));
355                 session.setAttribute(FilterConstants.LANGUAGE_ID, languageId);
356             }
357             catch (NumberFormatException JavaDoc e) {}
358         }
359
360         if (languageId != null)
361             return languageId;
362
363         if (session.getAttribute(FilterConstants.LANGUAGE_ID) != null) {
364             logger.info("Fetching languageId from session");
365             return (Integer JavaDoc) session.getAttribute(FilterConstants.LANGUAGE_ID);
366         }
367
368         Integer JavaDoc repositoryId = null;
369         if(repositoryVOList != null && repositoryVOList.size() > 0)
370             repositoryId = ((RepositoryVO)repositoryVOList.get(0)).getId();
371         
372         logger.info("Looking for languageId for repository " + repositoryId);
373         Locale JavaDoc requestLocale = request.getLocale();
374        
375         if(repositoryId == null)
376             return null;
377         
378         try
379         {
380             List JavaDoc availableLanguagesForRepository = LanguageDeliveryController.getLanguageDeliveryController().getAvailableLanguagesForRepository(db, repositoryId);
381
382             if (requestLocale != null)
383             {
384                 for (int i = 0; i < availableLanguagesForRepository.size(); i++)
385                 {
386                     LanguageVO language = (LanguageVO) availableLanguagesForRepository.get(i);
387                     logger.info("language:" + language.getLanguageCode());
388                     logger.info("browserLanguage:" + requestLocale.getLanguage());
389                     if (language.getLanguageCode().equalsIgnoreCase(requestLocale.getLanguage())) {
390                         languageId = language.getLanguageId();
391                     }
392                 }
393             }
394             if (languageId == null && availableLanguagesForRepository.size() > 0) {
395                 languageId = ((LanguageVO) availableLanguagesForRepository.get(0)).getLanguageId();
396             }
397         }
398         catch (Exception JavaDoc e)
399         {
400             logger.error("Failed to fetch available languages for repository " + repositoryId);
401         }
402
403         if (languageId == null)
404             throw new ServletException JavaDoc("Unable to determine language for repository " + repositoryId);
405
406         session.setAttribute(FilterConstants.LANGUAGE_ID, languageId);
407         
408         return languageId;
409     }
410
411     // @TODO should I URLDecode the strings first? (incl. context path)
412
private String JavaDoc getContextRelativeURI(HttpServletRequest JavaDoc request) {
413         String JavaDoc requestURI = request.getRequestURI();
414         String JavaDoc contextPath = request.getContextPath();
415         if (contextPath != null && requestURI.length() > 0) {
416             requestURI = requestURI.substring(contextPath.length(), requestURI.length());
417         }
418         if (requestURI.length() == 0)
419             return "/";
420         return requestURI;
421     }
422     
423     private String JavaDoc[] splitString(String JavaDoc str, String JavaDoc delimiter) {
424         List JavaDoc list = new ArrayList JavaDoc();
425         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(str, delimiter);
426         while (st.hasMoreTokens()) {
427             // Updated to handle portal-url:s
428
String JavaDoc t = st.nextToken();
429             if (t.startsWith("_")) {
430                 break;
431             } else {
432                 // Not related to portal - add
433
list.add(t.trim());
434             }
435         }
436         return (String JavaDoc[]) list.toArray(new String JavaDoc[list.size()]);
437     }
438
439     private HttpServletRequest JavaDoc prepareRequest(HttpServletRequest JavaDoc request, Integer JavaDoc siteNodeId, Integer JavaDoc languageId)
440     {
441         HttpServletRequest JavaDoc wrappedRequest = new IGHttpServletRequest(request, siteNodeId, languageId);
442
443         return wrappedRequest;
444     }
445     
446
447     private class IGHttpServletRequest extends HttpServletRequestWrapper JavaDoc
448     {
449         Map JavaDoc requestParameters = new HashMap JavaDoc();
450         
451         public IGHttpServletRequest(HttpServletRequest JavaDoc httpServletRequest, Integer JavaDoc siteNodeId, Integer JavaDoc languageId)
452         {
453             super(httpServletRequest);
454             
455             requestParameters.putAll(httpServletRequest.getParameterMap());
456             requestParameters.put("siteNodeId", new String JavaDoc[] { String.valueOf(siteNodeId)});
457             requestParameters.put("languageId", new String JavaDoc[] { String.valueOf(languageId)});
458         
459             if (requestParameters.get("contentId") == null)
460                 requestParameters.put("contentId", new String JavaDoc[] { String.valueOf(-1)});
461
462             String JavaDoc originalServletPath = ((HttpServletRequest JavaDoc)httpServletRequest).getServletPath();
463             String JavaDoc originalRequestURL = ((HttpServletRequest JavaDoc)httpServletRequest).getRequestURL().toString();
464             String JavaDoc originalQueryString = ((HttpServletRequest JavaDoc)httpServletRequest).getQueryString();
465             //System.out.println("originalServletPath:" + originalServletPath);
466
//System.out.println("originalRequestURL:" + originalRequestURL);
467
requestParameters.put("originalServletPath", new String JavaDoc[] { originalServletPath });
468             requestParameters.put("originalRequestURL", new String JavaDoc[] { originalRequestURL });
469             if(originalQueryString != null && originalQueryString.length() > 0)
470                 requestParameters.put("originalQueryString", new String JavaDoc[] { originalQueryString });
471                 
472             //logger.info("siteNodeId:" + siteNodeId);
473
//logger.info("languageId:" + languageId);
474
//logger.info("contentId:" + requestParameters.get("contentId"));
475
}
476
477         public String JavaDoc getParameter(String JavaDoc s)
478         {
479             String JavaDoc[] array = (String JavaDoc[]) requestParameters.get(s);
480             if (array != null && array.length > 0)
481                 return array[0];
482         
483             return null;
484         }
485
486         public Map JavaDoc getParameterMap()
487         {
488             return Collections.unmodifiableMap(requestParameters);
489         }
490
491         public Enumeration JavaDoc getParameterNames()
492         {
493             return new ParameterNamesEnumeration(requestParameters.keySet().iterator());
494         }
495
496         public String JavaDoc[] getParameterValues(String JavaDoc s)
497         {
498             String JavaDoc[] array = (String JavaDoc[]) requestParameters.get(s);
499             if (array != null && array.length > 0)
500                 return array;
501             
502             return null;
503         }
504         
505     }
506
507     private class ParameterNamesEnumeration implements Enumeration JavaDoc {
508         Iterator JavaDoc it = null;
509
510         public ParameterNamesEnumeration(Iterator JavaDoc it) {
511             this.it = it;
512         }
513
514         public boolean hasMoreElements() {
515             return it.hasNext();
516         }
517
518         public Object JavaDoc nextElement() {
519             return it.next();
520         }
521
522     }
523
524 }
Popular Tags