1 22 23 package org.cofax.cds; 24 25 import java.io.File ; 26 import java.io.FileWriter ; 27 import java.io.IOException ; 28 import java.io.PrintWriter ; 29 import java.io.UnsupportedEncodingException ; 30 import java.net.URLEncoder ; 31 import java.util.Date ; 32 import java.util.Enumeration ; 33 import java.util.HashMap ; 34 import java.util.Iterator ; 35 import java.util.Properties ; 36 37 import javax.servlet.RequestDispatcher ; 38 import javax.servlet.ServletConfig ; 39 import javax.servlet.ServletContext ; 40 import javax.servlet.ServletException ; 41 import javax.servlet.ServletOutputStream ; 42 import javax.servlet.http.HttpServlet ; 43 import javax.servlet.http.HttpServletRequest ; 44 import javax.servlet.http.HttpServletResponse ; 45 46 import org.cofax.CofaxCache; 47 import org.cofax.CofaxJspResponse; 48 import org.cofax.CofaxPage; 49 import org.cofax.CofaxUtil; 50 import org.cofax.DataStore; 51 import org.cofax.Glossary; 52 import org.cofax.Redirection; 53 import org.cofax.TemplateLoader; 54 import org.cofax.TemplateProcessor; 55 import org.cofax.cms.login.ILoginHandler; 56 57 78 79 public class CDSServlet extends HttpServlet { 80 81 84 private static final long serialVersionUID = -1521543069026357290L; 85 86 89 public final static String COFAX_VERSION = "Revision : 2.3 / Build date : 2006/12/07"; 90 91 94 private static int maxUrlLength; 95 96 101 private static String searchTemplate; 102 103 106 private static String searchEngineFileTemplate; 107 108 111 private static String searchEngineListTemplate; 112 113 116 public static String contextPath; 117 118 public static String articleRessourceFolder; 120 121 public static String userImageFolder; 122 123 126 private static String servletPath; 127 128 131 private static String dataStoreClass; 132 133 136 private static String templateProcessorClass; 137 138 141 private static String IPStartsWith; 142 143 private static String IPEquals; 144 145 private static String IPExceptionsStartsWith; 146 147 private static String IPExceptionsEquals; 148 149 private static String PortNumberEquals; 150 151 private static String PortNameEquals; 152 153 156 private static Redirection cofaxRedirect; 157 158 161 private static String redirectionClass; 162 163 166 static CofaxCache cacheOfPages; 167 168 171 static CofaxCache cacheOfTemplates; 172 173 176 static CofaxCache cacheOfPackageTags; 177 178 181 private static TemplateLoader templateLoader; 182 183 186 static DataStore dataStore; 187 188 191 private static HashMap configGlossary = new HashMap (); 192 193 196 public static String templatePath = ""; 197 198 public static String templateLoaderClass = ""; 199 200 public static String listTemplate = ""; 201 202 public static String fileTemplate = ""; 203 204 207 public static String mailHost = ""; 208 209 211 private static String logFolder; 212 213 private static String logLocation; 214 215 219 private static String defaultPublication; 220 221 226 public String getServletInfo() { 227 228 return "For more information about cofax, refer to http://www.cofax.org/"; 229 } 230 231 240 public final void init(ServletConfig config) throws ServletException { 241 242 super.init(config); 243 244 boolean errorInitializing = false; 245 templatePath = ""; 246 String dataStoreName = ""; 247 try { 249 ServletContext context = getServletContext(); 251 252 contextPath = context.getRealPath("/"); 255 256 logFolder = contextPath; 258 try { 259 logFolder = config.getInitParameter("logFolder"); 260 if (!(logFolder.endsWith(File.separator))) 261 logFolder += File.separator; 262 } catch (Exception e) { 263 logFolder = contextPath; 264 System.err.println("[WARNING] logFolder parameter not initialized. 'contextPath' value used instead"); 265 } 266 267 try { 269 defaultPublication = config.getInitParameter("defaultPublication"); 270 if (!(defaultPublication.endsWith("/"))) 271 defaultPublication += "/"; 272 } catch (Exception e) { 273 System.err.println("[WARNING] defaultPublication parameter not initialized."); 274 } 275 276 logLocation = logFolder + "cofax-cds.log"; 277 278 for (Enumeration params = config.getInitParameterNames(); params.hasMoreElements();) { 281 String paramName = (String ) params.nextElement(); 282 if (paramName.indexOf("configGlossary:") > -1) { 283 configGlossary.put(paramName, config.getInitParameter(paramName)); 284 } 285 } 286 287 maxUrlLength = 512; 289 try { 290 maxUrlLength = Integer.parseInt(config.getInitParameter("maxUrlLength")); 291 } catch (Exception e) { 292 maxUrlLength = 512; 293 } 294 295 WebBrowser.init(contextPath + config.getInitParameter("searchEngineRobotsDb")); 297 298 searchEngineFileTemplate = config.getInitParameter("searchEngineFileTemplate"); 300 searchEngineListTemplate = config.getInitParameter("searchEngineListTemplate"); 301 302 int cache_packageTags_maxTrack = Integer.parseInt(config.getInitParameter("cachePackageTagsTrack")); 304 int cache_packageTags_maxStore = Integer.parseInt(config.getInitParameter("cachePackageTagsStore")); 305 int cache_packageTags_refresh = Integer.parseInt(config.getInitParameter("cachePackageTagsRefresh")); 306 cacheOfPackageTags = new CofaxCache(cache_packageTags_maxTrack, cache_packageTags_maxStore, cache_packageTags_refresh, 0); 307 308 int cache_pages_maxTrack = Integer.parseInt(config.getInitParameter("cachePagesTrack")); 310 int cache_pages_maxStore = Integer.parseInt(config.getInitParameter("cachePagesStore")); 311 int cache_pages_refresh = Integer.parseInt(config.getInitParameter("cachePagesRefresh")); 312 int cache_pages_dirtyRead = Integer.parseInt(config.getInitParameter("cachePagesDirtyRead")); 313 cacheOfPages = new CofaxCache(cache_pages_maxTrack, cache_pages_maxStore, cache_pages_refresh, cache_pages_dirtyRead); 314 315 int cache_templates_maxTrack = Integer.parseInt(config.getInitParameter("cacheTemplatesTrack")); 317 int cache_templates_maxStore = Integer.parseInt(config.getInitParameter("cacheTemplatesStore")); 318 int cache_templates_refresh = Integer.parseInt(config.getInitParameter("cacheTemplatesRefresh")); 319 cacheOfTemplates = new CofaxCache(cache_templates_maxTrack, cache_templates_maxStore, cache_templates_refresh, 0); 320 321 IPStartsWith = config.getInitParameter("IPStartsWith"); 323 IPEquals = config.getInitParameter("IPEquals"); 324 IPExceptionsStartsWith = config.getInitParameter("IPExceptionsStartsWith"); 325 IPExceptionsEquals = config.getInitParameter("IPExceptionsEquals"); 326 PortNumberEquals = config.getInitParameter("PortNumberEquals"); 327 PortNameEquals = config.getInitParameter("PortNameEquals"); 328 329 templatePath = config.getInitParameter("templatePath"); 331 templatePath = contextPath + templatePath; 332 templateProcessorClass = config.getInitParameter("templateProcessorClass"); 333 listTemplate = config.getInitParameter("defaultListTemplate"); 334 fileTemplate = config.getInitParameter("defaultFileTemplate"); 335 searchTemplate = config.getInitParameter("defaultSearchTemplate"); 336 int templateMode = Integer.parseInt(config.getInitParameter("templateMode")); 337 int templateSearchLimit = Integer.parseInt(config.getInitParameter("templateSearchLimit")); 338 templateLoaderClass = config.getInitParameter("templateLoaderClass"); 339 if (templatePath == null || templatePath.equals("")) { 340 System.err.println("ERROR getting template path"); 341 errorInitializing = true; 342 } 343 try { 344 Class c = Class.forName(templateLoaderClass); 345 templateLoader = (TemplateLoader) c.newInstance(); 346 templateLoader.setTemplateRoot(templatePath); 347 templateLoader.setDefaultIndex(listTemplate); 348 templateLoader.setDefaultObject(fileTemplate); 349 templateLoader.setTemplateMode(templateMode); 350 templateLoader.setTemplateSearchLimit(templateSearchLimit); 351 } catch (Exception e) { 352 System.err.println("Error loading template loader class:"); 353 e.printStackTrace(System.err); 354 errorInitializing = true; 355 } 356 357 mailHost = config.getInitParameter("mailHost"); 359 360 boolean useDataStore = Boolean.valueOf(config.getInitParameter("useDataStore")).booleanValue(); 362 363 dataStoreName = config.getInitParameter("dataStoreName"); 364 dataStoreClass = config.getInitParameter("dataStoreClass"); 365 redirectionClass = config.getInitParameter("redirectionClass"); 366 367 Properties dbProps = new Properties (); 370 dbProps.setProperty("drivers", config.getInitParameter("dataStoreDriver")); 371 dbProps.setProperty("logfile", config.getInitParameter("dataStoreLogFile")); 372 dbProps.setProperty(dataStoreName + ".url", config.getInitParameter("dataStoreUrl")); 373 dbProps.setProperty(dataStoreName + ".user", config.getInitParameter("dataStoreUser")); 374 dbProps.setProperty(dataStoreName + ".password", config.getInitParameter("dataStorePassword")); 375 dbProps.setProperty(dataStoreName + ".initconns", config.getInitParameter("dataStoreInitConns")); 376 dbProps.setProperty(dataStoreName + ".maxconns", config.getInitParameter("dataStoreMaxConns")); 377 dbProps.setProperty(dataStoreName + ".connusagelimit", config.getInitParameter("dataStoreConnUsageLimit")); 378 dbProps.setProperty(dataStoreName + ".testquery", config.getInitParameter("dataStoreTestQuery")); 379 dbProps.setProperty(dataStoreName + ".loglevel", config.getInitParameter("dataStoreLogLevel")); 380 381 if (!useDataStore) { 382 dataStoreName = "cofax"; 383 dataStoreClass = "org.cofax.DummyDataStore"; 384 redirectionClass = "org.cofax.DummyRedirection"; 385 } 386 try { 387 Class c = Class.forName(dataStoreClass); 388 dataStore = (DataStore) c.newInstance(); 389 if (useDataStore) { 390 dataStore.init(dbProps); 391 dataStore.setDataStoreName(dataStoreName); 392 dataStore.setCache(cacheOfPackageTags, DataStore.PACKAGE_TAG_CACHE); 393 } 394 } catch (Exception e) { 395 System.err.println("Error loading data store class:"); 396 e.printStackTrace(System.err); 397 errorInitializing = true; 398 } 399 try { 400 Class c = Class.forName(redirectionClass); 401 cofaxRedirect = (Redirection) c.newInstance(); 402 if (useDataStore) { 403 cofaxRedirect.init(dataStore); 404 } 405 } catch (Exception e) { 406 System.err.println("Error loading redirection class:"); 407 e.printStackTrace(System.err); 408 errorInitializing = true; 409 } 410 411 printConfiguration(); 413 414 } catch (Exception e) { 415 System.err.println("Error reading configuration:"); 416 e.printStackTrace(System.err); 417 errorInitializing = true; 418 } 419 420 String loginHandlerName = config.getInitParameter("loginHandlerName"); 422 ILoginHandler loginHandler = null; 423 try { 424 Class c = Class.forName(loginHandlerName); 425 loginHandler = (ILoginHandler) c.newInstance(); 426 loginHandler.init(config); 427 } catch (Exception e) { 428 System.err.println("Error reading configuration:"); 429 e.printStackTrace(System.err); 430 errorInitializing = true; 431 } 432 433 getServletContext().setAttribute("cacheOfPages", cacheOfPages); 435 getServletContext().setAttribute("cacheOfTemplates", cacheOfTemplates); 436 getServletContext().setAttribute("cacheOfPackageTags", cacheOfPackageTags); 437 getServletContext().setAttribute("dataStore", dataStore); 438 getServletContext().setAttribute("dataStoreName", dataStoreName); 439 getServletContext().setAttribute("dataStoreClass", dataStoreClass); 440 getServletContext().setAttribute("COFAX_VERSION", COFAX_VERSION); 441 getServletContext().setAttribute("applicationPath", contextPath); 442 getServletContext().setAttribute("templatePath", templatePath); 443 getServletContext().setAttribute("adminEmail", CofaxUtil.getString(configGlossary, "configGlossary:adminEmail")); 444 getServletContext().setAttribute("loginHandler", loginHandler); 445 446 if (errorInitializing) { 448 throw new ServletException ("Could not initilize CDSServlet. This was likely the result of a misconfiguration."); 449 } 450 } 451 452 470 private static String checkClientAccessRestriction(HttpServletRequest req) { 471 String returnedString = ""; 472 String IPClient = ""; 473 String IPForward = ""; 474 475 if (req.getHeader("X-Forwarded-For") != null) 476 IPForward = req.getHeader("X-Forwarded-For"); 477 478 String [] tabIPStartsWith = (IPStartsWith != null) ? IPStartsWith.split(",") : null; 479 String [] tabIPEquals = (IPEquals != null) ? IPEquals.split(",") : null; 480 String [] tabIPExceptionsStartsWith = (IPExceptionsStartsWith != null) ? IPExceptionsStartsWith.split(",") : null; 481 String [] tabIPExceptionsEquals = (IPExceptionsEquals != null) ? IPExceptionsEquals.split(",") : null; 482 String [] tabPortNumberEquals = (PortNumberEquals != null) ? PortNumberEquals.split(",") : null ; 483 String [] tabPortNameEquals = (PortNameEquals != null ) ? PortNameEquals.split(",") : null ; 484 485 486 490 if ( tabIPStartsWith == null && 491 tabIPEquals == null && 492 tabIPExceptionsStartsWith == null && 493 tabIPExceptionsEquals == null && 494 tabPortNumberEquals == null && 495 tabPortNameEquals == null 496 ) 497 { 498 return "public"; 500 } 501 502 String [] tabIPforward = null; 503 504 if ((IPForward != null) || (tabIPforward.length > 0)) { 505 tabIPforward = IPForward.split(","); 506 IPClient = tabIPforward[tabIPforward.length - 1]; 507 } 508 509 if (IPClient.length() < 1) { 510 IPClient = req.getRemoteAddr(); 511 } 512 513 int cptIPStartsWith = 0; 514 int cptIPEquals = 0; 515 int cptIPExceptionsStartsWith = 0; 516 int cptIPExceptionsEquals = 0; 517 int cptPortNumberEquals = 0; 518 int cptPortNameEquals = 0; 519 520 boolean privateClient = false; 521 522 if (IPStartsWith.length() > 0) { 523 while (cptIPStartsWith < tabIPStartsWith.length) { 524 if (IPClient.startsWith(tabIPStartsWith[cptIPStartsWith])) 525 privateClient = true; 526 cptIPStartsWith++; 527 } 528 } 529 530 if (IPEquals.length() > 0) { 531 while (cptIPEquals < tabIPEquals.length) { 532 if (IPClient.equals(tabIPEquals[cptIPEquals])) 533 privateClient = true; 534 cptIPEquals++; 535 } 536 } 537 538 if (IPExceptionsStartsWith.length() > 0) { 539 while (cptIPExceptionsStartsWith < tabIPExceptionsStartsWith.length) { 540 if (IPClient.startsWith(tabIPExceptionsStartsWith[cptIPExceptionsStartsWith])) 541 privateClient = false; 542 cptIPExceptionsStartsWith++; 543 } 544 } 545 546 if (IPExceptionsEquals.length() > 0) { 547 while (cptIPExceptionsEquals < tabIPExceptionsEquals.length) { 548 if (IPClient.equals(tabIPExceptionsEquals[cptIPExceptionsEquals])) 549 privateClient = false; 550 cptIPExceptionsEquals++; 551 } 552 } 553 554 if (PortNumberEquals.length() > 0) { 555 while (cptPortNumberEquals < tabPortNumberEquals.length) { 556 if (req.getServerPort() == Integer.parseInt(tabPortNumberEquals[cptPortNumberEquals])) 557 privateClient = true; 558 cptPortNumberEquals++; 559 } 560 } 561 562 if (PortNameEquals.length() > 0) { 563 while (cptPortNameEquals < tabPortNumberEquals.length) { 564 if (req.getScheme().equals(tabPortNameEquals[cptPortNameEquals])) 565 privateClient = true; 566 cptPortNameEquals++; 567 } 568 } 569 570 if (privateClient) { 571 returnedString = "private"; 572 } else { 573 returnedString = "public"; 574 } 575 576 return returnedString; 577 } 578 579 590 608 609 621 public final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException { 622 623 doGet(request, response); 624 625 } 626 627 645 public final void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException , IOException { 646 647 long cacheStart = System.currentTimeMillis(); 648 CofaxPage page = new CofaxPage(); 649 653 String pageId = ""; 654 String hostName = ""; 655 656 String queryString = ""; 657 String pathInfo = ""; 658 String requestedUrl = ""; 659 String requestedUrlWithoutQueryString = ""; 660 661 String templateId = ""; 662 HashMap glossary = new HashMap (); 663 boolean usingJSP = false; 664 665 servletPath = req.getServletPath(); 666 pathInfo = req.getPathInfo(); 667 if (pathInfo == null) { 668 pathInfo = servletPath; 669 } 670 671 queryString = req.getQueryString(); 672 Object tmp = req.getHeader("host"); 673 675 if (tmp != null) { 676 hostName = (String ) tmp; 677 } else { 678 hostName = req.getServerName(); 679 } 680 681 if (pathInfo.length() > maxUrlLength) { 682 page.setStatus(HttpServletResponse.SC_REQUEST_URI_TOO_LONG); 683 page.setErrorMsg("ERROR: Requested URI was too long. The administrator has set length to: " + maxUrlLength); 684 } 685 686 691 requestedUrl = req.getScheme() + "://" + hostName + req.getRequestURI(); 693 694 pageId = checkClientAccessRestriction(req) + pathInfo; 696 697 String contextName = req.getContextPath(); 698 cofaxLog("contextName= " + contextName + "\nrequestedUrl= " 699 + requestedUrl); 700 if (requestedUrl.endsWith(contextName + "/") || requestedUrl.endsWith(contextName)) { 701 if (!requestedUrl.endsWith("/")) 702 requestedUrl += "/"; 703 String _redirection = requestedUrl + defaultPublication + "/"; 704 cofaxLog("Redirection= " + _redirection); 705 res.sendRedirect(_redirection); 706 return; 708 } 709 710 712 requestedUrlWithoutQueryString = requestedUrl; 713 if (!(queryString == null || queryString.equals(""))) { 719 requestedUrl += "?" + queryString; 720 pageId += "?" + queryString; 721 } 722 try { 723 724 if ((cacheOfPages.isPageCached(pageId)) && (cacheOfPages.getPage(pageId).getStatus() == HttpServletResponse.SC_OK) 726 727 ) { 728 729 731 page = cacheOfPages.getPage(pageId); 734 737 if ((System.currentTimeMillis() - page.getLastModified()) < cacheOfPages.getRefreshInterval()) { 738 743 744 cacheOfPages.incrementHitCount(pageId); 748 page.setStatus(HttpServletResponse.SC_OK); 749 page.setServingClient(req.getRemoteAddr()); 750 751 sendHeaders(page, res); 752 753 ServletOutputStream out = res.getOutputStream(); 754 String content = new String (page.toString()); out.print(content); 760 page.setEndBuildTime(); 761 out.print(page.pageAge()); 762 out.print(page.cacheTime(cacheStart)); 763 out.flush(); out.close(); 766 767 768 cacheOfPages.CleanIfPossible(); 769 return; } 771 772 } 773 774 page.reset(); 776 glossary = initializeGlossary(req, page, pathInfo, requestedUrl, queryString, requestedUrlWithoutQueryString, pageId, hostName); 780 781 782 783 786 788 791 if (page.getStatus() != HttpServletResponse.SC_OK) { 792 throw new ServletException ("Cofax Internal Error"); 793 } 794 795 String urlToRedirectTo = CofaxUtil.getString(glossary, "request:urlToRedirectTo"); 798 799 801 if (!urlToRedirectTo.equals("")) { 802 res.sendRedirect(urlToRedirectTo); 803 return; 804 } 805 806 addToGlossary(req, glossary); 808 page.setLastModified(Long.parseLong((String ) glossary.get("request:todayMilliSecs"))); 810 templateLoader.setTemplateSearch(templateLoader.getTemplateRoot() + "/" + glossary.get("request:templateSearch").toString()); 811 812 templateId = templateLoader.choose(glossary.get("request:fileNameWithExtension").toString(), CofaxUtil.getString(glossary, "request:template"), 813 CofaxUtil.getString(glossary, "request:fileNameExtension")); 814 if (templateId.endsWith(".JSP") || templateId.endsWith(".jsp")) { 815 usingJSP = true; 816 templateId = templateLoader.getResource(templateId, contextPath); 817 } else { 818 usingJSP = false; 819 } 820 821 glossary.put("request:templateId", templateId); 822 if (templateId.equals("")) { 823 page.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 824 page.setErrorMsg("Error: Template not found to satisfy request."); 825 } 826 827 DataStore db = null; 829 db = (DataStore) (Class.forName(dataStoreClass)).newInstance(); 830 831 if (db == null) { 832 page.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 833 page.setErrorMsg("Error: Could not create DataStore object db."); 834 throw new ServletException ("Cofax Internal Error"); 835 } else if (page.getStatus() == HttpServletResponse.SC_OK) { 836 Glossary cofaxGlossary = new Glossary(); 837 page.setGlossary(cofaxGlossary); 838 page.addToGlossary(glossary); 839 page.setTemplateLoader(templateLoader); 840 page.setDataStore(db); 841 page.setServingPage(req.getRequestURI()); 842 page.setServingClient(req.getRemoteAddr()); 843 844 if (usingJSP) { req.setAttribute("cofaxPage", page); 846 847 848 try { 849 CofaxJspResponse jspResponse = new CofaxJspResponse(res, page); 850 RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(templateId); 851 dispatcher.include(req, jspResponse); 852 if (page.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY) { 853 res.sendRedirect(jspResponse.getRedirect()); 854 return; 855 } 856 860 String _output = req.getParameter("output"); 861 if (_output != null) { 862 page.putHeader("Content-Type", _output); 863 } 864 865 page.append(jspResponse.toString()); 866 } catch (IOException ioe) { 867 String errText = ioe.toString(); 868 page.setErrorMsg(errText); 869 System.err.println(ioe); 870 throw new ServletException ("Cofax Internal IOException"); 871 } catch (ServletException e) { 872 String errText = e.toString(); 873 page.setErrorMsg(errText); 874 System.err.println(e); 875 throw new ServletException ("Cofax Internal ServletException"); 876 } catch (Exception e) { 877 String errText = e.toString(); 878 page.setErrorMsg(errText); 879 System.err.println(e); 880 throw new ServletException ("Cofax Internal Exception"); 881 } 882 883 } else { 885 CofaxPage template; 888 cacheOfTemplates.incrementHitCount(templateId); 889 if (cacheOfTemplates.isPageCached(templateId)) { 890 template = cacheOfTemplates.getPage(templateId); 891 } else { 892 template = templateLoader.load(templateId); 893 } 894 895 TemplateProcessor tp = null; 897 tp = (TemplateProcessor) (Class.forName(templateProcessorClass)).newInstance(); 898 899 tp.setPage(page); 900 tp.setTemplate(template); 901 902 if (tp.applyTemplate()) { 903 page.setStatus(HttpServletResponse.SC_OK); 904 } else { 905 if (page.getStatus() == HttpServletResponse.SC_OK) { 906 page.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 907 } 908 throw new ServletException ("Cofax Internal Error"); 909 } 910 917 } 918 if (page.getStatus() == HttpServletResponse.SC_OK) { 920 page.append("\r\n<!-- Powered By: " + CofaxUtil.getString(glossary, "configGlossary:poweredBy") + " at " 921 + CofaxUtil.getString(glossary, "configGlossary:installationAt") + " -->\r\n"); 922 page.setEndBuildTime(); 923 page.append(page.buildTime(cacheStart)); 924 if (!page.mustBeCached()) { 925 page.append("\r\n<!-- page was generated without the cache -->"); 926 } 927 cacheOfPages.incrementHitCount(pageId); 928 page.putHeader("X-Cofax", COFAX_VERSION); 930 page.putHeader("Server", "Cofax/" + COFAX_VERSION); 931 if (CofaxUtil.getString(glossary, "PublicationGlossary:P3PPolicyRef") != "") { 932 String P3P = CofaxUtil.getString(glossary, "PublicationGlossary:P3PPolicyRef") + ", CP=" 933 + CofaxUtil.getString(glossary, "PublicationGlossary:P3PCompactHeader"); 934 page.putHeader("P3P", P3P); 935 } 936 if (cacheOfPages.shouldPageBeCached(pageId) && page.mustBeCached()) { 938 page.setPageId(pageId); 939 cacheOfPages.addPageToCache(pageId, page); 940 } 941 } 942 943 } 944 } catch (Exception e) { 945 String errMsg = e.toString(); 946 if (page.getStatus() == HttpServletResponse.SC_OK) { 947 page.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 948 } 949 if (page.getErrorMsg().equals("")) { 950 page.setErrorMsg(errMsg); 951 } 952 if (errMsg.indexOf("Cofax Internal Error") == -1) { 953 System.err.print("Cofax Handeled Internal Error.\n "); 954 System.err.print(" Cofax Error: " + errMsg + "\n"); 955 System.err.print(" Error: " + errMsg + "\n"); 956 System.err.print(" Stack: "); 957 e.printStackTrace(System.err); 958 System.err.print("\n"); 959 } 960 } finally { 961 boolean cacheError = false; 963 if (page.getStatus() != HttpServletResponse.SC_OK) { 964 if (page.getStatus() == HttpServletResponse.SC_NOT_FOUND) { 965 cacheError = true; 966 } 967 968 if (CofaxUtil.getString(glossary, "PublicationGlossary:errorHeaders").equals("1")) { 969 res.sendError(page.getStatus()); 970 } else { 971 page.reset(); 972 page.append("<title>Cofax Error -- " + req.getRequestURI() + "</title>\n"); 973 page.append("<body bgcolor=FFFFFF>\n"); 974 page.append("<h2>An Error Has Occured</h2>"); 975 page.append("Cofax has encountered and error while processing your request.<br>\n"); 976 page.append("Cofax Version: " + COFAX_VERSION + "<br><br>\n"); 977 page.append("<dd><font color=FF2121>Error Message:</font> " + page.getStatus() + ": "); 978 page.append(page.getErrorMsg() + "<br>\n"); 979 page.append("<dd>Request: " + req.getRequestURI() + "<br>\n"); 980 page.append("<dd>Template: " + templateId + "<br><br>\n"); 981 page.append("Please try one of the following:<ul>\n"); 982 page.append("<li><a HREF=javascript:window.location.reload()>reload this page</a></li>\n"); 983 page.append("<li><a HREF=javascript:window.history.back()>return to your previous page</a></li>\n"); 984 page.append("<li><a HREF=" + req.getContextPath() + "/" + CofaxUtil.getString(glossary, "request:pubName")); 985 page.append(">go to the home for this publication</a></li>\n"); 986 page.append("<li><a HREF=mailto:i" + CofaxUtil.getString(glossary, "configGlossary:adminEmail") + ">contact " 987 + CofaxUtil.getString(glossary, "configGlossary:adminTitle") + "</a></li></ul>\n"); 988 System.err.print("Cofax encountered and handeled a delivery Error of Type: " + page.getStatus() + "\n"); 989 System.err.print(" Error: " + page.getErrorMsg() + "\n"); 990 System.err.print(" Serving: " + req.getRequestURI() + "\n"); 991 992 } 993 } 994 if (!cacheError) { 996 sendHeaders(page, res); 999 1000 ServletOutputStream out = res.getOutputStream(); 1001 page.setEndBuildTime(); 1002 String content = new String (page.toString()); 1003 out.print(content); 1004 out.flush(); out.close(); 1008 1009 } } 1011 1012 cacheOfPages.CleanIfPossible(); 1013 1014 return; 1015 } 1016 1017 1025 private void sendHeaders(CofaxPage page, HttpServletResponse res) { 1026 1027 HashMap headers = page.getHeaders(); 1028 res.setContentType(page.getHeader("Content-Type")); 1029 1030 if (headers != null && !headers.isEmpty()) { 1031 for (Iterator i = headers.keySet().iterator(); i.hasNext();) { 1032 String headerName = i.next().toString(); 1033 String headerValue = headers.get(headerName).toString(); 1034 res.setHeader(headerName, headerValue); 1035 } 1036 } 1037 } 1038 1039 1040 1043 public void destroy() { 1044 1045 dataStore.destroy(); 1046 super.destroy(); 1047 1048 } 1049 1050 1059 private static HashMap initializeGlossary(HttpServletRequest req, CofaxPage page, String pathInfo, String requestedUrl, String queryString, 1060 String requestedUrlWithoutQueryString, String pageId, String hostName) { 1061 1062 HashMap glossary = new HashMap (); 1063 1064 Enumeration e; 1065 String tag = ""; 1066 String value = ""; 1067 1068 for (e = req.getHeaderNames(); e.hasMoreElements();) { 1070 tag = (String ) e.nextElement(); 1071 value = req.getHeader(tag); 1072 glossary.put("http_header:" + tag, value + ""); 1073 } 1074 1075 String refresh = req.getParameter("refresh"); 1078 if (!(refresh == null || refresh.equals("true"))) { 1079 page.putHeader("Expires", "0"); 1080 page.putHeader("Pragma", "no-cache"); 1081 page.putHeader("Cache-Control", "no-cache"); 1082 } 1083 1084 boolean isSection = false; 1090 int positionOfLastSlash = pathInfo.lastIndexOf('/'); 1091 if (positionOfLastSlash != -1) { 1092 String fileName = pathInfo.substring(positionOfLastSlash); 1093 if (fileName.indexOf('.') == -1) { 1094 isSection = true; 1095 } 1096 } else { 1097 isSection = true; 1098 } 1099 String urlToRedirectTo = ""; 1102 if (isSection && !pathInfo.endsWith("/")) { 1103 if (requestedUrl.indexOf("?") > -1) { 1104 urlToRedirectTo = requestedUrlWithoutQueryString + "/?" + queryString; 1105 } else { 1106 urlToRedirectTo = requestedUrl + "/"; 1107 } 1108 glossary.put("request:urlToRedirectTo", urlToRedirectTo); 1110 } 1111 1112 WebBrowser browser = new WebBrowser(req); 1117 if (browser.isCrawler()) { 1118 if (isSection) { 1119 queryString = "template=" + searchEngineListTemplate; 1120 glossary.put("request:template", searchEngineListTemplate); 1121 } else { 1122 queryString = "template=" + searchEngineFileTemplate; 1123 glossary.put("request:template", searchEngineFileTemplate); 1124 } 1125 } 1126 1127 String redirectPathInfo = cofaxRedirect.getRedirection(pathInfo.toLowerCase()); 1129 1130 if (!redirectPathInfo.equals("") && redirectPathInfo.indexOf("INVALID") == -1) { 1131 redirectPathInfo = req.getScheme() + "://" + hostName + req.getContextPath() + redirectPathInfo; 1132 glossary.put("request:urlToRedirectTo", redirectPathInfo); 1133 } else if (redirectPathInfo.indexOf("INVALID") > -1) { 1134 page.setStatus(HttpServletResponse.SC_NOT_FOUND); 1135 page.setErrorMsg("ERROR: Requested URI contained " + redirectPathInfo); 1136 return glossary; 1137 } 1138 1139 glossary.put("request:requestedUrlWithoutQueryString", requestedUrlWithoutQueryString); 1140 glossary.put("request:url", requestedUrlWithoutQueryString); 1141 glossary.put("request:pageId", pageId); 1142 glossary.put("request:requestedUrl", requestedUrl); 1143 1144 try { 1145 glossary.put("request:requestedUrlEncoded", URLEncoder.encode(requestedUrl, "UTF-8")); 1146 } catch (UnsupportedEncodingException uee) { 1147 System.err.println("URLEncoder error : "); 1148 uee.printStackTrace(System.err); 1149 } 1150 1151 glossary.put("request:queryString", queryString + ""); 1152 glossary.put("request:query_string", queryString + ""); 1153 glossary.put("request:pathInfo", pathInfo); 1154 glossary.put("request:hostName", hostName); 1155 glossary.put("request:cofaxVersion", COFAX_VERSION); 1156 1157 for (Iterator i = configGlossary.keySet().iterator(); i.hasNext();) { 1159 String key2 = i.next().toString(); 1160 String value2 = configGlossary.get(key2).toString(); 1161 glossary.put(key2, value2); 1162 } 1163 1164 glossary.put("client", checkClientAccessRestriction(req)); glossary.put("request:client", checkClientAccessRestriction(req)); 1169 glossary.put("request:contextPath", req.getContextPath()); 1172 1173 return glossary; 1174 } 1175 1176 1178 1188 private final static void addToGlossary(HttpServletRequest req, HashMap glossary) { 1189 1190 String pathInfo = glossary.get("request:pathInfo").toString(); 1193 1194 String pub = ""; 1195 String date = ""; 1196 String section = ""; 1197 String fileNameWithExtension = ""; 1198 String fileName = ""; 1199 int datePartCount = 0; 1201 String fileNameExtension = ""; 1202 Date dateObject = new Date (); 1203 long dateMilliSecs = dateObject.getTime(); 1204 int count = 0; 1205 Iterator paths = CofaxUtil.split("/", pathInfo).iterator(); 1207 1208 while (paths.hasNext()) { 1209 String path = (String ) paths.next(); 1212 glossary.put("request:pathPart[" + count + "]", path); 1213 1214 if (path.indexOf('.') > -1) { 1215 fileNameWithExtension = path; 1216 } else { 1218 if (CofaxUtil.isDigits(path) && datePartCount <= 3 && !path.equals("")) { 1220 datePartCount++; 1221 if (datePartCount == 1) { 1222 date = path; 1223 } else if (datePartCount == 2) { 1224 date = date + "/" + path; 1225 } else if (datePartCount == 3) { 1226 date = date + "/" + path; 1227 } 1228 } else { 1229 if (count == 1) { 1230 pub = path; 1231 } else { 1232 if (section.equals("")) { 1233 section = path; 1235 } else { 1236 section = section + "/" + path; 1237 } 1238 } 1239 } 1240 } 1241 count++; 1242 } 1243 1244 if (section.equals("")) { 1247 glossary.put("request:templateSearch", pub); 1248 } else { 1249 glossary.put("request:templateSearch", pub + "/" + section); 1250 } 1251 1252 int dotLoc = fileNameWithExtension.lastIndexOf('.'); 1255 if (dotLoc > -1) { 1256 fileName = fileNameWithExtension.substring(0, dotLoc); 1257 fileNameExtension = fileNameWithExtension.substring(dotLoc); 1258 } 1259 1260 glossary.put("request:date", date); 1261 glossary.put("request:today", CofaxUtil.getDateFormat("yyyy/MM/dd", "") + ""); 1262 glossary.put("request:todayMilliSecs", String.valueOf(dateMilliSecs)); 1263 glossary.put("request:date_format_1", CofaxUtil.getDateFormat("EEEE, MMMM d, yyyy", date) + ""); 1264 glossary.put("request:day_of_week", CofaxUtil.getDateFormat("EEE", date) + ""); 1265 glossary.put("request:name", section); 1266 glossary.put("request:section", section); 1267 glossary.put("request:publication", pub); 1268 glossary.put("request:pubName", pub); 1269 glossary.put("request:path_info", pathInfo); 1270 glossary.put("request:file_name", fileName); 1271 glossary.put("request:fileName", fileName); 1272 glossary.put("request:fileNameWithExtension", fileNameWithExtension); 1273 glossary.put("request:fileNameExtension", fileNameExtension); 1274 1275 1281 for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) { 1282 String tag = (String ) e.nextElement(); 1283 glossary.put("request:" + tag, req.getParameter(tag) + ""); 1284 if (tag.equals("search")) { 1285 glossary.put("request:template", searchTemplate); 1286 } 1287 } 1288 1289 String requestTemplate = req.getParameter("template"); 1292 if (requestTemplate != null && !requestTemplate.equals("")) { 1293 requestTemplate = CofaxUtil.replace(requestTemplate, "../", ""); 1294 glossary.put("request:template", requestTemplate); 1295 } 1296 } 1297 1298 1301 private static void printConfiguration() { 1302 System.out.println("--------------- COFAX CONFIGURATION --------------"); 1303 System.out.println("\n\nCofax version: " + COFAX_VERSION + "\n"); 1304 System.out.println("CDSServlet CONFIGURATION:"); 1305 System.out.println("Cache Of Package Tags"); 1306 System.out.println(cacheOfPackageTags.toString()); 1307 System.out.println("\nCache Of Pages"); 1308 System.out.println(cacheOfPages.toString()); 1309 System.out.println("\nCache Of Templates"); 1310 System.out.println(cacheOfTemplates.toString()); 1311 System.out.println("\nTemplate Loader"); 1312 System.out.println(templateLoader.toString()); 1313 System.out.println("\nRedirection"); 1314 System.out.println(cofaxRedirect.toString()); 1315 System.out.println("\nTemplate Processor"); 1316 System.out.println("Instance Of: " + templateProcessorClass); 1317 System.out.println("\nSearch Engine Templates"); 1318 System.out.println("File Template: " + searchEngineFileTemplate); 1319 System.out.println("List Template: " + searchEngineListTemplate); 1320 System.out.println("Search Template: " + searchTemplate); 1321 System.out.println("\nData Store"); 1322 System.out.println(dataStore.toString()); 1323 System.out.println("End CONFIGURATION, begin normal operation\n\n"); 1324 System.out.println("------------------------------"); 1325 1326 } 1327 1328 public static void cofaxLog(String input) { 1330 input = new java.util.Date ().toString() + " - " + input; 1331 try { 1332 PrintWriter fileOutputStream = new PrintWriter (new FileWriter (logLocation, true)); 1333 fileOutputStream.println(input); 1334 fileOutputStream.close(); 1335 1336 } catch (IOException e) { 1337 System.err.println("CofaxCDSLog Error : " + e.toString()); 1338 } 1339 } 1340 1341} 1342 | Popular Tags |