Dave Ward 10da961097 Merged V3.3-BUG-FIX to HEAD
21981: Fixed ALF-2390: ContentService needs to return total/available space values where possible
      - Added ContentService getStoreTotalSpace and getStoreFreeSpace
      - Supported by underlying ContentStore methods
         - getSpaceUsed: Actual binary storage size (was getTotalSize, which is not deprecated)
         - getSpaceTotal: Total storage space on partition
         - getSpaceAvailable: Remaining storage space on partition
      - Added JMX methods
      - Note: getSpaceUsed is NOT exposed as a service method as it is too easy to abuse
   21982: Follow-up to Fixed ALF-2390: Patch uses new 'getSizeUsed' instead of deprecated 'getTotalSize'
   21983: Fixed ALF-766: Allow cache peer URLs to be set in ehcache-custom.xml
      - Was investigating settings required for client, so just added this in
      - By default, the 'cacheManagerPeerListenerFactory' uses no system properties, but
        a comment has been added on how to define hostName, port and socketTimeoutMillis.
      - Variables associated with that have been added to repository.properties and are
        exported to the Java system properties environment for EHCache to pick up.
   21984: More ALF-766: Allow cache peer URLs to be set in ehcache-custom.xml
      - Added alfresco.ehcache.rmi.remoteObjectPort (see ALF-765)
   22011: Fix for ALF-3005 - Blog and Discussion components not correctly checking length of modified HTML content
   22074: Fix for ALF-4447 - Failure when publishing a Post - some reverse proxies changing the response header to lower case
   22075: (RECORD ONLY) Merged HEAD to BRANCHES/DEV/V3.3-BUG-FIX:
      22073: Resolve ALF-4522: Accessing document via /alfresco/service/api/path doesn't work - "Company Home" token is duplicated
   22091: Merged PATCHES/V2.2.7 to V3.3-BUG-FIX (RECORD ONLY)
      19832: Merged BRANCHES/V3.1 to PATCHES/V2.2.7:
         17255: Fixed ETHREEOH-3180: Error appears when trying to search resources on Manage Task page
      19778: Incremented version label
      19769: ALF-2011: Backported dependencies
         ALF-2360: Merged V3.1 to PATCHES/V2.2.7
            17314: ETHREEOH-3158: Fix RepoServerMgmt to work with external authentication methods
               - AuthenticationService.getCurrentTicket / getNewTicket now call pre authentication check before issuing a new ticket, thus still allowing ticket enforcement when external authentication is in use.
         ALF-2361: Merged V3.2 to PATCHES/V2.2.7
            17456: Fix for: ETHREEOH-1465: It's impossible to get the login history for a given user (Audit)
               - all authentication routes (SSO and password) can now audit getting a new ticket for a session. SSO does not authenticate via the alfresco AuthenticationService API
               - you can now use auditing to track new sessions for users.
      19558: Created hotfix branch off TAGS/ENTERPRISE/V2.2.7
      19557: Tagged V2.2 build 533 Revision 19303 as TAGS/ENTERPRISE/V2.2.7
   22092: Merged PATCHES/V3.1.0 to V3.3-BUG-FIX (RECORD ONLY)
      21274: Merged PATCHES/V3.1.2 to PATCHES/V3.1.0
         21264: ALF-3889: JBPMDeployProcessServlet not accessible by default
            - Should only be enabled in development environment
      20242: ALF-2733: Recreate corrupt authorities produced by LDAP import
      20240: ALF-2733: Recreate corrupt authorities produced by LDAP import
      19032: Moved V3.1.0-ENTERPRISE-FINAL into ENTERPRISE/V3.1.0
      13776: Tagged V3.1 rev 13700 (build 142) as V3.1.0-ENTERPRISE-FINAL
   22093: Merged PATCHES/V3.1.1 to V3.3-BUG-FIX (RECORD ONLY)
      21570: ALF-3687: Build classpath fix
      21549: Merged PATCHES/V3.1.0 to PATCHES/V3.1.1
         20221: Merged PATCHES/V3.1.2 to PATCHES/V3.1.0
            20217: Merged PATCHES/V3.2.0 to PATCHES/V3.1.2
               19793: Merged HEAD to V3.2.0
                  19786: Refactor of previous test fix. I have pushed down the OOo-specific parts of the change from AbstractContentTransformerTest to OpenOfficeContentTransformerTest leaving an extension point in the base class should other transformations need to be excluded in the future.
                  19785: Fix for failing test OpenOfficeContentTransformerTest.testAllConversions.
                     Various OOo-related transformations are returned as available but fail on our test server with OOo on it.
                     Pending further work on these failings, I am disabling those transformations in test code whilst leaving them available in the product code. This is because in the wild a different OOo version may succeed with these transformations.
                     I had previously explicitly disabled 3 transformations in the product and I am moving that restriction from product to test code for the same reason.
                  19707: Return value from isTransformationBlocked was inverted. Fixed now.
                  19705: Refinement of previous check-in re OOo transformations.
                     I have pulled up the code that handles blocked transformations into a superclass so that the JodConverter-based transformer worker can inherit the same list of blocked transformations. To reiterate, blocked transformations are those that the OOo integration code believes should work but which are broken in practice. These are blocked by the transformers and will always be unavailable regardless of the OOo connection state.
                  19702: Fix for HEAD builds running on panda build server.
                     OOo was recently installed on panda which has activated various OOo-related transformations/extractions in the test code.
                     It appears that OOo does not support some transformations from Office 97 to Office 2007. Specifically doc to docx and xls to xlsx. These transformations have now been marked as unavailable.
      21548: Incremented version label
      21547: ALF-4121: Merged V3.2 to PATCHES/V3.1.1
         16827: ETHREEOH-2678 - Unfriendly system error occurs when trying to view Workflows information on content Details page if workflow was canceled
      21275: Merged PATCHES/V3.1.2 to PATCHES/V3.1.1
         21264: ALF-3889: JBPMDeployProcessServlet not accessible by default
            - Should only be enabled in development environment
      21235: Removed old source zip
      21233: Merged PATCHES/V3.1.2 to PATCHES/V3.1.1
         20890: ALF-3687: Apply LUCENE-1383 patch to Lucene 2.1.0 to reduce memory leaks from ThreadLocals
         20891: ALF-3687: Build classpath fix
      21227: Merged PATCHES/V3.2.1 to PATCHES/V3.1.1
         21207: Extra debug logging to track index triggering activity
      21225: Merged V3.2 to PATCHES/V3.1.1
         19598: Backported (merge not possible) HEAD rev 18790 for IndexInfo fixes
            - Hit problem where re-index threads were all waiting for merging, which had nothing to do
      21223: Merged V3.2 to PATCHES/V3.1.1
         16923: Lucene performance: avoid too many index deltas getting created by throttling transactions when the number of index entries gets above a configurable size
            - Stops performance degradation over time and out of memory errors under load
      21222: Merged V3.2 to PATCHES/V3.1.1
         16799: Fix for ETHREEOH-2843:  lucene.indexer.minMergeDocs , lucene.indexer.mergeFactor and lucene.indexer.maxMergeDocs are never read / used
            - removed unused properties and parameterised the remaining unexposed properties
      21220: Created hotfix branch off TAGS/ENTERPRISE/V3.1.1
      19033: Moved V3.1.1-ENTERPRISE-FINAL into ENTERPRISE/V3.1.1
      14897: Tagged V3.1 rev 14748 (build 229) as TAGS/V3.1.1-ENTERPRISE-FINAL
   22096: Merged PATCHES/V3.1.2 to V3.3-BUG-FIX (RECORD ONLY)
      22033: ALF-4504: Fix unit test classpath
      22031: ALF-4503: Removed spurious mergeinfo
      22030: ALF-4503: Merged V3.2 to PATCHES/V3.1.2
         19518: ALF-757: Corrected audit config resource URL so that it resolves inside Tomcat as well as JUnit!
      22028: Incremented version label
      22026: ALF-4504: Merged HEAD to PATCHES/V3.1.2
         19958: Updating pdfbox and fontbox libraries.
            The 3rd party libraries apache pdfbox and apache fontbox have been updated from version 0.8.0-incubating to version 1.1.0.

            Apache states that: [...] notable changes in this release include basic support for tagged PDF, various font handling improvements and better handling of CJK character sets.

            Source is available as before for pdfbox, but is no longer included for fontbox.
      22025: ALF-4503: Merged V3.2 to PATCHES/V3.1.2
         18000: Merged DEV/BELARUS/V3.2-2009_11_24 to V3.2
            17719: ETHREEOH-3393: AuditConfig file is read every time the audit method is called in HibernateAuditDAO
         19501: Merged DEV/BELARUS/V3.2-2010_02_24 to HEAD (with corrections)
            19243: ALF-757: Cannot start up on JBoss 5.1 due to audit configuration error
               - Removed getPath() method because it is incompatible with JBoss and other app servers where resources can't be resolved to a file
               - Now use Spring ResourceLoader instead of creating FileInputStream
               - getLastModified() still returned where the resource resolves to a file; otherwise the server startup time
      21699: Incremented version label
      21697: ALF-4275: Merged PATCHES/V3.2.0 to PATCHES/V3.1.2
         20349: Merged V3.3 to PATCHES/V3.2.0
            20346: ALF-2839: Node pre-loading generates needless resultset rows
               - Added missing Criteria.list() call
         20280: Fixed ALF-2839: Node pre-loading generates needless resultset rows
              - Split Criteria query to retrieve properties and aspects separately
      21696: ALF-4275: Merged V3.3-BUG-FIX to PATCHES/V3.1.2
         20231: Fixed ALF-2784: Degradation of performance between 3.1.1 and 3.2x (observed in JSF)
            - Handles warm caches more efficiently
            - Doesn't regress on ETWOTWO-949
            - Can be backported safely
      21694: ALF-4275: Merged PATCHES/V3.2.0 to PATCHES/V3.1.2
         20266: Test reproduction of ALF-2839 failure: Node pre-loading generates needless resultset rows
      17041: Merged V3.2 to V3.1
         17023: Fixed parentAssocCache bug when adding assocs against an empty cache   
      16987: Merge 2.2 to 3.1:
         13089: (record-only) Fix "Read-Write transaction" exception, when the user does not exist. ETWOTWO-1055.
         13091: (record-only) Fix for NFS server "Read-Write transaction started within read-only transaction" exception. ETWOTWO-1054.
         14190: (record-only) Fix for cut/paste a folder from Alfresco CIFS to local drive loses folder contents. ETWOTWO-1159.
         14191: (record-only) Additional fix for CIFS 'No more connections' error. ETWOTWO-556
         14199: (record-only) Fix for NFS problem with Solaris doing an Access check on the share level handle. ETWOTWO-1225.
         14210: (record-only) Added support for FTP EPRT and EPSV commands, on IPv4 only. ETWOTWO-325.
         14216: (record-only) Fixed FTP character encoding, ported UTF8 normalizer code from v3.x. ETWOTWO-1151.
         14229: (record-only) Remove unused import.
         14655: (record-only) Convert content I/O exceptions to file server exceptions during write and truncate. ETWOTWO-1241.
         14825: (record-only) Add support for the extended response to the CIFS NTCreateAndX call, back port of ETWOTWO-1232.
         15869: (record-only) Port of desktop action client side EXE fixes from v3.x. ETWOTWO-1374.
      16727: Fix for unable to connect via FTP via Firefox (when anonymous logons are not enabled). ETHREEOH-2012.
      16718: Fix for Alfresco and AVM spaces are empty when viewed by FTP and Alfresco is run as non-root. ETHREEOH-2652.
         Triggered when CIFS server uses default ports on Linux/Unix/Mac platforms and fails to start.
      16717: Fixed setAllowConsoleShutdown setting in standalone server can cause infinite loop. JLAN-38.
      16710: Added CIFS NT status code/text for the 'account locked' status, 0xC0000234. ETHREEOH-2897.
      16709: Fixed the FTP not logged on status return code, now uses reply code 530. JLAN-90.
      16666: Fix for CIFS cannot handle requests over 64K in JNI code, causes session disconnect, standalone server. JLAN-91.
      16559: Fix for ACL parsing in the standalone JLAN Server build. JLAN-89.
      16556: Fix for CIFS session leak and 100% CPU when connect/disconnecting quickly. ETHREEOH-2881. 
      16555: Fix for processing of NetBIOS packets over 64K in the older JNI code. Part of ETHREEOH-2882.
      16309: Merged V2.2 to V3.1 (for rev 16305)
         16304: Fix ETWOONE-335: Parallel Review does not store Priority and Due Date set at task creation
      16305: ETWOONE-335: Parallel Review does not store Priority and Due Date set at task creation
      16163: Added timstamp tracking via the file state cache, blend cached timestamps into file info/folder search results.
         Added support for . and .. pseudo entries in a wildcard folder search.
      16162: Add support for the . and .. pseudo entries in a folder search.
         Return EA size as zero in CIFS file information levels.
         Added more debug output to notify change handler.
      16160: Minor change to debug output
      15827: Fixed bug in delete node event processing.
      15780: Fix for MS Office document locking issue. ETHREEOH-2579.
      15628: Update svn:mergeinfo
      15627: Merge 3.2 to 3.1:
         15626: Fixed NetBIOS reports an invalid packet during session connection, and connection stalls for a while. JLAN-86.
      15572: Update svn:mergeinfo
      15571: Merge 3.2 to 3.1:
         15549: Check for null ClientInfo in the setCurrentUser() method and clear the auth context. Part of ETHREEOH-2538.
         15550: Fixed performance issue in the continue search code, add warn level output of folder search timing.
      15570: Merge 3.2 to 3.1:
         15548: CIFS server memory leak fixes (clear auth context, session close). ETHREEOH-2538
      15231: Fix for cut/paste file between folders on CIFS. ETHREEOH-2323.
         Added debug flags to the Alfresco filesystems, implemented in the ContentDiskDriver. Changed debug output to be single line. ENH-515.
      14930: Updated svn:mergeinfo
      14921: Merge HEAD to V3.1:
         14599: Fixes to file server ACL parsing, part of ETHREEOH-2177
      14916: Fixes for local domain lookup when WINS is configured. ETHREEOH-2263.
      14523: Add trailing 'A' to CIFS server name, removed by recent checkin.
      14484: Merged HEAD to v3.1:
         13943 Added FTP IPv6 configuration, via the <IPv6 state="enabled|disabled"/> tag. Added the ftp.ipv6 property. MOB-714.
      14483: Merged HEAD to v3.1:
         13942 Added FTP IPv6 support. MOB-714.
   22097: Merged PATCHES/V3.2.0 to V3.3-BUG-FIX (RECORD ONLY)
      21556: Incremented version label
      21555: ALF-4208: Merged PATCHES/V3.1.1 to PATCHES/V3.2.0
         21225: Merged V3.2 to PATCHES/V3.1.1
            19598: Backported (merge not possible) HEAD rev 18790 for IndexInfo fixes
               - Hit problem where re-index threads were all waiting for merging, which had nothing to do
      17875: “Tagged V3.2 build 304 Revision 17823 as TAGS/V3.2.0-ENTERPRISE-FINAL”
   22098: Merged PATCHES/V3.2.1 to V3.3-BUG-FIX (RECORD ONLY)
      17876: Fix CMIS repo and folder browser web scripts. This can now be used as sample stand-alone JSR-168 portlet.
      18309: ETHREEOH-4003: Impossibility to declare email as record
      18378: ETHREEOH-4034: Permission exception when creating non-electronic records ...
      18468: ETHREEOH-4105: Frozen Records Can Be Destroyed
      18470: Part of ETHREEOH-4089: StoreModelObjectPersister fails to load model object
         - Added toString() methods to aid with diagnostics
      18471: Fixed ETHREEOH-4089: StoreModelObjectPersister fails to load model object
         - If the XML fails to parse, then it is treated the same as a missing document.
         - Rather than having the system fail, the XML failures are reported (turn DEBUG
           on for full XML dump) and the document is treated the same as
           "store.hasDocument() = false"
         - Merges to HEAD will need merging to SpringFramework
      18494: ETHREEOH-4089: StoreModelObjectPersister fails to load model object
         - Handle document parsing exceptions as well
      19170: Fixed ALF-730: MLText is not fully carried during cut-paste or copy-paste
         - Fetching of properties for copy now uses 'mlAwareNodeService'
      19286: Fix for https://issues.alfresco.com/jira/browse/ALF-626 "Using 'null' as an authority argument in clearPermissions() cause a java.lang.NullPointerException"
      19406: Fix for ALF-649 - Web Service query() no longer returns metadata in 3.2
      19597: Gave PropertyBackedBeanExporter a shorter name for it's cluster region name
      19599: Fix ETHREEOH-2583: Make the index tracking "hole" retention period more configurable
         - Added property 'index.tracking.maxVoidRetentionTimeMinutes', which defaults to the 'maxTxnDurationMinutes'
         - Even more usefully, added 'index.tracking.minVoidCheckPeriodSeconds' that allows void checking to be less frequent
           defaulting to only doing it every 60s
         - Added explicit logging for voids: log4j.logger.org.alfresco.repo.node.index.IndexTransactionTracker.voids=DEBUG
      19654: Fix blog test
      19718: Merged HEAD to BRANCHES/V3.2:
         19678: Fix PostgreSQL handling for null Serializable values (ALF-1614)
            - Provides generic way of targeting BLOB behaviour for different dialects
            - Fixes ALF-2301 by the way
      19759: Fix for CIFS/CheckInOut.exe save of working copy breaks lock on original file. ALF-2028.
      19760: Fix for working copy checked out via CIFS is not accessible until FileStateReaper expires file state. ALF-962.
      20048: "Tagged V3.2 build 499 Revision 19935 as TAGS/ENTERPRISE.V3.2.1"
      21166: Merged V3.3-BUG-FIX to PATCHES/V3.2.1
         21165: Fixed ALF-3867: SQL format error when re-instating orphaned content URL
            - Parameter was not bounded with #
            - Added unit test to ensure SQL generated is correct
   22101: Resolve ALF-4522: Accessing document via /alfresco/service/api/path doesn't work - "Company Home" token is duplicated
   - /cmis... urls accept paths relative to CMIS root path (which is /Company Home)
   - /api/path... urls accept paths relative to root of store
   22103: Merge from HEAD to V3.3-BUG-FIX
      22099: Fix for ALF-3733.

      Note that this should also fix ALF-4465.
   22104: Merged V3.3 to V3.3-BUG-FIX
      21690: ALF-3991: Disable audit behaviour when applying the RenditionModel.ASPECT_RENDITIONED aspect
      21722: Merged PATCHES/V3.3.1 to V3.3
         21721: ALF-4039: Extend store name encoding to all non-ASCII characters, as otherwise these are incorrectly mangled by the Tomcat 5 virtualization server when they appear in a web app path
            - Also use -x instead of _x so that the full encoded user name can be included in a DNS name
            - WCM preview now working with variety of user sandboxes with exotic characters in the user name!
      21767: ALF-4234: CMIS Relationships (fix issue with source and target relationship type checking)
      21789: ALF-4333: Fix
         - Updated RepoPrimaryManifestProcessorImpl so it can handle deletions that are reported by either pre-delete noderef or archived noderef (previously only handled the latter).
         - Updated TransferManifestNodeFactory so that it handles the case where the status of the node to transfer is "deleted".
         - Updated UnitTestTransferManifestNodeFactory so that it handles the change to TransferManifestNodeFactory above.
         - Added new tests for deletion cases.
      21808: Fix for ALF-1908 - encoding for all arguments to all templates associated with WebScripts that can be exposed and executed via a URL.
         - this includes any freemarker templates in /components and /modules that can be executed via url and do not touch context objects that would cause them to be invalid when executed via that url, for example any component or template that touches page.* cannot be executed via a url in the browser, but those that do not *could* be exposed via a clever scripted URL and be manipulated to potentially contain XSS code.
      21837: ALF-4039: In WebProjectServiceImpl.getWebUserRef() do not trust results of Lucene search alone. Certain special characters are ignored or treated as equivalent. Do string comparison to ensure exact match.
      21843: Merged V3.3-BUG-FIX to V3.3
         21137: ALF-3841: Alfresco Explorer SSO Authentication Filters now accept ticket parameters too
            - Can be turned back off with ntlm.authentication.browser.ticketLogons=false or kerberos.authentication.browser.ticketLogons=false
            - Wiki updated
      21856: ALF-4391: Fix Share URL rewrite configuration
         - The URL rewrite configuration was not including the query string in the source URL meaning that it got lost in the rewritten URL (for some reason only on Websphere)
         - Solved this by using the urlrewrite.xml from ALF-260 and adding use-query-string="true"
         - Need to retest on Tomcat and WAS
      21873: Fix ALF-2974: Locate file action is absent for documents in I'm editing tab in Repository
      21907: ALF-4401: Web services not working on Websphere 7 (ever?)
         - Added in Sun SAAJ and JAXP reference implementations to shared library in order to make CXF work
         - Removed old Sun SAAJ libraries as these are embedded into JDK 1.6
      21911: ALF-4399: Broken Repository Document library in Share on Websphere.
         (Fixing fallout from argument encoding in r21808)
      21924: Further fixes for ALF-1908 - XSS argument encoding fixes in Forms runtime
      21987: ALF-4187: Fix bitrock installer config so that the RMI communication ports are randomly selected and do not clash with the RMI registry port
      21998: ALF-4323: Fix ability to use ECMA-357 ECMAScript for XML (E4X) expressions in Share on Weblogic (and Rules Management)
         - Use child first loading of org.apache.xmlbeans.* packages
         - Makes sense because it was originally donated by BEA
   22105: Merged PATCHES/V3.2.r to V3.3-BUG-FIX (RECORD ONLY)
      21082: Fixes for ALF-3777 and ALF-3778 - improvements to XSS attack mitigation.
      21375: Fix ALF-3951 - XSS attack mitigation for IE6 browser. Also minor wiki code formatting fixes & HTML entities appearing in wiki dashlet.
      21400: Merged BRANCHES/V3.2 to PATCHES/V3.2.r
         19144: Added PRE tag to whitelist of safe tags for HTML stripping in Share.
         19363: Fix for ALF-1952 - multi-pass HTML stripping
         19814: Fix for ALF-2322 - discussion topic containing non-ascii characters cannot be saved
      21759: Fix for IE6 XSS issue ALF-4307
   22106: Merged PATCHES/V3.3.1 to V3.3-BUG-FIX (RECORD ONLY)
      21838: Merged V3.3 to PATCHES/V3.3.1
         21837: ALF-4039: In WebProjectServiceImpl.getWebUserRef() do not trust results of Lucene search alone. Certain special characters are ignored or treated as equivalent. Do string comparison to ensure exact match.
      21941: ALF-4424: Merged V3.3-BUG-FIX to PATCHES/V3.3.1
         21659: Workaround for ALF-4230: use of flash technology to upload documents into a share site makes the use of (some) external authentication methods difficult (or impossible)
            - The Flash uploader can be disabled via share-config: DocumentLibary / file-upload / adobe-flash-enabled
      21944: Incremented version label
      22079: ALF-4458: Merged PATCHES/V3.2.1 to PATCHES/V3.3.1
         21606 ALF-4044: Introduced new policy.content.update.ignoreEmpty setting, that when true causes the repository to behave as it did before the fix to ALF-254. I.e. writing empty content will not trigger onContentPropertyUpdate policies or inbound content rules. This enables better compatibility with mac clients using CIFS or WebDAV; they actually create and close a file before appending its data.
      ALF-4458: Merged V3.3 to PATCHES/V3.3.1
         20855: Fix for ALF-3690. Unable to FTP files into Share site documentLibrary folder.
            This fix corrects what it essentially a typo. The dictionaryService was injected twice into the CreateNodeRuleTrigger bean, rather than the dictionaryService and the ruleService.
      22082: Incremented version label
   22107: Merged PATCHES/V3.3.1 to V3.3-BUG-FIX
      21943: ALF-4402: Use normalized repository user ID when doing filesystem quota tracking
      22080: ALF-4458: Fixed broken logic in CreateNodeRuleTrigger.onAddAspect()
         - hasAspect() check was inverted because onAddAspect() is called before aspect is actually added


