PageRenderTime 40ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/java/src/org/jpublish/SiteContext.java

http://jpublish.googlecode.com/
Java | 1507 lines | 707 code | 242 blank | 558 comment | 118 complexity | 3a570ef0c532ebee2e57fe45d0e035a5 MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. * Copyright 2004-2007 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. package org.jpublish;
  18. import com.anthonyeden.lib.config.Configuration;
  19. import com.anthonyeden.lib.config.ConfigurationException;
  20. import com.anthonyeden.lib.config.XMLConfiguration;
  21. import com.anthonyeden.lib.resource.FileResourceLoader;
  22. import com.anthonyeden.lib.resource.ResourceException;
  23. import com.anthonyeden.lib.resource.ResourceRecipient;
  24. import com.anthonyeden.lib.util.ClassUtilities;
  25. import com.anthonyeden.lib.util.IOUtilities;
  26. import com.atlassian.util.profiling.UtilTimerStack;
  27. import org.apache.commons.logging.Log;
  28. import org.apache.commons.logging.LogFactory;
  29. import org.jpublish.action.ActionManager;
  30. import org.jpublish.repository.RepositoryContent;
  31. import org.jpublish.template.TemplateContent;
  32. import org.jpublish.util.*;
  33. import org.jpublish.view.ViewRenderer;
  34. import javax.servlet.ServletConfig;
  35. import javax.servlet.ServletContext;
  36. import javax.servlet.http.HttpServlet;
  37. import java.io.File;
  38. import java.io.FileInputStream;
  39. import java.io.InputStream;
  40. import java.util.*;
  41. /**
  42. * This class contains configuration information for a particular
  43. * site. Pages are loaded and actions are executed within the
  44. * context of the site and have access to all of the methods within
  45. * this class.
  46. * <p/>
  47. * <p>Instances of the SiteContext class will also reload themselves
  48. * automatically when the underlying configuration file changes.</p>
  49. * <p/>
  50. *
  51. * @author Anthony Eden
  52. * @author <a href="mailto:florin.patrascu@gmail.com">Florin T.PATRASCU</a>
  53. */
  54. public class SiteContext implements ResourceRecipient {
  55. private static final Log log = LogFactory.getLog(SiteContext.class);
  56. public static final Log syslog = LogFactory.getLog("syslog");
  57. public static final String JPUBLISH_VERSION = "4.0";
  58. public static final String NAME = "jpublishSiteContext";
  59. public static final String DEFAULT_PAGE_MANAGER = "org.jpublish.page.filesystem.FileSystemPageManager";
  60. public static final String DEFAULT_TEMPLATE_MANAGER = "org.jpublish.template.filesystem.FileSystemTemplateManager";
  61. public static final String DEFAULT_STATIC_RESOURCE_MANAGER = "org.jpublish.resource.filesystem.FileSystemStaticResourceManager";
  62. public static final String DEFAULT_VIEW_RENDERER = "org.jpublish.view.velocity.VelocityViewRenderer";
  63. public static final String DEFAULT_COMPONENT_MANAGER = "org.jpublish.component.InMemoryComponentManager";
  64. public static final String DEFAULT_PAGE_ROOT = "pages";
  65. public static final String DEFAULT_TEMPLATE_ROOT = "templates";
  66. public static final String DEFAULT_ACTION_ROOT = "actions";
  67. public static final String DEFAULT_STATIC_ROOT = "static";
  68. public static final String DEFAULT_ACTION_IDENTIFIER = "action";
  69. public static final String DEFAULT_PAGE = "index.html";
  70. public static final String DEFAULT_TEMPLATE = "basic";
  71. public static final String DEFAULT_PAGE_SUFFIX = ".xml";
  72. public static final String FILE_SYSTEM_SEPARATOR = System.getProperty("file.separator");
  73. private static final String ATTRIBUTE_CLASSNAME = "classname";
  74. private File configurationFile;
  75. private File root;
  76. private File contextRoot;
  77. private String pageSuffix = DEFAULT_PAGE_SUFFIX;
  78. private File pageRoot;
  79. private File templateRoot;
  80. private File actionRoot;
  81. private File staticRoot;
  82. private File webInfPath;
  83. private ServletContext servletContext;
  84. private String actionIdentifier;
  85. private String defaultPage = DEFAULT_PAGE;
  86. private String defaultTemplate = DEFAULT_TEMPLATE;
  87. private boolean protectReservedNames = false;
  88. private boolean parameterActionsEnabled = false;
  89. private boolean debug = false;
  90. private List modules;
  91. private List repositories;
  92. private List defaultErrorHandlers;
  93. private List disableSessionPaths;
  94. private Map errorHandlerMap;
  95. private Map cachedErrorHandlers;
  96. private PathDispatcherManager pathDispatcherManager;
  97. private JPublishCacheManager jPublishCacheManager;
  98. private PageManager pageManager;
  99. private ActionManager actionManager;
  100. private TemplateManager templateManager;
  101. private StaticResourceManager staticResourceManager;
  102. private ViewRenderer viewRenderer;
  103. private ComponentManager componentManager;
  104. private MimeTypeMap mimeTypeMap;
  105. private CharacterEncodingManager characterEncodingManager;
  106. private String evaluateVelocityTemplates;
  107. private Map attributes;
  108. private ServletConfig servletConfig;
  109. private HttpServlet jPublishServlet;
  110. private static boolean profiling = false;
  111. private String formatChangeParameterName = "";
  112. public static final String DEFAULT_CACHE_NAME = "default";
  113. /**
  114. * Construct a new SiteContext using the given File to load the
  115. * context's configuration.
  116. *
  117. * @param contextRoot Get the application context root
  118. * @param configPath JPublish configuration file path
  119. * @throws Exception an Exception is thrown if anything goes wrong
  120. */
  121. public SiteContext(File contextRoot, String configPath) throws Exception {
  122. String systemProfilingProperty = System.getProperty(UtilTimerStack.ACTIVATE_PROPERTY);
  123. setContextRoot(contextRoot);
  124. File configurationFile = new File(configPath);
  125. if (!configurationFile.isAbsolute()) {
  126. configurationFile = new File(contextRoot, configurationFile.getPath());
  127. }
  128. this.configurationFile = configurationFile;
  129. modules = new ArrayList();
  130. repositories = new ArrayList();
  131. defaultErrorHandlers = new ArrayList();
  132. errorHandlerMap = new HashMap();
  133. cachedErrorHandlers = new HashMap();
  134. mimeTypeMap = new MimeTypeMap();
  135. characterEncodingManager = new CharacterEncodingManager();
  136. disableSessionPaths = new ArrayList();
  137. attributes = new HashMap();
  138. if (systemProfilingProperty != null) {
  139. profiling = systemProfilingProperty.equalsIgnoreCase("true");
  140. }
  141. }
  142. public void init() throws ResourceException {
  143. FileResourceLoader fileResourceLoader = new FileResourceLoader();
  144. fileResourceLoader.loadResource(configurationFile.getAbsolutePath(), this);
  145. }
  146. /**
  147. * Get the configuration File.
  148. *
  149. * @return The configuration File
  150. */
  151. public File getConfigurationFile() {
  152. return configurationFile;
  153. }
  154. public ServletContext getServletContext() {
  155. return servletContext;
  156. }
  157. public void setServletContext(ServletContext servletContext) {
  158. this.servletContext = servletContext;
  159. }
  160. public String getPageSuffix() {
  161. return pageSuffix;
  162. }
  163. public void setPageSuffix(String pageSuffix) {
  164. this.pageSuffix = pageSuffix;
  165. }
  166. /**
  167. * Return the root directory. This directory may be used as
  168. * a base path for all of the other directories required by
  169. * JPublish. If the root is not set then this method will
  170. * return the context root.
  171. *
  172. * @return The root directory
  173. */
  174. public File getRoot() {
  175. if (root == null) {
  176. if (log.isDebugEnabled())
  177. log.debug("Root is null - using context root instead");
  178. return getContextRoot();
  179. }
  180. return root;
  181. }
  182. /**
  183. * Set the root directory.
  184. *
  185. * @param root The new root directory
  186. */
  187. public void setRoot(File root) {
  188. this.root = root;
  189. }
  190. /**
  191. * Set the root directory.
  192. *
  193. * @param root The new root directory
  194. */
  195. public void setRoot(String root) {
  196. if (root != null) {
  197. setRoot(new File(root));
  198. }
  199. }
  200. /**
  201. * Get the context root. The context root is set by the
  202. * JPublishServlet. The value is the root of the web
  203. * application context.
  204. *
  205. * @return The webapp context root
  206. */
  207. public File getContextRoot() {
  208. return contextRoot;
  209. }
  210. /**
  211. * Set the context root.
  212. *
  213. * @param contextRoot The new context root
  214. */
  215. public void setContextRoot(File contextRoot) {
  216. if (log.isDebugEnabled())
  217. log.debug("setContextRoot(" + contextRoot + ")");
  218. this.contextRoot = contextRoot;
  219. }
  220. /**
  221. * Set the context root.
  222. *
  223. * @param contextRoot The new context root
  224. */
  225. public void setContextRoot(String contextRoot) {
  226. if (contextRoot != null) {
  227. setContextRoot(new File(contextRoot));
  228. }
  229. }
  230. /**
  231. * Get the directory where page configuration files are stored. Page
  232. * configurations are stored as XML files and are cached to improve
  233. * performance. The page will automatically be reloaded if it is modified.
  234. *
  235. * @return The page root
  236. */
  237. public File getPageRoot() {
  238. return pageRoot;
  239. }
  240. /**
  241. * Set the directory where page configuration files are stored. Page
  242. * configurations are stored as XML files and are cached to improve
  243. * performance. The page will automatically be reloaded if it is modified.
  244. *
  245. * @param pageRoot The new page root
  246. */
  247. public void setPageRoot(File pageRoot) {
  248. this.pageRoot = pageRoot;
  249. }
  250. /**
  251. * Set the directory where page configuration files are stored. Page
  252. * configurations are stored as XML files and are cached to improve
  253. * performance. The page will automatically be reloaded if it is modified.
  254. *
  255. * @param pageRoot The new page root
  256. */
  257. public void setPageRoot(String pageRoot) {
  258. if (pageRoot != null) {
  259. setPageRoot(new File(pageRoot));
  260. }
  261. }
  262. /**
  263. * If the value of <code>getPageRoot()</code> is an absolute file
  264. * path then that value is returned, otherwise the return value is
  265. * is <code>new File(getRoot(), getPageRoot())</code>.
  266. *
  267. * @return The real page root
  268. */
  269. public File getRealPageRoot() {
  270. File pageRoot = getPageRoot();
  271. if (!pageRoot.isAbsolute()) {
  272. pageRoot = new File(getRoot(), pageRoot.getPath());
  273. }
  274. return pageRoot;
  275. }
  276. /**
  277. * Get the directory where templates are stored. Templates are merged
  278. * with the runtime context to produce a final document.
  279. *
  280. * @return The template root
  281. */
  282. public File getTemplateRoot() {
  283. return templateRoot;
  284. }
  285. /**
  286. * Set the directory where templates are stored. Templates are merged
  287. * with the runtime context to produce a final document.
  288. *
  289. * @param templateRoot The template root
  290. */
  291. public void setTemplateRoot(File templateRoot) {
  292. this.templateRoot = templateRoot;
  293. }
  294. /**
  295. * Set the directory where templates are stored. Templates are merged
  296. * with the runtime context to produce a final document.
  297. *
  298. * @param templateRoot The template root
  299. */
  300. public void setTemplateRoot(String templateRoot) {
  301. if (templateRoot != null) {
  302. setTemplateRoot(new File(templateRoot));
  303. }
  304. }
  305. /**
  306. * If the value of <code>getTemplateRoot()</code> is an absolute file
  307. * path then that value is returned, otherwise the return value is
  308. * is <code>new File(getRoot(), getTemplateRoot())</code>.
  309. *
  310. * @return The real template root
  311. */
  312. public File getRealTemplateRoot() {
  313. File templateRoot = getTemplateRoot();
  314. if (!templateRoot.isAbsolute()) {
  315. templateRoot = new File(getRoot(), templateRoot.getPath());
  316. }
  317. return templateRoot;
  318. }
  319. /**
  320. * Get the directory where action scripts are stored. Actions stored
  321. * here are scripts written in a language supported by the BSF library.
  322. * The language's Java implementation must be included in the classpath.
  323. *
  324. * @return The action root
  325. */
  326. public File getActionRoot() {
  327. return actionRoot;
  328. }
  329. /**
  330. * Set the directory where action scripts are stored. Actions stored
  331. * here are scripts written in a language supported by the BSF library.
  332. * The language's Java implementation must be included in the classpath.
  333. *
  334. * @param actionRoot The new action root
  335. */
  336. public void setActionRoot(File actionRoot) {
  337. this.actionRoot = actionRoot;
  338. }
  339. /**
  340. * Set the directory where action scripts are stored. Actions stored
  341. * here are scripts written in a language supported by the BSF library.
  342. * The language's Java implementation must be included in the classpath.
  343. *
  344. * @param actionRoot The new action root
  345. */
  346. public void setActionRoot(String actionRoot) {
  347. if (actionRoot != null) {
  348. setActionRoot(new File(actionRoot));
  349. }
  350. }
  351. /**
  352. * If the value of <code>getActionRoot()</code> is an absolute file
  353. * path then that value is returned, otherwise the return value is
  354. * is <code>new File(getRoot(), getActionRoot())</code>.
  355. *
  356. * @return The real action root
  357. */
  358. public File getRealActionRoot() {
  359. File actionRoot = getActionRoot();
  360. if (!actionRoot.isAbsolute()) {
  361. actionRoot = new File(getRoot(), actionRoot.getPath());
  362. }
  363. return actionRoot;
  364. }
  365. /**
  366. * Get the directory where static files are stored. Static files are
  367. * files which are not processed by JPublish but are returned byte for
  368. * byte.
  369. *
  370. * @return The root directory where static files are stored
  371. */
  372. public File getStaticRoot() {
  373. return staticRoot;
  374. }
  375. /**
  376. * Set the directory where static files are stored. Static files are
  377. * files which are not processed by JPublish but are returned byte for
  378. * byte.
  379. *
  380. * @param staticRoot The new root directory where static files are stored
  381. */
  382. public void setStaticRoot(File staticRoot) {
  383. this.staticRoot = staticRoot;
  384. }
  385. /**
  386. * Set the directory where static files are stored. Static files are
  387. * files which are not processed by JPublish but are returned byte for
  388. * byte.
  389. *
  390. * @param staticRoot The path of the new root directory where static
  391. * files are stored
  392. */
  393. public void setStaticRoot(String staticRoot) {
  394. if (staticRoot != null) {
  395. setStaticRoot(new File(staticRoot));
  396. }
  397. }
  398. /**
  399. * If the value of <code>getStaticRoot()</code> is an absolute file
  400. * path then that value is returned, otherwise the return value is
  401. * is <code>new File(getRoot(), getStaticRoot())</code>.
  402. *
  403. * @return The real static root
  404. */
  405. public File getRealStaticRoot() {
  406. File staticRoot = getStaticRoot();
  407. if (!staticRoot.isAbsolute()) {
  408. staticRoot = new File(getRoot(), staticRoot.getPath());
  409. }
  410. return staticRoot;
  411. }
  412. /**
  413. * Get the File for the WEB-INF directory. This is used to locate the
  414. * classes and JARs so they are accessible to scripting languages.
  415. *
  416. * @return The WEB-INF file
  417. */
  418. public File getWebInfPath() {
  419. return webInfPath;
  420. }
  421. /**
  422. * Set the File for the WEB-INF directory.
  423. *
  424. * @param webInfPath The WEB-INF file
  425. */
  426. public void setWebInfPath(File webInfPath) {
  427. this.webInfPath = webInfPath;
  428. }
  429. /**
  430. * Get the action identifier which is used to trigger parameter actions.
  431. * The default value is 'action'.
  432. *
  433. * @return The action identifier
  434. */
  435. public String getActionIdentifier() {
  436. return actionIdentifier;
  437. }
  438. /**
  439. * Set the action identifier. If this method is invoked with a null
  440. * argument then the action identifier will be reset to the default
  441. * value.
  442. *
  443. * @param actionIdentifier The new action identifer or null to reset
  444. */
  445. public synchronized void setActionIdentifier(String actionIdentifier) {
  446. if (actionIdentifier == null) {
  447. this.actionIdentifier = DEFAULT_ACTION_IDENTIFIER;
  448. } else {
  449. this.actionIdentifier = actionIdentifier;
  450. }
  451. }
  452. /**
  453. * Return true if parameter actions are enabled.
  454. *
  455. * @return True if parameter actions are enabled
  456. * @since 1.4.1
  457. */
  458. public boolean isParameterActionsEnabled() {
  459. return parameterActionsEnabled;
  460. }
  461. /**
  462. * Set to true to enable parameter actions. Parameter actions are disabled
  463. * by default because of the inherent security risks involved in using
  464. * them.
  465. *
  466. * @param parameterActionsEnabled True to enabled parameter actions
  467. * @since 1.4.1
  468. */
  469. public void setParameterActionsEnabled(boolean parameterActionsEnabled) {
  470. this.parameterActionsEnabled = parameterActionsEnabled;
  471. }
  472. /**
  473. * Set to true to enable parameter actions. Parameter actions are disabled
  474. * by default because of the inherent security risks involved in using
  475. * them.
  476. *
  477. * @param parameterActionsEnabled True to enabled parameter actions
  478. * @since 1.4.1
  479. */
  480. public void setParameterActionsEnabled(String parameterActionsEnabled) {
  481. setParameterActionsEnabled("true".equals(parameterActionsEnabled));
  482. }
  483. /**
  484. * Get the default page. This value will be used when directories
  485. * are requested. By default this returns 'index.html'.
  486. *
  487. * @return The default page
  488. */
  489. public String getDefaultPage() {
  490. return defaultPage;
  491. }
  492. /**
  493. * Set the default page. This value will be used when directories
  494. * are requested.
  495. *
  496. * @param defaultPage The new default page
  497. */
  498. public void setDefaultPage(String defaultPage) {
  499. this.defaultPage = defaultPage;
  500. }
  501. /**
  502. * Get the default template. This method returns the name of the
  503. * template which will be used when no template is specified in
  504. * a page's configuration.
  505. *
  506. * @return The default template
  507. */
  508. public String getDefaultTemplate() {
  509. return defaultTemplate;
  510. }
  511. /**
  512. * Set the default template. The default template will be used when
  513. * no template is specified in a page's configuration.
  514. *
  515. * @param defaultTemplate The new default template
  516. */
  517. public void setDefaultTemplate(String defaultTemplate) {
  518. this.defaultTemplate = defaultTemplate;
  519. }
  520. /**
  521. * Get the default mime type. This method delegates to the current
  522. * MimeTypeMap.
  523. *
  524. * @return The default mime type
  525. */
  526. public String getDefaultMimeType() {
  527. return getMimeTypeMap().getDefaultMimeType();
  528. }
  529. /**
  530. * Set the default mime type. This method delegates to the current
  531. * MimeTypeMap.
  532. *
  533. * @param defaultMimeType The new default mime type
  534. */
  535. public void setDefaultMimeType(String defaultMimeType) {
  536. getMimeTypeMap().setDefaultMimeType(defaultMimeType);
  537. }
  538. /**
  539. * Returns true if reserved names should be protected in the
  540. * JPublishContext. This method returns false by default.
  541. *
  542. * @return True if reserved names should be protected
  543. */
  544. public boolean isProtectReservedNames() {
  545. return protectReservedNames;
  546. }
  547. /**
  548. * Set to true to protect reserved names in the JPublishContext.
  549. *
  550. * @param protectReservedNames True to protect reserved names
  551. */
  552. public void setProtectReservedNames(boolean protectReservedNames) {
  553. if (protectReservedNames)
  554. log.info("Protect reserved names enabled");
  555. this.protectReservedNames = protectReservedNames;
  556. }
  557. /**
  558. * Set to "true" to protect reserved names in the JPublishContext.
  559. *
  560. * @param protectReservedNames "true" to protect reserved names
  561. */
  562. public void setProtectReservedNames(String protectReservedNames) {
  563. setProtectReservedNames("true".equals(protectReservedNames));
  564. }
  565. /**
  566. * Return true if debugging is enabled.
  567. *
  568. * @return True if debugging is enabled
  569. */
  570. public boolean isDebug() {
  571. return debug;
  572. }
  573. /**
  574. * Set to true to enable debugging.
  575. *
  576. * @param debug True to enable debugging
  577. */
  578. public void setDebug(boolean debug) {
  579. if (debug)
  580. log.info("JPublish debugging enabled.");
  581. this.debug = debug;
  582. }
  583. /**
  584. * Set to "true" to enable debugging.
  585. *
  586. * @param debug "true" to enable debugging
  587. */
  588. public void setDebug(String debug) {
  589. setDebug("true".equals(debug));
  590. }
  591. /**
  592. * Return a list of paths where the session object should NOT be
  593. * created.
  594. *
  595. * @return A List of paths where sessions should not be created
  596. */
  597. public List getDisableSessionPaths() {
  598. return disableSessionPaths;
  599. }
  600. /**
  601. * Get a List of all loaded modules.
  602. *
  603. * @return List of loaded modules
  604. */
  605. public List getModules() {
  606. return modules;
  607. }
  608. /**
  609. * Get a list of all registered repositories.
  610. *
  611. * @return A list of all registered Repository objects
  612. */
  613. public List getRepositories() {
  614. return repositories;
  615. }
  616. /**
  617. * Get a List of all error handlers for the given path. The path can
  618. * include the '*' wildcard. If there are no error handlers for the
  619. * given path then this method will return the default handlers. If
  620. * you do not want any handlers then define a error handler mapping
  621. * with no defined error handlers.
  622. *
  623. * @param path The path
  624. * @return A List of error handlers
  625. */
  626. public List getErrorHandlers(String path) {
  627. List errorHandlers = (List) cachedErrorHandlers.get(path);
  628. if (errorHandlers == null) {
  629. Iterator keys = errorHandlerMap.keySet().iterator();
  630. while (keys.hasNext()) {
  631. String key = (String) keys.next();
  632. if (PathUtilities.match(path, key)) {
  633. errorHandlers = (List) errorHandlerMap.get(key);
  634. cachedErrorHandlers.put(path, errorHandlers);
  635. return errorHandlers;
  636. }
  637. }
  638. return getDefaultErrorHandlers();
  639. } else {
  640. return errorHandlers;
  641. }
  642. }
  643. /**
  644. * Get the List of default error handlers. These error handlers should
  645. * be used whenever no error handlers are defined.
  646. *
  647. * @return The default error handlers
  648. */
  649. public List getDefaultErrorHandlers() {
  650. return defaultErrorHandlers;
  651. }
  652. /**
  653. * Get a Repository by name. If the repository was not registered
  654. * then this method will return null.
  655. *
  656. * @param name The name of the Repository
  657. * @return The repository or null
  658. */
  659. public Repository getRepository(String name) {
  660. Iterator iter = getRepositories().iterator();
  661. while (iter.hasNext()) {
  662. Repository repository = (Repository) iter.next();
  663. if (repository.getName().equals(name)) {
  664. return repository;
  665. }
  666. }
  667. return null;
  668. }
  669. /**
  670. * Get the site's ActionManager.
  671. *
  672. * @return The ActionManager
  673. * @see org.jpublish.action.ActionManager
  674. */
  675. public ActionManager getActionManager() {
  676. return actionManager;
  677. }
  678. /**
  679. * Get the site's PageManager.
  680. *
  681. * @return The PageManager
  682. * @see PageManager
  683. */
  684. public PageManager getPageManager() {
  685. return pageManager;
  686. }
  687. /**
  688. * Get the site's TemplateManager.
  689. *
  690. * @return The TemplateManager
  691. * @see TemplateManager
  692. */
  693. public TemplateManager getTemplateManager() {
  694. return templateManager;
  695. }
  696. /**
  697. * Get the site's StaticResourceManager.
  698. *
  699. * @return The StaticResourceManager
  700. * @see StaticResourceManager
  701. */
  702. public StaticResourceManager getStaticResourceManager() {
  703. return staticResourceManager;
  704. }
  705. /**
  706. * Get the site's ViewRenderer which is used to render content.
  707. *
  708. * @return The ViewRenderer
  709. */
  710. public ViewRenderer getViewRenderer() {
  711. return viewRenderer;
  712. }
  713. /**
  714. * Get the site's ComponentManager.
  715. *
  716. * @return The ComponentManager
  717. * @since 2.0
  718. */
  719. public ComponentManager getComponentManager() {
  720. return componentManager;
  721. }
  722. /**
  723. * Get the site's MimeType map. Mime types can be mapped to file
  724. * suffixes.
  725. *
  726. * @return The MimeTypeMap
  727. */
  728. public MimeTypeMap getMimeTypeMap() {
  729. return mimeTypeMap;
  730. }
  731. /**
  732. * Return the CharacterEncodingManager.
  733. *
  734. * @return The CharacterEncodingManager
  735. */
  736. public CharacterEncodingManager getCharacterEncodingManager() {
  737. return characterEncodingManager;
  738. }
  739. /**
  740. * Retrieve a Content object for the specified named content. The content
  741. * name must include the origin prefix. In the case of content pulled from
  742. * a repository this would be:
  743. * <p/>
  744. * <blockquote>
  745. * <code>repository:repository_name://path/to/content</code>
  746. * </blockquote>
  747. * <p/>
  748. * <p>In the case of templates, this would be:</p>
  749. * <p/>
  750. * <blockquote>
  751. * <code>template:/path/to/template</code>
  752. * </blockquote>
  753. * <p/>
  754. * <p>Ultimately there should be a common repository system for all content
  755. * whether it be text content, templates, binary content, etc.</p>
  756. * <p/>
  757. * <p>This method must return null if the named content can not be
  758. * found.</p>
  759. *
  760. * @param name The content name
  761. * @return The Content object
  762. */
  763. public Content getContent(String name) {
  764. String path;
  765. try {
  766. if (log.isDebugEnabled())
  767. log.debug("getContent(" + name + ")");
  768. InternalURI uri = InternalURIParser.getInstance().parse(name);
  769. String protocol = uri.getProtocol();
  770. if (protocol.equalsIgnoreCase("template")) {
  771. path = uri.getPath();
  772. if (log.isDebugEnabled())
  773. log.debug("Looking for template: " + path);
  774. return new TemplateContent(templateManager.getTemplate(path));
  775. } else if (protocol.equalsIgnoreCase("repository")) {
  776. String repositoryName = ((RepositoryURI) uri).getRepositoryName();
  777. Repository r = getRepository(repositoryName);
  778. path = uri.getPath();
  779. if (log.isDebugEnabled())
  780. log.debug("Looking for content: " + path);
  781. if (r == null) {
  782. throw new Exception(
  783. "Repository for " + repositoryName + " is null. Cannot get content for: " + path);
  784. }
  785. return new RepositoryContent(r.get(path), r.getLastModified(path));
  786. } else {
  787. throw new Exception("Protocol " + protocol + " not supported");
  788. }
  789. } catch (Throwable t) {
  790. // this is necessary to support FreeMarker for the moment.
  791. // FreeMarker adds localized parts to the file path and thus
  792. // the file will not be found on the first try, but FreeMarker
  793. // requires that this method return null, so voila! When they
  794. // fix the setLocalizedLookup() method so false works I will
  795. // probably remove this.
  796. log.error("Error getting content: " + t.getMessage(), t);
  797. t.printStackTrace();
  798. return null;
  799. }
  800. }
  801. public long getLastModified(String name) throws Exception {
  802. InternalURI uri = InternalURIParser.getInstance().parse(name);
  803. String protocol = uri.getProtocol();
  804. String path = uri.getPath();
  805. long lastModified = 0;
  806. if (protocol.equalsIgnoreCase("template")) {
  807. lastModified = templateManager.getTemplate(path).getLastModified();
  808. } else if (protocol.equalsIgnoreCase("repository")) {
  809. String repositoryName = ((RepositoryURI) uri).getRepositoryName();
  810. Repository r = getRepository(repositoryName);
  811. lastModified = r.getLastModified(path);
  812. }
  813. return lastModified;
  814. }
  815. // Start Attribute support
  816. /**
  817. * Get the named site attribute. Returns null if there is no
  818. * site attribute for the specified name.
  819. *
  820. * @param name The attribute name
  821. * @return The site attribute or null
  822. */
  823. public Object getAttribute(String name) {
  824. return attributes.get(name);
  825. }
  826. /**
  827. * Set the named site attribute.
  828. *
  829. * @param name The site attribute name
  830. * @param value The site attribute value
  831. */
  832. public void setAttribute(String name, Object value) {
  833. attributes.put(name, value);
  834. }
  835. /**
  836. * Remove the named site attribute.
  837. *
  838. * @param name The site attribute name
  839. */
  840. public void removeAttribute(String name) {
  841. attributes.remove(name);
  842. }
  843. /**
  844. * Get an Iterator of all names for site attributes.
  845. *
  846. * @return Iterator of attribute names
  847. */
  848. public Iterator getAttributeNames() {
  849. return attributes.keySet().iterator();
  850. }
  851. // End Attribute support
  852. /**
  853. * Reload the site configuration.
  854. */
  855. public void reload() {
  856. try {
  857. log.info("Loading site configuration.");
  858. loadConfiguration();
  859. log.info("Configuration loaded.");
  860. } catch (Exception e) {
  861. e.printStackTrace();
  862. }
  863. }
  864. /**
  865. * Load the site configuration from the given InputStream. The
  866. * InputStream must be attached to an XML document.
  867. *
  868. * @param in The InputStream
  869. * @throws Exception
  870. */
  871. public void load(InputStream in) throws Exception {
  872. if (log.isDebugEnabled())
  873. log.debug("Loading configuration");
  874. // construct the Configuration object from the stream
  875. Configuration configuration = new XMLConfiguration(in);
  876. // construct the ActionManager
  877. actionManager = new ActionManager(this);
  878. // setup the ActionManager
  879. Configuration actionManagerConfiguration = configuration.getChild("action-manager");
  880. if (actionManagerConfiguration != null) {
  881. List classPathElements = actionManager.getClassPathElements();
  882. Configuration classpathConfiguration = actionManagerConfiguration.getChild("classpath");
  883. Iterator pathElements = classpathConfiguration.getChildren("pathelement").iterator();
  884. while (pathElements.hasNext()) {
  885. Configuration pathElement = (Configuration) pathElements.next();
  886. classPathElements.add(pathElement.getValue());
  887. }
  888. }
  889. // setup alien dispatcher
  890. // load path actions
  891. pathDispatcherManager = new PathDispatcherManager(this);
  892. Configuration pathDispatcherManagerConfiguration = configuration.getChild("path-dispatcher");
  893. if (pathDispatcherManagerConfiguration != null) {
  894. if (log.isDebugEnabled()) {
  895. log.debug("loading path-dispatcher elements");
  896. }
  897. pathDispatcherManager.loadConfiguration(configuration);
  898. }
  899. /**
  900. * Create a default Cache manager
  901. *
  902. */
  903. jPublishCacheManager = new JPublishCacheManager(this);
  904. Configuration cacheManagerConfiguration = configuration.getChild("cache-manager");
  905. if (cacheManagerConfiguration != null) {
  906. if (log.isDebugEnabled()) {
  907. log.debug("loading cache-manager elements");
  908. }
  909. jPublishCacheManager.loadConfiguration(configuration);
  910. }
  911. // load the PageManager
  912. log.debug("Creating PageManager");
  913. Configuration pageManagerConfiguration = configuration.getChild("page-manager");
  914. if (pageManagerConfiguration != null) {
  915. String pageManagerClass = pageManagerConfiguration.getAttribute(ATTRIBUTE_CLASSNAME);
  916. if (pageManagerClass == null) {
  917. // handle using page-manager value as class name
  918. pageManagerClass = pageManagerConfiguration.getValue();
  919. log.warn("The page-manager class should now be specified " +
  920. "using the classname attribute");
  921. }
  922. pageManager = (PageManager) ClassUtilities.loadClass(pageManagerClass).newInstance();
  923. pageManager.setSiteContext(this);
  924. pageManager.loadConfiguration(pageManagerConfiguration);
  925. } else {
  926. pageManager = (PageManager) ClassUtilities.loadClass(DEFAULT_PAGE_MANAGER).newInstance();
  927. pageManager.setSiteContext(this);
  928. }
  929. // load the TemplateManager
  930. if (log.isDebugEnabled())
  931. log.debug("Creating TemplateManager");
  932. Configuration templateManagerConfiguration = configuration.getChild("template-manager");
  933. if (templateManagerConfiguration != null) {
  934. String templateManagerClass = templateManagerConfiguration.getAttribute(ATTRIBUTE_CLASSNAME);
  935. if (templateManagerClass == null) {
  936. // handle using element value as class name
  937. templateManagerClass = templateManagerConfiguration.getValue();
  938. log.warn("The template-manager class should now be specified " +
  939. "using the classname attribute");
  940. }
  941. templateManager = (TemplateManager) ClassUtilities.loadClass(templateManagerClass).newInstance();
  942. templateManager.setSiteContext(this);
  943. templateManager.loadConfiguration(templateManagerConfiguration);
  944. } else {
  945. templateManager = (TemplateManager) ClassUtilities.loadClass(DEFAULT_TEMPLATE_MANAGER).newInstance();
  946. templateManager.setSiteContext(this);
  947. }
  948. if (jPublishCacheManager.getCache(DEFAULT_CACHE_NAME) != null) {
  949. templateManager.setCache(jPublishCacheManager.getCache(DEFAULT_CACHE_NAME));
  950. } else {
  951. // no default cache enabled, will use the first cache available
  952. String[] cacheNames = jPublishCacheManager.getAvailableCacheNames();
  953. if (cacheNames != null && cacheNames.length > 0) {
  954. String cacheName = cacheNames[0];
  955. JPublishCache templateCache = jPublishCacheManager.getCache(cacheName);
  956. if (templateCache != null) {
  957. templateManager.setCache(templateCache);
  958. log.info(String.format("The JPublish Template Manager is using the: %s cache.", cacheName));
  959. }
  960. } else {
  961. log.warn("Template caching is disabled. Please define a cache manager in the jpublish.xml file");
  962. }
  963. }
  964. // load the StaticResourceManager
  965. log.debug("Creating StaticResourceManager");
  966. Configuration staticResourceManagerConfiguration = configuration.getChild("static-resource-manager");
  967. if (staticResourceManagerConfiguration != null) {
  968. String staticResourceManagerClass = staticResourceManagerConfiguration.getAttribute(ATTRIBUTE_CLASSNAME);
  969. if (staticResourceManagerClass == null) {
  970. // handle using element value as class name
  971. staticResourceManagerClass = staticResourceManagerConfiguration.getValue();
  972. log.warn("The static-resource-manager class should be " +
  973. "specified using the classname attribute");
  974. }
  975. staticResourceManager = (StaticResourceManager) ClassUtilities.loadClass(staticResourceManagerClass).newInstance();
  976. staticResourceManager.setSiteContext(this);
  977. staticResourceManager.loadConfiguration(staticResourceManagerConfiguration);
  978. } else {
  979. staticResourceManager =
  980. (StaticResourceManager) ClassUtilities.loadClass(
  981. DEFAULT_STATIC_RESOURCE_MANAGER).newInstance();
  982. staticResourceManager.setSiteContext(this);
  983. }
  984. // load the ViewRenderer
  985. if (log.isDebugEnabled())
  986. log.debug("Creating ViewRenderer");
  987. Configuration viewRendererConfiguration = configuration.getChild("view-renderer");
  988. if (viewRendererConfiguration != null) {
  989. String viewRendererClass = viewRendererConfiguration.getAttribute(ATTRIBUTE_CLASSNAME);
  990. if (viewRendererClass == null) {
  991. // handle using element value as class name
  992. viewRendererClass = viewRendererConfiguration.getValue();
  993. log.warn("The view-renderer class should be " +
  994. "specified using the classname attribute");
  995. }
  996. viewRenderer = (ViewRenderer) ClassUtilities.loadClass(viewRendererClass).newInstance();
  997. viewRenderer.setSiteContext(this);
  998. viewRenderer.loadConfiguration(viewRendererConfiguration);
  999. } else {
  1000. viewRenderer = (ViewRenderer) ClassUtilities.loadClass(DEFAULT_VIEW_RENDERER).newInstance();
  1001. viewRenderer.setSiteContext(this);
  1002. }
  1003. if (log.isDebugEnabled())
  1004. log.debug("View renderer: " + viewRenderer.getClass());
  1005. viewRenderer.init();
  1006. // load modules
  1007. Iterator moduleElements = configuration.getChildren("module").iterator();
  1008. while (moduleElements.hasNext()) {
  1009. Configuration moduleElement = (Configuration) moduleElements.next();
  1010. String className = moduleElement.getAttribute(ATTRIBUTE_CLASSNAME);
  1011. try {
  1012. JPublishModule module = (JPublishModule) ClassUtilities.loadClass(className).newInstance();
  1013. module.init(this, moduleElement);
  1014. modules.add(module);
  1015. } catch (Exception e) {
  1016. log.error("Unable to load module " + className);
  1017. e.printStackTrace();
  1018. }
  1019. }
  1020. // load repository references
  1021. Iterator repositoryElements = configuration.getChildren("repository").iterator();
  1022. while (repositoryElements.hasNext()) {
  1023. Configuration repositoryElement = (Configuration) repositoryElements.next();
  1024. String className = repositoryElement.getAttribute(ATTRIBUTE_CLASSNAME);
  1025. Repository repository = (Repository) ClassUtilities.loadClass(className).newInstance();
  1026. repository.setSiteContext(this);
  1027. repository.loadConfiguration(repositoryElement);
  1028. getRepositories().add(repository);
  1029. }
  1030. // load the ComponentManager
  1031. if (log.isDebugEnabled())
  1032. log.debug("Creating ComponentManager");
  1033. Configuration componentManagerConfiguration = configuration.getChild("component-manager");
  1034. String componentManagerClass = null;
  1035. if (componentManagerConfiguration != null) {
  1036. componentManagerClass = componentManagerConfiguration.getAttribute(ATTRIBUTE_CLASSNAME);
  1037. }
  1038. if (componentManagerClass == null) {
  1039. componentManagerClass = DEFAULT_COMPONENT_MANAGER;
  1040. }
  1041. if (log.isDebugEnabled())
  1042. log.debug("Component manager class: " + componentManagerClass);
  1043. componentManager = (ComponentManager) ClassUtilities.loadClass(componentManagerClass).newInstance();
  1044. componentManager.setSiteContext(this);
  1045. if (componentManagerConfiguration != null) {
  1046. componentManager.loadConfiguration(componentManagerConfiguration);
  1047. }
  1048. // Configure root paths
  1049. setRoot(configuration.getChildValue("root"));
  1050. // eventually these should be moved into the configuration
  1051. // methods for the actual managers since having roots only
  1052. // makes sense there
  1053. setPageRoot(configuration.getChildValue("page-root", DEFAULT_PAGE_ROOT));
  1054. setTemplateRoot(configuration.getChildValue("template-root", DEFAULT_TEMPLATE_ROOT));
  1055. setActionRoot(configuration.getChildValue("action-root", DEFAULT_ACTION_ROOT));
  1056. setStaticRoot(configuration.getChildValue("static-root", DEFAULT_STATIC_ROOT));
  1057. setActionIdentifier(configuration.getChildValue("action-identifier"));
  1058. // Set defaults
  1059. setDefaultPage(configuration.getChildValue("default-page", DEFAULT_PAGE));
  1060. setDefaultTemplate(configuration.getChildValue("default-template", DEFAULT_TEMPLATE));
  1061. setDefaultMimeType(configuration.getChildValue("default-mime-type"));
  1062. // configuration JNDI settings
  1063. if (log.isDebugEnabled())
  1064. log.debug("Configuring JNDI");
  1065. configureJNDI(configuration.getChild("jndi"));
  1066. // protect reserved names in the context
  1067. setProtectReservedNames(configuration.getChildValue("protect-reserved-names", "false"));
  1068. // enable or disable parameter actions
  1069. setParameterActionsEnabled(configuration.getChildValue("parameter-actions-enabled", "false"));
  1070. // enable or disable debugging
  1071. setDebug(configuration.getChildValue("debug", "false"));
  1072. // enable or disable the support for the 'format' request parameter
  1073. setFormatChangeParameterName(configuration.getChildValue("formatChangeParameterName", ""));
  1074. // enable or disable profiling
  1075. String minTime = "0";
  1076. setProfiling(configuration.getChildValue("profiling", "false"));
  1077. UtilTimerStack.setActive(getProfiling());
  1078. if (getProfiling()) {
  1079. // check to see if the user establishe a minimum execution threshold
  1080. minTime = configuration.getChild("profiling").getAttribute("MIN_TIME", "0");
  1081. System.setProperty(UtilTimerStack.MIN_TIME, minTime);
  1082. }
  1083. log.info("JPublish profiling is: " + (getProfiling() ? "On" : "Off") +
  1084. "; minimum time reported: >=" + minTime + "ms");
  1085. // enable or disable debugging
  1086. setEval(configuration.getChildValue("evaluateVelocityTemplates", "false"));
  1087. // load character encoding maps
  1088. if (log.isDebugEnabled())
  1089. log.debug("Loading CharacterEncodingMaps");
  1090. characterEncodingManager.loadConfiguration(configuration);
  1091. // load all actions
  1092. actionManager.loadConfiguration(configuration);
  1093. // load the mime type map
  1094. Iterator mimeTypeMapElements = configuration.getChildren("mime-mapping").iterator();
  1095. while (mimeTypeMapElements.hasNext()) {
  1096. Configuration mimeTypeMapElement = (Configuration) mimeTypeMapElements.next();
  1097. String ext = mimeTypeMapElement.getAttribute("ext");
  1098. String mimeType = mimeTypeMapElement.getAttribute("mimetype");
  1099. mimeTypeMap.put(ext, mimeType);
  1100. }
  1101. // load default error handlers
  1102. Configuration defaultErrorHandlersElement = configuration.getChild("default-error-handlers");
  1103. if (defaultErrorHandlersElement != null) {
  1104. Iterator defaultErrorHandlerElements = defaultErrorHandlersElement.getChildren("error-handler").iterator();
  1105. while (defaultErrorHandlerElements.hasNext()) {
  1106. Configuration defaultErrorHandlerElement = (Configuration) defaultErrorHandlerElements.next();
  1107. String className = defaultErrorHandlerElement.getAttribute("class");
  1108. defaultErrorHandlers.add(ClassUtilities.loadClass(className).newInstance());
  1109. }
  1110. }
  1111. // load error handlers
  1112. Iterator errorHandlerMapElements = configuration.getChildren("error-handler-map").iterator();
  1113. while (errorHandlerMapElements.hasNext()) {
  1114. Configuration errorHandlerMapElement = (Configuration) errorHandlerMapElements.next();
  1115. String path = errorHandlerMapElement.getAttribute("path");
  1116. if (path == null) {
  1117. throw new ConfigurationException("Error handler path must be defined");
  1118. }
  1119. Iterator errorHandlerElements = errorHandlerMapElement.getChildren("error-handler").iterator();
  1120. while (errorHandlerElements.hasNext()) {
  1121. Configuration errorHandlerElement = (Configuration) errorHandlerElements.next();
  1122. String errorHandlerClass = errorHandlerElement.getAttribute("class");
  1123. List errorHandlers = (List) errorHandlerMap.get(path);
  1124. if (errorHandlers == null) {
  1125. errorHandlers = new ArrayList();
  1126. errorHandlerMap.put(path, errorHandlers);
  1127. }
  1128. errorHandlers.add(ClassUtilities.loadClass(errorHandlerClass).newInstance());
  1129. }
  1130. }
  1131. // load session disable paths
  1132. Iterator disableSessionElements = configuration.getChildren("disable-session").iterator();
  1133. while (disableSessionElements.hasNext()) {
  1134. Configuration disableSessionElement = (Configuration) disableSessionElements.next();
  1135. String path = disableSessionElement.getAttribute("path");
  1136. disableSessionPaths.add(path);
  1137. }
  1138. /*
  1139. // add Spring to JPublish if the applicationContext is defined
  1140. log.info("Checking for JPublish-Spring support ...");
  1141. Configuration springSupportConfig = configuration.getChild("spring-support");
  1142. if (springSupportConfig != null) {
  1143. log.info("Loading Spring support ...");
  1144. String springConfigPath = springSupportConfig.getChildValue("config-path", "WEB-INF/applicationContext.xml");
  1145. String rootDir = contextRoot.getAbsolutePath();
  1146. springConfigPath = rootDir + FILE_SYSTEM_SEPARATOR + springConfigPath;
  1147. try {
  1148. ApplicationContext appContext = new FileSystemXmlApplicationContext("file:" + springConfigPath);
  1149. this.setAttribute(SiteContext.SPRING, appContext);
  1150. //messageSource = (MessageSource) appContext.getBean("messageSource");
  1151. //String[] localizationBaseNames = getLocalizationBaseNames(springSupportConfig);
  1152. //log.info("Localization properties definitions: ");
  1153. //for (int i = 0; i < localizationBaseNames.length; i++) {
  1154. // localizationBaseNames[i] = "file:" + rootDir + "/" +localizationBaseNames[i];
  1155. // log.info(" > "+localizationBaseNames[i]);
  1156. //}
  1157. //messageSource.setBasenames( localizationBaseNames);
  1158. } catch (BeansException e) {
  1159. e.printStackTrace();
  1160. }
  1161. } else {
  1162. log.info("Spring support not required ...");
  1163. }
  1164. */
  1165. }
  1166. /**
  1167. * enable or disable the profiling mode
  1168. *
  1169. * @param value a String containing "true" or anything else for false
  1170. */
  1171. public static void setProfiling(String value) {
  1172. if (value != null) {
  1173. profiling = value.trim().equalsIgnoreCase("true");
  1174. }
  1175. }
  1176. /**
  1177. * @return the boolean value of the profiling mode
  1178. */
  1179. public static boolean getProfiling() {
  1180. return profiling;
  1181. }
  1182. private void setEval(String evaluateVelocityTemplates) {
  1183. this.evaluateVelocityTemplates = evaluateVelocityTemplates;
  1184. }
  1185. // private methods
  1186. /**
  1187. * Configure the initial JNDI context properties. If the element is null
  1188. * then the property values will not be modified.
  1189. *
  1190. * @throws Exception
  1191. */
  1192. private void configureJNDI(Configuration configuration) throws Exception {
  1193. if (configuration != null) {
  1194. System.setProperty("java.naming.factory.initial", configuration.getChildValue("initial-factory"));
  1195. System.setProperty("java.naming.provider.url", configuration.getChildValue("provider"));
  1196. }
  1197. }
  1198. /*…

Large files files are truncated, but you can click here to view the full file