1 23 24 package org.infoglue.deliver.applications.filters; 25 26 import java.io.IOException ; 27 import java.net.URLDecoder ; 28 import java.util.ArrayList ; 29 import java.util.Collections ; 30 import java.util.Enumeration ; 31 import java.util.HashMap ; 32 import java.util.Iterator ; 33 import java.util.List ; 34 import java.util.Locale ; 35 import java.util.Map ; 36 import java.util.StringTokenizer ; 37 38 import javax.servlet.Filter ; 39 import javax.servlet.FilterChain ; 40 import javax.servlet.FilterConfig ; 41 import javax.servlet.ServletException ; 42 import javax.servlet.ServletRequest ; 43 import javax.servlet.ServletResponse ; 44 import javax.servlet.http.HttpServletRequest ; 45 import javax.servlet.http.HttpServletRequestWrapper ; 46 import javax.servlet.http.HttpServletResponse ; 47 import javax.servlet.http.HttpSession ; 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 72 73 public class ViewPageFilter implements Filter 74 { 75 public final static Logger logger = Logger.getLogger(ViewPageFilter.class.getName()); 76 77 private FilterConfig filterConfig = null; 78 private URIMatcher uriMatcher = null; 79 private URIMapperCache uriCache = null; 80 public static String attributeName = null; 81 public static boolean caseSensitive = false; 82 83 public void init(FilterConfig filterConfig) throws ServletException 84 { 85 this.filterConfig = filterConfig; 86 String filterURIs = filterConfig.getInitParameter(FilterConstants.FILTER_URIS_PARAMETER); 87 88 String 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 servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException , ServletException 110 { 111 long end, start = System.currentTimeMillis(); 112 HttpServletRequest httpRequest = (HttpServletRequest ) servletRequest; 113 HttpServletResponse httpResponse = (HttpServletResponse ) servletResponse; 114 115 128 129 String enableNiceURI = CmsPropertyHandler.getEnableNiceURI(); 130 if (enableNiceURI == null) 131 enableNiceURI = "false"; 132 133 validateCmsProperties(httpRequest); 134 String 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 148 RequestAnalyser.getRequestAnalyser().incNumberOfCurrentRequests(); 149 150 HttpSession httpSession = httpRequest.getSession(true); 151 152 List repositoryVOList = null; 153 Integer 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 siteNodeId = null; 167 if(languageId != null) 168 { 169 String [] nodeNames = splitString(requestURI, "/"); 170 logger.info("nodeNames:" + nodeNames.length); 171 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 arguments = new HashMap (); 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 192 } 193 catch (Exception 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 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 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 ("Could not map URI " + requestURI + " --> " + siteNodeId); 226 } 227 else 228 logger.info("Mapped URI " + requestURI + " --> " + siteNodeId + " in " + (end - start) + "ms"); 229 230 HttpServletRequest 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 (e); 238 } 239 catch (Exception e) 240 { 241 BaseDeliveryController.rollbackTransaction(db); 242 throw new ServletException (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 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 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 getRepositoryId(HttpServletRequest request, Database db) throws ServletException , SystemException, Exception 287 { 288 295 296 logger.info("Trying to lookup repositoryId"); 297 String serverName = request.getServerName(); 298 String portNumber = new Integer (request.getServerPort()).toString(); 299 String repositoryName = request.getParameter("repositoryName"); 300 logger.info("serverName:" + serverName); 301 logger.info("repositoryName:" + repositoryName); 302 303 String repCacheKey = "" + serverName + "_" + portNumber + "_" + repositoryName; 304 List repositoryVOList = (List )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 repositories = RepositoryDeliveryController.getRepositoryDeliveryController().getRepositoryVOListFromServerName(db, serverName, portNumber, repositoryName); 313 logger.info("repositories:" + repositories); 314 315 316 if (repositories.size() == 0) 317 { 318 String 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 e1) 331 { 332 logger.error("Failed to lookup master repository"); 333 } 334 } 335 336 if (repositories.size() == 0) 337 throw new ServletException ("Unable to find a repository for server-name " + serverName); 338 } 339 } 340 341 CacheController.cacheObject(uriCache.CACHE_NAME, repCacheKey, repositories); 342 return repositories; 344 } 345 346 private Integer getLanguageId(HttpServletRequest request, HttpSession session, List repositoryVOList, Database db) throws ServletException , Exception 347 { 348 Integer 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 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 ) session.getAttribute(FilterConstants.LANGUAGE_ID); 366 } 367 368 Integer 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 requestLocale = request.getLocale(); 374 375 if(repositoryId == null) 376 return null; 377 378 try 379 { 380 List 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 e) 399 { 400 logger.error("Failed to fetch available languages for repository " + repositoryId); 401 } 402 403 if (languageId == null) 404 throw new ServletException ("Unable to determine language for repository " + repositoryId); 405 406 session.setAttribute(FilterConstants.LANGUAGE_ID, languageId); 407 408 return languageId; 409 } 410 411 private String getContextRelativeURI(HttpServletRequest request) { 413 String requestURI = request.getRequestURI(); 414 String 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 [] splitString(String str, String delimiter) { 424 List list = new ArrayList (); 425 StringTokenizer st = new StringTokenizer (str, delimiter); 426 while (st.hasMoreTokens()) { 427 String t = st.nextToken(); 429 if (t.startsWith("_")) { 430 break; 431 } else { 432 list.add(t.trim()); 434 } 435 } 436 return (String []) list.toArray(new String [list.size()]); 437 } 438 439 private HttpServletRequest prepareRequest(HttpServletRequest request, Integer siteNodeId, Integer languageId) 440 { 441 HttpServletRequest wrappedRequest = new IGHttpServletRequest(request, siteNodeId, languageId); 442 443 return wrappedRequest; 444 } 445 446 447 private class IGHttpServletRequest extends HttpServletRequestWrapper 448 { 449 Map requestParameters = new HashMap (); 450 451 public IGHttpServletRequest(HttpServletRequest httpServletRequest, Integer siteNodeId, Integer languageId) 452 { 453 super(httpServletRequest); 454 455 requestParameters.putAll(httpServletRequest.getParameterMap()); 456 requestParameters.put("siteNodeId", new String [] { String.valueOf(siteNodeId)}); 457 requestParameters.put("languageId", new String [] { String.valueOf(languageId)}); 458 459 if (requestParameters.get("contentId") == null) 460 requestParameters.put("contentId", new String [] { String.valueOf(-1)}); 461 462 String originalServletPath = ((HttpServletRequest )httpServletRequest).getServletPath(); 463 String originalRequestURL = ((HttpServletRequest )httpServletRequest).getRequestURL().toString(); 464 String originalQueryString = ((HttpServletRequest )httpServletRequest).getQueryString(); 465 requestParameters.put("originalServletPath", new String [] { originalServletPath }); 468 requestParameters.put("originalRequestURL", new String [] { originalRequestURL }); 469 if(originalQueryString != null && originalQueryString.length() > 0) 470 requestParameters.put("originalQueryString", new String [] { originalQueryString }); 471 472 } 476 477 public String getParameter(String s) 478 { 479 String [] array = (String []) requestParameters.get(s); 480 if (array != null && array.length > 0) 481 return array[0]; 482 483 return null; 484 } 485 486 public Map getParameterMap() 487 { 488 return Collections.unmodifiableMap(requestParameters); 489 } 490 491 public Enumeration getParameterNames() 492 { 493 return new ParameterNamesEnumeration(requestParameters.keySet().iterator()); 494 } 495 496 public String [] getParameterValues(String s) 497 { 498 String [] array = (String []) 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 { 508 Iterator it = null; 509 510 public ParameterNamesEnumeration(Iterator it) { 511 this.it = it; 512 } 513 514 public boolean hasMoreElements() { 515 return it.hasNext(); 516 } 517 518 public Object nextElement() { 519 return it.next(); 520 } 521 522 } 523 524 } | Popular Tags |