git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@22108 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
2010-08-31 19:35:11 +00:00

1063 lines
42 KiB
Java

/*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.rendition.executer;
import static org.alfresco.model.ContentModel.PROP_NODE_DBID;
import static org.alfresco.model.ContentModel.PROP_NODE_REF;
import static org.alfresco.model.ContentModel.PROP_NODE_UUID;
import static org.alfresco.model.ContentModel.PROP_STORE_IDENTIFIER;
import static org.alfresco.model.ContentModel.PROP_STORE_NAME;
import static org.alfresco.model.ContentModel.PROP_STORE_PROTOCOL;
import static org.alfresco.service.cmr.rendition.RenditionService.PARAM_DESTINATION_PATH_TEMPLATE;
import static org.alfresco.service.cmr.rendition.RenditionService.PARAM_IS_COMPONENT_RENDITION;
import static org.alfresco.service.cmr.rendition.RenditionService.PARAM_ORPHAN_EXISTING_RENDITION;
import static org.alfresco.service.cmr.rendition.RenditionService.PARAM_RENDITION_NODETYPE;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.model.RenditionModel;
import org.alfresco.repo.action.ParameterDefinitionImpl;
import org.alfresco.repo.action.executer.ActionExecuterAbstractBase;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.policy.BehaviourFilter;
import org.alfresco.repo.rendition.RenderingEngineDefinitionImpl;
import org.alfresco.repo.rendition.RenditionDefinitionImpl;
import org.alfresco.repo.rendition.RenditionLocation;
import org.alfresco.repo.rendition.RenditionLocationResolver;
import org.alfresco.repo.rendition.RenditionNodeManager;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ActionDefinition;
import org.alfresco.service.cmr.action.ParameterDefinition;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
import org.alfresco.service.cmr.rendition.NodeLocator;
import org.alfresco.service.cmr.rendition.RenderCallback;
import org.alfresco.service.cmr.rendition.RenditionDefinition;
import org.alfresco.service.cmr.rendition.RenditionService;
import org.alfresco.service.cmr.rendition.RenditionServiceException;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.namespace.NamespaceException;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.GUID;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.extensions.surf.util.I18NUtil;
import com.sun.star.lang.NullPointerException;
/**
* This class adds some new behaviour to the standard ActionExecuterAbstractBase
* in order to support the RenditionService.
*
* @author Neil McErlean
* @author Nick Smith
* @since 3.3
*/
public abstract class AbstractRenderingEngine extends ActionExecuterAbstractBase
{
/** Logger */
private static Log logger = LogFactory.getLog(AbstractRenderingEngine.class);
private static final String LINE_BREAK = System.getProperty("line.separator", "\n");
protected static final String CONTENT_READER_NOT_FOUND_MESSAGE = "Cannot find Content Reader for document. Operation can't be performed";
private static final String DEFAULT_RUN_AS_NAME = AuthenticationUtil.getSystemUserName();
// A word on the default* fields below:
//
// RenditionExecuters can be executed with or without two optional
// parameters: "rendition node type"
// and a "rendition content property" parameter.
// These parameters can be specified on a per-action basis.
// If no value is specified, then the default is used.
// That default can be injected via Spring.
// If no default is injected via spring, then there is a "default default"
// for the two params
/**
* This is the default default node type for renditions - used if no value
* is injected from spring.
*/
private static final QName DEFAULT_DEFAULT_RENDITION_NODE_TYPE = ContentModel.TYPE_CONTENT;
/**
* This is the default default property used to specify where rendition
* content is stored - used if no value is injected from spring.
*/
private static final QName DEFAULT_DEFAULT_RENDITION_CONTENT_PROP = ContentModel.PROP_CONTENT;
private static final String DEFAULT_MIMETYPE = MimetypeMap.MIMETYPE_TEXT_PLAIN;
private static final String DEFAULT_ENCODING = "UTF-8";
/**
* This is the default node type that is used when creating rendition
* objects.
*/
private QName defaultRenditionNodeType = DEFAULT_DEFAULT_RENDITION_NODE_TYPE;
/**
* This is the default property that is used to store rendition objects'
* content.
*/
private QName defaultRenditionContentProp = DEFAULT_DEFAULT_RENDITION_CONTENT_PROP;
/**
* This is the default content property.
*/
private static final QName DEFAULT_CONTENT_PROPERTY = ContentModel.TYPE_CONTENT;
/* Injected Services */
protected ContentService contentService;
protected MimetypeMap mimetypeMap;
/* Parameter names common to all Rendering Actions */
/**
* This optional {@link String} parameter specifies the location of a
* classpath resource which can be used as a placeholder while a rendition
* is being generated. For example, this might be a simple icon to indicate
* a rendition is not yet available. This is intended to be used in
* conjunction with asynchronous generation of renditions.
*/
public static final String PARAM_PLACEHOLDER_RESOURCE_PATH = "placeHolderResourcePath";
/**
* This optional {@link QName} parameter specifies which property the
* Rendering Engine uses to read content from the source node in order to
* create a rendition. By default this property will be cm:content.
*/
public static final String PARAM_SOURCE_CONTENT_PROPERTY = "sourceContentProperty";
/**
* This optional {@link QName} parameter specifies which property the
* Rendering Engine uses to write content to the rendition node. By default
* the property used is cm:content.
*/
public static final String PARAM_TARGET_CONTENT_PROPERTY = "targetContentProperty";
/**
* This optional {@link Boolean} flag property specifies whether a rendition
* should be updated automatically if the source node changes. If set to
* <code>true</code> then the rendition will be re-rendered any time any
* property changes occur on the source node. This parameter defaults to
* <code>false</code>.
*/
public static final String PARAM_UPDATE_RENDITIONS_ON_ANY_PROPERTY_CHANGE = "update-renditions-on-any-property-change";
/**
* This optional {@link String} parameter specifies what user permissions
* are used when creating a rendition. By default the system user is used.
*/
public static final String PARAM_RUN_AS = "runAs";
// mime-type is not a common parameter on all Rendering Actions, but it is
// common to many and is used in some common handling code in this class.
/**
* This optional {@link String} parameter specifies the mime type of the
* rendition content. This defaults to the mime type of the source node
* content.
*/
public static final String PARAM_MIME_TYPE = "mime-type";
/**
* This optional {@link String} paramter specifies the encoding used to
* create the rendition content. The derfault encoding is UTF-8.
*/
public static final String PARAM_ENCODING = "encoding";
private static final List<QName> unchangedProperties = Arrays.asList(PROP_NODE_DBID, PROP_NODE_REF, PROP_NODE_UUID,
PROP_STORE_IDENTIFIER, PROP_STORE_NAME, PROP_STORE_PROTOCOL);
/**
* Default {@link NodeLocator} simply returns the source node.
*/
private final static NodeLocator defaultNodeLocator = new NodeLocator()
{
public NodeRef getNode(NodeRef sourceNode, Map<String, Serializable> params)
{
return sourceNode;
}
};
/*
* Injected beans
*/
private RenditionLocationResolver renditionLocationResolver;
protected NodeService nodeService;
private RenditionService renditionService;
private BehaviourFilter behaviourFilter;
private final NodeLocator temporaryParentNodeLocator;
private final QName temporaryRenditionLinkType;
/**
* Injects the nodeService bean.
*
* @param nodeService
* the nodeService.
*/
public void setNodeService(NodeService nodeService)
{
this.nodeService = nodeService;
}
/**
* Injects the renditionService bean.
*
* @param renditionService
*/
public void setRenditionService(RenditionService renditionService)
{
this.renditionService = renditionService;
}
/**
* @param behaviourFilter policy behaviour filter
*/
public void setBehaviourFilter(BehaviourFilter behaviourFilter)
{
this.behaviourFilter = behaviourFilter;
}
public void setRenditionLocationResolver(RenditionLocationResolver renditionLocationResolver)
{
this.renditionLocationResolver = renditionLocationResolver;
}
public AbstractRenderingEngine(NodeLocator temporaryParentNodeLocator, QName temporaryRenditionLinkType)
{
this.temporaryParentNodeLocator = temporaryParentNodeLocator != null ? temporaryParentNodeLocator
: defaultNodeLocator;
this.temporaryRenditionLinkType = temporaryRenditionLinkType != null ? temporaryRenditionLinkType
: RenditionModel.ASSOC_RENDITION;
}
public AbstractRenderingEngine()
{
this(null, null);
}
/**
* Sets the default rendition-node type.
*
* @param type
*/
public void setDefaultRenditionNodeType(String type)
{
QName qname;
try
{
qname = QName.createQName(type);
}
catch (NamespaceException nx)
{
if (logger.isErrorEnabled())
{
logger.error("Error when setting default rendition node type: ", nx);
}
throw nx;
}
if (logger.isInfoEnabled())
{
logger.info("Using default rendition node type: " + qname);
}
this.defaultRenditionNodeType = qname;
}
/**
* This method returns the type of the default rendition node type.
*
* @return the QName representing the type of the default rendition node
* type.
*/
protected QName getDefaultRenditionNodeType()
{
return defaultRenditionNodeType;
}
protected String getTargetMimeType(RenderingContext context)
{
return context.getParamWithDefault(PARAM_MIME_TYPE, DEFAULT_MIMETYPE);
}
protected String getTargetEncoding(RenderingContext context)
{
return context.getParamWithDefault(PARAM_ENCODING, DEFAULT_ENCODING);
}
/**
* Sets the default rendition content property.
*
* @param prop
*/
public void setDefaultRenditionContentProp(String prop)
{
QName qname;
try
{
qname = QName.createQName(prop);
}
catch (NamespaceException nx)
{
if (logger.isErrorEnabled())
{
logger.error("Error when setting default rendition content property: ", nx);
}
throw nx;
}
if (logger.isInfoEnabled())
{
logger.info("Using default rendition content property: " + qname);
}
this.defaultRenditionContentProp = qname;
}
/**
* This method returns the QName of the property that defines the location
* of the rendition content. An example would be cm:content.
*
* @return the QName the property defining the location of the rendition
* content.
*/
protected QName getDefaultRenditionContentProp()
{
return defaultRenditionContentProp;
}
/**
* Set the content service
*
* @param contentService the content service
*/
public void setContentService(ContentService contentService)
{
this.contentService = contentService;
}
public void setMimetypeMap(MimetypeMap mimetypeMap)
{
this.mimetypeMap = mimetypeMap;
}
@Override
protected ActionDefinition createActionDefinition(String definitionName)
{
return new RenderingEngineDefinitionImpl(definitionName);
}
@Override
protected void executeImpl(final Action action, final NodeRef sourceNode)
{
final RenditionDefinition renditionDef = (RenditionDefinition)action;
if (logger.isDebugEnabled())
{
StringBuilder msg = new StringBuilder();
msg.append("Rendering node ").append(sourceNode).append(" with rendition definition ").append(
renditionDef.getRenditionName());
msg.append("\n").append(" parameters:").append("\n");
if (renditionDef.getParameterValues().isEmpty() == false)
{
for (String paramKey : renditionDef.getParameterValues().keySet())
{
msg.append(" ").append(paramKey).append("=").append(renditionDef.getParameterValue(paramKey)).append("\n");
}
}
else
{
msg.append(" [None]");
}
logger.debug(msg.toString());
}
Serializable runAsParam = action.getParameterValue(AbstractRenderingEngine.PARAM_RUN_AS);
String runAsName = runAsParam == null ? DEFAULT_RUN_AS_NAME : (String) runAsParam;
// Renditions should all be created by system by default.
// When renditions are created by a user and are to be created under a
// node
// other than the source node, it is possible that the user will not
// have
// permissions to create content under that node.
// For that reason, we execute all rendition actions as system
// by default.
AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Void>()
{
public Void doWork() throws Exception
{
ChildAssociationRef result = null;
try
{
boolean isComponentRendition = isComponentRendition(action);
if (isComponentRendition == false)
{
preRendition(renditionDef, sourceNode);
}
executeRenditionImpl(action, sourceNode);
result = (ChildAssociationRef)action.getParameterValue(PARAM_RESULT);
if (isComponentRendition == false)
{
postRendition(renditionDef, sourceNode, result);
}
} catch (Throwable t)
{
notifyCallbackOfException(renditionDef, t);
throwWrappedException(t);
}
if (result != null)
{
notifyCallbackOfResult(renditionDef, result);
}
return null;
}
}, runAsName);
}
private boolean isComponentRendition(Action action) {
Serializable s = action.getParameterValue(PARAM_IS_COMPONENT_RENDITION);
boolean result = s == null ? false : (Boolean)s;
return result;
}
protected void executeRenditionImpl(Action action, NodeRef sourceNode)
{
if (logger.isDebugEnabled())
{
StringBuilder msg = new StringBuilder();
msg.append("Executing rendering engine; name:")
.append(this.name).append(", class:")
.append(this.getClass().getName());
logger.debug(msg.toString());
}
checkParameterValues(action);
RenditionDefinition renditionDefinition = checkActionIsRenditionDefinition(action);
checkSourceNodeExists(sourceNode);
ChildAssociationRef renditionAssoc = createRenditionNodeAssoc(sourceNode, renditionDefinition);
QName targetContentProp = getRenditionContentProperty(renditionDefinition);
NodeRef destinationNode = renditionAssoc.getChildRef();
RenderingContext context = new RenderingContext(sourceNode,//
destinationNode,//
renditionDefinition,//
targetContentProp);
render(context);
// This is a workaround for the fact that actions don't have return
// values.
action.getParameterValues().put(PARAM_RESULT, renditionAssoc);
}
/**
* This method can be overridden by subclasses to provide checking of parameter
* values.
* If a parameter value is illegal or inappropriate, an exception
* should be thrown.
*/
protected void checkParameterValues(Action action)
{
// Intentionally empty
}
/**
* @param renditionDefinition
* @return
*/
protected QName getRenditionContentProperty(RenditionDefinition renditionDefinition)
{
return getParamWithDefault(PARAM_TARGET_CONTENT_PROPERTY, defaultRenditionContentProp, renditionDefinition);
}
protected abstract void render(RenderingContext context);
/**
* @param actionedUponNodeRef
*/
protected void checkSourceNodeExists(NodeRef actionedUponNodeRef)
{
if (nodeService.exists(actionedUponNodeRef) == false)
{
String msg = "Cannot execute action as node does not exist: " + actionedUponNodeRef;
logger.warn(msg);
throw new RenditionServiceException(msg);
}
}
/**
* @param action
*/
protected RenditionDefinition checkActionIsRenditionDefinition(Action action)
{
if (action instanceof RenditionDefinition)
{
return (RenditionDefinition)action;
}
else
{
return new RenditionDefinitionImpl(action);
}
}
/**
* If no rendition node type is specified, then the default is used
*
* @param renditionDefinition
* @return
*/
private QName getRenditionNodeType(RenditionDefinition renditionDefinition)
{
return getParamWithDefault(PARAM_RENDITION_NODETYPE, defaultRenditionNodeType, renditionDefinition);
}
@Override
final protected void addParameterDefinitions(List<ParameterDefinition> paramList)
{
paramList.addAll(getParameterDefinitions());
}
/**
* This method gets the parameter definition display label from the properties file.
* It looks first for a property whose key has a fixed rendition service-specific
* prefix and if that gets null, it then delegates to the standard bean name-based
* approach.
*
* @param paramName the name of the parameter
* @return the display label of the parameter
*/
@Override
protected String getParamDisplayLabel(String paramName)
{
// First we try to get the message using a common prefix for all rendering engines.
final String commonPropertiesPrefix = "baseRenderingAction";
String message = I18NUtil.getMessage(commonPropertiesPrefix + "." + paramName + "." + DISPLAY_LABEL);
// And if that doesn't work we delegate to the standard bean name-based approach.
if (message == null)
{
message = super.getParamDisplayLabel(paramName);
}
return message;
}
/**
* Supplies the list of parameters required by this rendering engine.
*
* @return
*/
protected Collection<ParameterDefinition> getParameterDefinitions()
{
List<ParameterDefinition> paramList = new ArrayList<ParameterDefinition>();
paramList.add(new ParameterDefinitionImpl(RenditionDefinitionImpl.RENDITION_DEFINITION_NAME, DataTypeDefinition.QNAME, true,
getParamDisplayLabel(RenditionDefinitionImpl.RENDITION_DEFINITION_NAME)));
paramList.add(new ParameterDefinitionImpl(PARAM_RUN_AS, DataTypeDefinition.TEXT, false,
getParamDisplayLabel(PARAM_RUN_AS)));
paramList.add(new ParameterDefinitionImpl(PARAM_UPDATE_RENDITIONS_ON_ANY_PROPERTY_CHANGE, DataTypeDefinition.BOOLEAN, false,
getParamDisplayLabel(PARAM_UPDATE_RENDITIONS_ON_ANY_PROPERTY_CHANGE)));
paramList.add(new ParameterDefinitionImpl(PARAM_RENDITION_NODETYPE, DataTypeDefinition.QNAME, false,
getParamDisplayLabel(PARAM_RENDITION_NODETYPE)));
paramList.add(new ParameterDefinitionImpl(PARAM_PLACEHOLDER_RESOURCE_PATH, DataTypeDefinition.TEXT, false,
getParamDisplayLabel(PARAM_PLACEHOLDER_RESOURCE_PATH)));
paramList.add(new ParameterDefinitionImpl(PARAM_SOURCE_CONTENT_PROPERTY, DataTypeDefinition.QNAME, false,
getParamDisplayLabel(PARAM_SOURCE_CONTENT_PROPERTY)));
paramList.add(new ParameterDefinitionImpl(PARAM_TARGET_CONTENT_PROPERTY, DataTypeDefinition.QNAME, false,
getParamDisplayLabel(PARAM_TARGET_CONTENT_PROPERTY)));
paramList.add(new ParameterDefinitionImpl(PARAM_DESTINATION_PATH_TEMPLATE, DataTypeDefinition.TEXT, false,
getParamDisplayLabel(PARAM_DESTINATION_PATH_TEMPLATE)));
paramList.add(new ParameterDefinitionImpl(PARAM_ORPHAN_EXISTING_RENDITION, DataTypeDefinition.BOOLEAN, false,
getParamDisplayLabel(PARAM_ORPHAN_EXISTING_RENDITION)));
paramList.add(new ParameterDefinitionImpl(PARAM_RESULT, DataTypeDefinition.CHILD_ASSOC_REF, false,
getParamDisplayLabel(PARAM_RESULT)));
paramList.add(new ParameterDefinitionImpl(PARAM_IS_COMPONENT_RENDITION, DataTypeDefinition.BOOLEAN, false,
getParamDisplayLabel(PARAM_IS_COMPONENT_RENDITION)));
return paramList;
}
private ChildAssociationRef createRenditionNodeAssoc(NodeRef sourceNode, RenditionDefinition renditionDefinition)
{
QName renditionName = renditionDefinition.getRenditionName();
// The ThumbnailService puts a cm:name property on its thumbnail nodes.
Map<QName, Serializable> nodeProps = new HashMap<QName, Serializable>();
nodeProps.put(ContentModel.PROP_NAME, renditionName.getLocalName());
nodeProps.put(ContentModel.PROP_CONTENT_PROPERTY_NAME, getRenditionContentProp(renditionDefinition));
QName assocName = QName.createQName(NamespaceService.RENDITION_MODEL_1_0_URI, GUID.generate());
NodeRef parentNode = renditionDefinition.getRenditionParent();
QName assocType = renditionDefinition.getRenditionAssociationType();
QName nodeType = getRenditionNodeType(renditionDefinition);
ChildAssociationRef childAssoc = nodeService.createNode(parentNode, assocType, assocName, nodeType, nodeProps);
return childAssoc;
}
private Serializable getRenditionContentProp(RenditionDefinition renditionDefinition)
{
return getParamWithDefault(PARAM_TARGET_CONTENT_PROPERTY, getDefaultRenditionContentProp(), renditionDefinition);
}
/**
* Gets the value for the named parameter. Checks the type of the parameter
* is correct and throws a {@link RenditionServiceException} if it isn't.
* Returns <code>null</code> if the parameter value is <code>null</code>
*
* @param paramName the name of the parameter being checked.
* @param clazz the expected {@link Class} of the parameter value.
* @param definition the {@link RenditionDefinition} containing the
* parameters.
* @return the parameter value or <code>null</code>.
*/
@SuppressWarnings("unchecked")
public static <T> T getCheckedParam(String paramName, Class<T> clazz, RenditionDefinition definition)
{
Serializable value = definition.getParameterValue(paramName);
if (value == null)
return null;
else
{
if(clazz == null)
throw new RenditionServiceException("The class must not be null!", new NullPointerException());
Class<? extends Serializable> valueClass = value.getClass();
if ( !valueClass.isAssignableFrom(clazz))
{
throw new RenditionServiceException("The parameter: " + paramName + " must be of type: "
+ clazz.getName() + "but was of type: " + valueClass.getName());
}
else
return (T) value;
}
}
/**
* Gets the value for the named parameter. Checks the type of the parameter
* is the same as the type of <code>defaultValue</code> and throws a
* {@link RenditionServiceException} if it isn't. Returns
* <code>defaultValue</code> if the parameter value is <code>null</code>
*
* @param <T>
* @param paramName
* @param defaultValue
* @param definition
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getParamWithDefault(String paramName, T defaultValue, RenditionDefinition definition)
{
if(defaultValue == null)
throw new RenditionServiceException("The defaultValue cannot be null!", new NullPointerException());
Class<? extends T> clazz = (Class<? extends T>) defaultValue.getClass();
T result = getCheckedParam(paramName, clazz, definition);
if (result == null)
result = defaultValue;
return result;
}
protected class RenderingContext
{
private final NodeRef sourceNode;
private final NodeRef destinationNode;
private final RenditionDefinition definition;
private final QName renditionContentProperty;
/**
* @param sourceNode
* @param destinationNode
* @param definition
* @param renditionContentProperty
*/
public RenderingContext(NodeRef sourceNode,//
NodeRef destinationNode,//
RenditionDefinition definition,//
QName renditionContentProperty)
{
this.sourceNode = sourceNode;
this.destinationNode = destinationNode;
this.definition = definition;
this.renditionContentProperty = renditionContentProperty;
}
/**
* @return the sourceNode
*/
public NodeRef getSourceNode()
{
return this.sourceNode;
}
/**
* @return the destinationNode
*/
public NodeRef getDestinationNode()
{
return this.destinationNode;
}
/**
* @return the definition
*/
public RenditionDefinition getDefinition()
{
return this.definition;
}
/**
* Gets the value for the named parameter from the . Checks the type of
* the parameter is correct and throws and Exception if it isn't.
* Returns <code>null</code> if the parameter value is <code>null</code>
*
* @param paramName the name of the parameter being checked.
* @param clazz the expected {@link Class} of the parameter value.
* @return the parameter value or <code>null</code>.
*/
public <T> T getCheckedParam(String paramName, Class<T> clazz)
{
return AbstractRenderingEngine.getCheckedParam(paramName, clazz, definition);
}
/**
* Gets the value for the named parameter. Checks the type of the
* parameter is the same as the type of <code>defaultValue</code> and
* throws a {@link RenditionServiceException} if it isn't. Returns
* <code>defaultValue</code> if the parameter value is <code>null</code>
*
* @param <T>
* @param paramName
* @param defaultValue
* @return
*/
public <T> T getParamWithDefault(String paramName, T defaultValue)
{
return AbstractRenderingEngine.getParamWithDefault(paramName, defaultValue, definition);
}
public ContentReader makeContentReader()
{
QName srcContentProp = getParamWithDefault(PARAM_SOURCE_CONTENT_PROPERTY, DEFAULT_CONTENT_PROPERTY);
ContentReader contentReader = contentService.getReader(sourceNode, srcContentProp);
if (contentReader == null || !contentReader.exists())
{
throw new RenditionServiceException(CONTENT_READER_NOT_FOUND_MESSAGE);
}
return contentReader;
}
public ContentWriter makeContentWriter()
{
ContentWriter contentWriter = contentService.getWriter(destinationNode, renditionContentProperty, true);
String mimetype = getTargetMimeType(this);
contentWriter.setMimetype(mimetype);
String encoding = getTargetEncoding(this);
contentWriter.setEncoding(encoding);
return contentWriter;
}
public int getIntegerParam(String key, int defaultValue)
{
Serializable serializable = definition.getParameterValue(key);
if (serializable == null)
return defaultValue;
else
{
Number number = (Number) serializable;
return number.intValue();
}
}
}
protected void preRendition(final RenditionDefinition renditionDef, final NodeRef actionedUponNodeRef)
{
setTemporaryRenditionProperties(actionedUponNodeRef, renditionDef);
// Adds the 'Renditioned' aspect to the source node if it
// doesn't exist.
if (!nodeService.hasAspect(actionedUponNodeRef, RenditionModel.ASPECT_RENDITIONED))
{
// Ensure we do not update the 'modifier' due to thumbnail addition
behaviourFilter.disableBehaviour(actionedUponNodeRef, ContentModel.ASPECT_AUDITABLE);
try
{
nodeService.addAspect(actionedUponNodeRef, RenditionModel.ASPECT_RENDITIONED, null);
}
finally
{
behaviourFilter.enableBehaviour(actionedUponNodeRef, ContentModel.ASPECT_AUDITABLE);
}
}
}
protected void postRendition(final RenditionDefinition renditionDef, final NodeRef actionedUponNodeRef, ChildAssociationRef tempRendAssoc)
{
ChildAssociationRef result = createOrUpdateRendition(actionedUponNodeRef, tempRendAssoc, renditionDef);
renditionDef.setParameterValue(PARAM_RESULT, result);
}
protected void notifyCallbackOfException(RenditionDefinition renditionDefinition, Throwable t)
{
// Rendition has failed. If there is a callback, it needs to be notified
if (renditionDefinition != null)
{
RenderCallback callback = renditionDefinition.getCallback();
if (callback != null)
{
callback.handleFailedRendition(t);
}
}
}
protected void throwWrappedException(Throwable t)
{
// and rethrow Exception
if (t instanceof AlfrescoRuntimeException)
{
throw (AlfrescoRuntimeException) t;
} else
{
throw new RenditionServiceException(t.getMessage(), t);
}
}
protected void notifyCallbackOfResult(RenditionDefinition renditionDefinition, ChildAssociationRef result)
{
// Rendition was successful. Notify the callback object.
if (renditionDefinition != null)
{
RenderCallback callback = renditionDefinition.getCallback();
if (callback != null)
{
callback.handleSuccessfulRendition(result);
}
}
}
/**
* This method sets the temporary rendition parent node and the rendition assocType on the
* rendition definition.
*
* @param sourceNode
* @param definition the rendition definition.
*/
private void setTemporaryRenditionProperties(NodeRef sourceNode, RenditionDefinition definition)
{
// Set the parent and assoc type for the temporary rendition to be
// created.
NodeRef parent = temporaryParentNodeLocator.getNode(sourceNode, definition.getParameterValues());
definition.setRenditionParent(parent);
definition.setRenditionAssociationType(temporaryRenditionLinkType);
}
private ChildAssociationRef createOrUpdateRendition(NodeRef sourceNode, ChildAssociationRef tempRendition,
RenditionDefinition renditionDefinition)
{
NodeRef tempRenditionNode = tempRendition.getChildRef();
RenditionLocation renditionLocation = resolveRenditionLocation(sourceNode, renditionDefinition, tempRenditionNode);
QName renditionQName = renditionDefinition.getRenditionName();
if (logger.isDebugEnabled())
{
StringBuilder msg = new StringBuilder();
msg.append("Creating/updating rendition based on:").append(LINE_BREAK).append(" sourceNode: ").append(
sourceNode).append(LINE_BREAK).append(" tempRendition: ").append(tempRendition).append(
LINE_BREAK).append(" parentNode: ").append(renditionLocation.getParentRef()).append(LINE_BREAK).append(
" childName: ").append(renditionLocation.getChildName()).append(LINE_BREAK).append(
" renditionDefinition.name: ").append(renditionQName);
logger.debug(msg.toString());
}
NodeRef oldRendition=getOldRenditionIfExists(sourceNode, renditionDefinition);
RenditionNodeManager renditionNodeManager = new RenditionNodeManager(sourceNode, oldRendition,
renditionLocation, renditionDefinition, nodeService);
ChildAssociationRef primaryAssoc = renditionNodeManager.findOrCreateRenditionNode();
// Copy relevant properties from the temporary node to the new rendition
// node.
NodeRef renditionNode = primaryAssoc.getChildRef();
transferNodeProperties(tempRenditionNode, renditionNode);
// Set the name property on the rendition if it has not already been
// set.
String renditionName = getRenditionName(tempRenditionNode, renditionLocation, renditionDefinition);
nodeService.setProperty(renditionNode, ContentModel.PROP_NAME, renditionName);
// Delete the temporary rendition.
nodeService.removeChildAssociation(tempRendition);
// Handle the rendition aspects
manageRenditionAspects(sourceNode, primaryAssoc);
ChildAssociationRef renditionAssoc = renditionService.getRenditionByName(sourceNode, renditionQName);
if (renditionAssoc == null)
{
String msg = "A rendition of type: " + renditionQName + " should have been created for source node: "
+ sourceNode;
throw new RenditionServiceException(msg);
}
return renditionAssoc;
}
/**
* This method returns the rendition on the given sourceNode with the given renditionDefinition, if such
* a rendition exists.
*
* @param sourceNode
* @param renditionDefinition
* @return the rendition node if one exists, else null.
*/
private NodeRef getOldRenditionIfExists(NodeRef sourceNode, RenditionDefinition renditionDefinition)
{
QName renditionName=renditionDefinition.getRenditionName();
ChildAssociationRef renditionAssoc = renditionService.getRenditionByName(sourceNode, renditionName);
NodeRef result = (renditionAssoc == null) ? null : renditionAssoc.getChildRef();
if (logger.isDebugEnabled())
{
StringBuilder msg = new StringBuilder();
msg.append("Existing rendition with name ")
.append(renditionName)
.append(": ")
.append(result);
logger.debug(msg.toString());
}
return result;
}
/**
* This method manages the <code>rn:rendition</code> aspects on the rendition node. It applies the
* correct rendition aspect based on the rendition node's location and removes any out-of-date rendition
* aspect.
*/
private void manageRenditionAspects(NodeRef sourceNode, ChildAssociationRef renditionParentAssoc)
{
NodeRef renditionNode = renditionParentAssoc.getChildRef();
NodeRef primaryParent = renditionParentAssoc.getParentRef();
// If the rendition is located directly underneath its own source node
if (primaryParent.equals(sourceNode))
{
// It should be a 'hidden' rendition.
nodeService.addAspect(renditionNode, RenditionModel.ASPECT_HIDDEN_RENDITION, null);
nodeService.removeAspect(renditionNode, RenditionModel.ASPECT_VISIBLE_RENDITION);
// We remove the other aspect to cover the potential case where a
// rendition
// has been updated in a different location.
} else
{
// Renditions stored underneath any node other than their source are
// 'visible'.
nodeService.addAspect(renditionNode, RenditionModel.ASPECT_VISIBLE_RENDITION, null);
nodeService.removeAspect(renditionNode, RenditionModel.ASPECT_HIDDEN_RENDITION);
}
}
/**
* This method calculates the name for a rendition node. The following approaches are attempted in
* the order given below.
* <ol>
* <li>If a name is defined in the {@link RenditionLocation} then that is used.</li>
* <li>If the temporary rendition has a <code>cm:name</code> value, then that is used.</li>
* <li>Otherwise use the rendition definition's rendition name.</li>
* </ol>
*
* @param tempRenditionNode the temporary rendition node.
* @param location a RenditionLocation struct.
* @param renditionDefinition the rendition definition.
* @return the name for the rendition.
*/
private String getRenditionName(NodeRef tempRenditionNode, RenditionLocation location,
RenditionDefinition renditionDefinition)
{
// If a location name is set then use it.
String locName = location.getChildName();
if (locName != null && locName.length() > 0)
{
return locName;
}
// Else if the temporary rendition specifies a name property use that.
Serializable tempName = nodeService.getProperty(tempRenditionNode, ContentModel.PROP_NAME);
if (tempName != null)
{
return (String) tempName;
}
// Otherwise use the rendition definition local name.
return renditionDefinition.getRenditionName().getLocalName();
}
/**
* This method copies properties from the sourceNode onto the targetNode as well as the node type.
* {@link NewPerformRenditionActionExecuter#unchangedProperties Some properties} are not copied.
*
* @param sourceNode the node from which the type and properties should be copied.
* @param targetNode the node to which the type and properties are copied.
*/
private void transferNodeProperties(NodeRef sourceNode, NodeRef targetNode)
{
if (logger.isDebugEnabled())
{
StringBuilder msg = new StringBuilder();
msg.append("Transferring some properties from ").append(sourceNode).append(" to ").append(targetNode);
logger.debug(msg.toString());
}
QName type = nodeService.getType(sourceNode);
nodeService.setType(targetNode, type);
Map<QName, Serializable> newProps = nodeService.getProperties(sourceNode);
for (QName propKey : unchangedProperties)
{
newProps.remove(propKey);
}
nodeService.setProperties(targetNode, newProps);
}
/**
* Given a rendition definition, a source node and a temporary rendition node, this method uses a
* {@link RenditionLocationResolver} to calculate the {@link RenditionLocation} of the rendition.
*/
private RenditionLocation resolveRenditionLocation(NodeRef sourceNode, RenditionDefinition definition,
NodeRef tempRendition)
{
return renditionLocationResolver.getRenditionLocation(sourceNode, definition, tempRendition);
}
}