Dave Ward fb887123ea Merged V4.1-BUG-FIX to HEAD
44918: Fix for ALF-14850 Opencmis getTotalNumItems doesn't return the correct result when setting MaxItemsPerPage
   - correctly report the max number of items
   44927: ALF-16254 ("Leave Site" behaviour for group based site membership)
   44931: Merged V3.4-BUG-FIX to V4.1-BUG-FIX (RECORD ONLY)
      44930: Merged V3.4 (3.4.12) to V3.4-BUG-FIX
         44929: Merged V4.1-BUG-FIX to V3.4 (3.4.12)
            42118: ALF-15878 ALF-15741: generate doc and src zip for web-framework-commons and jlan
   44939: Remove svn:mergeinfo
   44985: Merged DEV to V4.1-BUG-FIX
      44981: ALF-17085 : DB2: unexpected index found in database
         Correcting db structure after upgrade from 3.4. Optional statement was added.
   44988: Merged DEV to V4.1-BUG-FIX
      44937: ALF-16756: WebDAV: An error occurs on drag&drop content from local machine to alfresco when inbound move rule configured.
         Add check for content data length during determining existence of content on node.
   44989: Merged PATCHES/V4.1.3 to V4.1-BUG-FIX
      44984: Merged DEV to PATCHES/V4.1.3
         44983: ALF-12425: Can't launch activiti workflow console from Share when external / ntlm / kerberos authentication is used.
         In activiti-admin.get.js generated an absolute URL . Use  url.server + url.context  instead of /alfresco.
      44986: (RECORD ONLY) Merged DEV to PATCHES/V4.1.3
         44937: ALF-16756: WebDAV: An error occurs on drag&drop content from local machine to alfresco when inbound move rule configured.
         Add check for content data length during determining existence of content on node.
      44987: ALF-17331 60k Site Performance: Admin Console | Groups | Browse Groups (include sys groups): Pagination doesn't work correctly
   45008: ALF-17300 - ConcurrentModificationException
   45011: BDE-103 - Timezone test fail when not run from the UK (at least from Maven build)
   45054: Merged from DEV to V4.1-BUG-FIX
     ALF-13312 - If the license does not exist, please specify in the error message
   45055: Fix for ALF-13921. Description of the web project is not updated.
   45063: Slight improvement to test code as part of ALF-15413.
     Changing test code to get companyHome from repositoryHelper rather than Lucene query, which doesn't work on a dev box with ill-configured SOLR/Lucene.
   45170: Merged PATCHES\V4.1.3 to BRANCHES\DEV\V4.1-BUG-FIX
       45161: Fix for     ALF-17341  CLONE - Hyphen not handled correctly in cmis-alfresco search for Aspects/types : " no viable alternative at character 'a' "
   45192: Merged BRANCHES/DEV/V3.4-BUG-FIX to BRANCHES/DEV/V4.1-BUG-FIX:
      45187: (RECORD ONLY) Fix for ALF-16997 Discrepancies between standalone and cluster ehcache config
   45312: Merged V4.0.2 (4.0.2.23-24) to V4.1-BUG-FIX (4.1.4)
      44912: MNT-248 - 4.0.2.22 HOT FIX: Extra version is created saving changes in OpenOffice document via CIFS
      44964: Merged DEV to PATCHES/V4.0.2
         44963: MNT-263 : CLONE - CIFS: Image document version history lost after saving content in Preview on Mac Mountain Lion
         Fix for "Preview" shuffle scenario on Mac Mountain Lion. New ScenarioDoubleRenameShuffle scenario was added for pattern .*\.sb(-[A-Za-z0-9]*){2}. Unit test for correspomding scenario was added.
      45037: Remove PID check from byte range lock list checks. MNT-266.
      45286: MNT-277 - CIFS: Input/output error during saving ods file via OpenOffice. (Linux Specific)
   45319: NORWEGIAN: Translation updates.
   45338: Merged V4.1.3 (4.1.3) to V4.1-BUG-FIX (4.1.4)
      45186: ALF-17303: fix naming mismatch when deploying alfresco-enterprise-repository artifactId to Maven
      45247: Part 2: Better fix for     ALF-16359 Fix SOLR logging in production and other environments
      45265: ALF-17337 Read time out when browsing trash can 
      45298: ALF-17389: Merged: CLOUD1 to V4.1.3
         45082: CLOUD-1139: Cloud feednotifier running on 2 boxes
         - FeedNotifierImpl modified to use reliable lock refresh
         - Added additional debug logging to AbstractUserNotifier just in case we have to prove duplicate entries are still being processed
         - For full debug logging set
            log4j.logger.org.alfresco.repo.activities.feed.FeedNotifier=debug 
         - Happy New Year!
   45355: ALF-17389: Fix build error
   45357: Fix for     ALF-17430  CMIS valid relationships do not check the source and target are valid CMIS docs or folders.
   45363: Merge CLOUD1-BUG-FIX to V4.1-BUG-FIX
     42576 : Job Locking of PostLookup
   45367: Build fix corrections to merge 45363
   45381: ALF-17389 : Implementing Activities Job Lock.
   45416: Merged V4.1.3 (4.1.3) to V4.1-BUG-FIX (4.1.4) RECORD ONLY
      45415: ALF-17389: Merged V4.1-BUG-FIX to V4.1.3 (4.1.3)
         << Previous merge was to the wrong branch >>
         45363: Merge CLOUD1-BUG-FIX to V4.1-BUG-FIX
           42576 : Job Locking of PostLookup
         45367: Build fix corrections to merge 45363
         45381: ALF-17389 : Implementing Activities Job Lock.
   45424: Merged BRANCHES/DEV/BELARUS/V4.1-BUG-FIX-2013_01_05 to BRANCHES/DEV/V4.1-BUG-FIX:
      45235: ALF-15604 : Oracle: schema reference files missing nvarchar2 column sizes
   45425: Merged BRANCHES/DEV/BELARUS/V4.1-BUG-FIX-2013_01_05 to BRANCHES/DEV/V4.1-BUG-FIX:
      45236: ALF-15604 : Oracle: schema reference files missing nvarchar2 column sizes
   45480: ALF-17224: There will not be a "pageList" object in the freemarker model if a wiki page does not exist in a site and the wiki dashlet will cause an error on the site
   45482: Fixed ALF-11036, applied the patch, ran the tests.
   45485: ALF-17224: If the wiki page which was configured in the wiki dashlet will be deleted the dashlet will cause an error. The result of the call must be checked.
   45513: MNT-279: Use binary search in cached authority search to cut down search time when a group contains an astronomical number of authorities
   - Experimental fix to cut down on severe profiling hit
   45542: Fix for ALF-17443 - Contributors cannot edit their own discussion reply
   --This line, and th se below, will be ignored--
   M    root/projects/remote-api/source/java/org/alfresco/repo/web/scripts/discussion/ForumPostPut.java
   M    root/projects/remote-api/source/java/org/alfresco/repo/web/scripts/discussion/DiscussionRestApiTest.java
   45550: Merged V3.4-BUG-FIX to V4.1-BUG-FIX
      44920: ALF-11315 removed date localisation on blogpost.lib.ftl dates and corrected date format on pubDate within postlist-rss.get.rss.ftl (iso8601 was being used instead of the required RFC822)
      44936: Fix build
      44967: Merged V3.4 to V3.4-BUG-FIX
         44966: Merged PATCHES/V3.4.11 to V3.4 (3.4.12)
            44891: ALF-17339: Merged DEV to V3.4.11 (3.4.11.2)
               44877: MNT-265: possible improvement to Alfresco SQL query?
               -   Add getOneTxnsByCommitTimeDescending function that makes efficient query to find most recent transaction in time range.
            44951: ALF-17325 / MNT-274: Merged HEAD to PATCHES/V3.4.11
               33015: ALF-11837 - Alfresco 4.0 SMTP Inbound does not work with messages without From and To Headers.
      45191: Merged BRANCHES/V3.4 to BRANCHES/DEV/V3.4-BUG-FIX:
         45172: Fixed ALF-16140: Blank filetype icon is displayed for tiff image
      45436: Merged HEAD to BRANCHES/DEV/V3.4-BUG-FIX:
         31107: Google Docs SSL error
             * Fixed SSL required error that has appeared recently.
             * Google seemingly no longer supports non secure access to GDoc API.
             * Default URL's fixed up.
      45547: Merged V3.4 to V3.4-BUG-FIX
         45166: ALF-17339: Merged V3.4.11 (3.4.11.4) to V3.4 (3.4.12)
            45162: Merged DEV to V3.4.11 (3.4.11.4)
               44877: MNT-275 Possible issue with MNT-265 fix
                  - SQL from original HF should have used < rather than <= for upper time limit.
         45230: Merged DEV to V3.4 (3.4.12)
            45203: ALF-16992 : patch.fixAclInheritance is failing on sharedAclsThatDoNotInheritCorrectlyFromThePrimaryParent
            Ignoring of repeated ACL added
         45233: Mark the NFS server as active during startup. ALF-16228.
         45287: ALF-12145 Calendar autocomplete for advanced search form incorrectly handles zeros 
         45380: ALF-17461: There is different size of wcm-bootstrap-context.xml file from installer and archive
         - Replicated changes from ALF-11644 to Bitrock-installed copy of wcm-bootstrap-context.xml 
         45454: ALF-17396, ALF-13805: Merged V4.1-BUG-FIX (4.1.4) to V3.4 (3.4.12)
            Revision: 45452
            Author: kroast
            Date: 16 January 2013 09:59:45
            Message:
            Corrected config check for ALF-16413 - Share asks for Basic-Auth while not needed trying to access RSS feeds (thus breaking SSO).
            ----
            Modified : /alfresco/BRANCHES/DEV/V4.1-BUG-FIX/root/projects/slingshot/source/java/org/alfresco/web/site/servlet/SlingshotFeedController.java
         45491: Merge DEV to V3.4 (V3.4.12)
            45473: ALF-11956: WCM accessibility
            DOJO time picker has been fixed to allow selection of hours and minutes, using keyboard. Missing JavaScript key event handlers have been added.
            CSS class checking has been fixed in 'alfresco.xforms.FocusResolver' in 'xforms.js' to support all versions of IE. Some other minor changes...
         45543: Merged V4.1 to V3.4
            44743: ALF-17533 / ALF-17117: Created article or publication cant be viewed on WQS site
            - Further corrections to locking to avoid deadlocks
            44682: ALF-17512 / ALF-17118 WQS: Impossible to upload document to publications space
               - Only first part to do with the transformation failure has been committed. 
            44653: ALF-17533 / ALF-17117: Created article or publication cant be viewed on WQS site
            - Missed file from previous checkin
            44652: ALF-17533/ ALF-17117: Created article or publication cant be viewed on WQS site
            - Fixes by Dmitry Vaserin
            - Removed unnecessary outer read locks from getRelatedAssets and getRelatedAsset to prevent deadlock
            - Correct markup error when node doesn't have tags
         45546: ALF-17512: Corrections to property names by Pavel
      45548: Merged V3.4 to V3.4-BUG-FIX (RECORD ONLY)
         44977: Merged V3.4-BUG-FIX to V3.4
            44936: Fix build
   45553: Merged V3.4-BUG-FIX to V4.1-BUG-FIX (RECORD ONLY)
      45523: Merged BRANCHES/DEV/V4.1-BUG-FIX to BRANCHES/DEV/V3.4-BUG-FIX:
         45482: Fixed ALF-11036, applied the patch, ran the tests.
   45557: Merged V3.4-BUG-FIX to V4.1-BUG-FIX (RECORD ONLY)
      45556: Merged V3.4 to V3.4-BUG-FIX
         45554: Latest translations from Gloria for revision 45205
   45568: Merged PATCHES/V4.1.3 to V4.1-BUG-FIX
      45421: Merged HEAD to PATCHES\V4.1.3
          44243: Merged BRANCHES\DEV\AUTH_BRIDGE to HEAD
              43735: Final part of ALF-14861 	  SOLR to scale for non-admin users in 100k sites and a subgroup of each of 1000 independent groupings with 1000 subgroups
                     ALF-17489  ALF-17456
      45428: ALF-17455 : BM-0013: SOAK01_04: Activities Feed Cleaner query runs for minutes
      45489: ALF-17455 : BM-0013: SOAK01_04: Activities Feed Cleaner query runs for minutes
   45569: Merged PATCHES/V4.1.3 to V4.1-BUG-FIX (RECORD ONLY)
      45564: ALF-17492: WebScript errors must contain useful information 
      - So doth Derek decree
      - Copied in Surf revision 1217 changes as class local to share.war to avoid pulling in any more untested Surf changes
   45591: ALF-17465 (Document "social buttons/actions" not showing in document library page while document is being edited (locked))
   45601: ALF-17433 (Document detail version display incorrect document version when clicking on edit off line)
   45611: ALF-17478 - MailMetadataExtracter does not store all Message-Recipient-Address
   45622: Merged HEAD to BRANCHES/DEV/V4.1-BUG-FIX:
      35614: ALF-17598: CLONE - Add range header support to the webDAV servlet
   45633: ALF-17469: JSON message sent back to a client after a category creation is only partially JSON
   --This line, and th se below, will be ignored--
   M    category.post.json.ftl
   45641: Fix non-ASCII character in source comment
   45649: ALF-17556 (Share not redering URL correctly in description field)
   45650: Manually merged HEAD to BRANCHES/DEV/V4.1-BUG-FIX:
      - Changes to StreamContent from merge of THOR1_SPRINTS to HEAD in r34698
   45651: Merged HEAD to BRANCHES/DEV/V4.1-BUG-FIX:
      45222: ALF-17599: CLONE - Support For HTTP Range Requests in Repository WebScripts
           - Added HttpRangeProcessor.processRange which takes a WebScriptResponse parameter instead of HttpServletResponse
           - Changed HttpRangeProcessor.processSingeRange and HttpRangeProcessor.processMultiRange to accept a generic Object parameter then cast to the appropriate WebScriptResponse or HttpServletResponse
           - Added Javadoc to HttpRangeProcessor.processRange
           - Changed StreamContent.streamContentImpl to add code from BaseDownloadContentServlet which does the work of processing the range header from the request
           - Changed StreamContent.streamContentImpl method signature to accept nodeRef and propertyQName parameters needed for multi-range requests
           - Modified methods which override or call StreamContent.streamContentImpl for new method signature, passing in nodeRef and propertyQName or nulls where appropriate
   45655: Merged DEV to V4.1-BUG-FIX (4.1.4)
      45565: ALF-17503 : Lucene search with skipcount > hits fails when RM is installed
      Return a length=0 if a difference of values (count of finded results and results, that need to skip) is < 0
   45672: ALF-17452 (Status can't be updated with a blank status)
   45682: ALF-17444: Transformation of Outlook files (.msg) doesn't work ootb
   45751: Merged DEV to VC4.1-BUG-FIX (4.1.4)
      45748: ALF-17517: Document does not revert to previous version if certain rule is applied to the parent folder.
      Check node existance on ActionExecuterAbstractBase execution. Add unit test for case when inbound rule executed on node that was checked in.
   45758: ALF-12264: Fixed issue with pooled-tasks for groups with same name across tenants
   45761: Block r45756 from being merged to V4.1-BUG-FIX
   45765: Fix for     ALF-17153    FTS query parser FTSQueryParser is not debuggable
   45810: ALF-17520: Open Document templates are not tranformed properly for thumbnail and preview generation
   45828: Additional fix for     ALF-17153  FTS query parser FTSQueryParser is not debuggable
   45857: ALF-17516 (SHARE: Admin console of users and groups)
   45873: Remove so-called intermittent test category, so that only RepositoryStartupTest remains as a gatekeeper
   45903: ALF-16611 (When opening My Pages filter, a link to the renamed document becomes red)
   45906: ALF-17515: Wrong mimetype name in mimetype-map.xml
      - Changed macroEnabled to macroenabled
   45913: ALF-17462 (In Alfresco explorer invitation to a site does not show the correct options)
   45921: Fix for     ALF-17421  If a property is both multi-valued and multilingual a ClassCastException is thrown when Solr tries to index the property 
   - support multi-valued ML text but not content
   45926: Fix for     ALF-17602    lucene.defaultAnalyserResourceBundleName is not injected anywhere in the spring config
   46024: Merged V4.1.3 (4.1.3) to V4.1-BUG-FIX (4.1.4)
      45585: ALF-17303: alfresco-platform-distribution was not deployed properly to Maven repo
      45621: Removed svn:mergeinfo.  A 1.7 client should do this automatically.
      45669: Fix ALF-17582 - BM-0013: JMeter: Run 02: MT ContentStore caching is not thread safe
      45670: Fix ALF-17589 - BM-0013: JMeter: Run 02: CMISAbstractDictionaryService caching of DictionaryRegistry is not thread safe
      45692: Config option for     ALF-17526  BM-0013: JMeter: Run 02: Improve efficiency of services for SOLRAPIClient.getNodesMetaData 
      - preloading can be controlled + removed incorrect use of the secondary cache that could pull in stale data
      45705: Reverted Config option for     ALF-17526  BM-0013: JMeter: Run 02: Improve efficiency of services for SOLRAPIClient.getNodesMetaData 
      - preloading can be controlled + removed incorrect use of the secondary cache that could pull in stale data
      45716: Fix for ALF-17594 	SolrTracker: CMIS model diff (show 1 repeated diff) => CMIS dictionary re-init x2 (every 15 sec) 
      - only refresh the CMIS dictionary if there was an actual model put
      45755: Extra support to make clear what causes any difference between SOLR reports ALF-17588 	BM-0013: JMeter: Run 02: Deviation was detected in full index check reports for SOLR nodes. 
      - also added RETRY command to retry indexing any nodes that failed with errors.
      45803: Fix for     ALF-17490 Solr indexation problem with certain acls on a customer environment 
      - AclsGet respects the maximum acls requested and does not silently truncate toe 1024
      45829: GERMAN: Translation updates based on EN r45262
      45830: SPANISH: Translation updates based on EN r45262
      45831: FRENCH: Translation updates based on EN r45262
      45832: ITALIAN: Translation updates based on EN r45262
      45833: JAPANESE: Translation updates based on EN r45262
      45834: DUTCH: Translation updates based on EN r45262
      45835: RUSSIAN: Translation updates based on EN r45262
      45836: CHINESE: Translation updates based on EN r45262
      45858: Fix ALF-17634 -on startup FeedNotifier fetches all people slowly
      - switch from GetChildren CQ -> GetPeople CQ
      45859: Fix ALF-17634 -on startup FeedNotifier fetches all people slowly
      - reverse fix for this test ... for now, until we re-implement the deprecated method and fix the test case ;-)
      45951: Fix for     ALF-17687  BM-0013: Soak: Run 02: SolrJSONResultSet must preload nodes 
      - added node preload
      45952: SiteServiceImplTest: Added check that size limiting of results is working (and other minor cleanup)
      45953: Fixed ALF-17702: BM-0013: Soak: Run 02: getCachedChildAuthorities is not caching results 
       - getChildAssocs specifically checks for 'members' associations (was eliminated by code)
       - Cache negative results i.e. when there are no children
      45969: Part fix for     ALF-17526   BM-0013: Soak: Run 02: SOLRAPIClient.getNodesMetaData does N+1 calls to NodeDAO 
      - prependPaths caches nodes for the next layer
      45998: Part 2     ALF-17526   BM-0013: Soak: Run 02: SOLRAPIClient.getNodesMetaData does N+1 calls to NodeDAO 
      - make sure bulk node load works and that assocs are cached
      45999: Alternative implementation for     ALF-17719  BM-0013: Soak: Run 03: Contained authorities cache warmup times are restrictive 
      - bridge table is the default for hasAuthority()  - configurable on AuthorityServiceImpl
      46000: ALF-17574 BM-0013: JMeter: Run 02: Blocked threads on PDFParser.parse 
         - Found two blocking points in PdfBox to do with loading fonts from the class path (this was the main cause) and
           the PDFOperator access to a Synchronised map (identified above by Derek).
         - Note in 1.7.0 of PDFBox generally no font was loaded, but under 1.6.0 it was.
           This may be a bug in 1.7.0
      46001: ALF-17722: Merged V3.4 (3.4.12) to V4.1.3 (4.1.3)
         45629: ALF-17536: Stack Specific: Can't transform pdf to jpg
            - Added TRACE to log env properties using
              log4j.logger.org.alfresco.util.exec.RuntimeExec=trace
         45667: ALF-17536 Can't transform multi page pdf to jpg
            - issue was introduced by ALF-15436 Alfresco 3.4c + Share + TIFF preview only shows the first page
      46018: Merged HEAD to PATCHES/V4.1.3
         41904: Fixes bugs uncovered by JDK 7 upgrade
         - nodeService's interceptors depended on nodeService, resulting in some 'interesting' interceptor ordering in the chain (3 * the normal number in a random order). Now we use a lazy interceptor to break the cycle.
         - When the Content Language was en_GB and an MLText property contained {en_US, en_GB} it would return the en_US one, not taking country codes into account when available
      46023: Follow on to previous check in. Fix up evil cloud sync override of "nodeService" to also not suffer from a cyclic dependency!
   46034: Merged V3.4-BUG-FIX (3.4.13) to V4.1-BUG-FIX (4.1.4)
      45745: Merge V3.4 (3.4.12) to V3.4-BUG-FIX (3.4.13)
         45629: ALF-17536: Stack Specific: Can't transform pdf to jpg
            - Added TRACE to log env properties using
              log4j.logger.org.alfresco.util.exec.RuntimeExec=trace
         45667: ALF-17536 Can't transform multi page pdf to jpg
            - issue was introduced by ALF-15436 Alfresco 3.4c + Share + TIFF preview only shows the first page
         45724: ALF-17533 CLONE - Created article or publication cant be viewed on WQS site
            - Further change required to avoid deadlock
         45743: Correction to AuditComponentTest
            - Test was reporting "Incorrect number of audit entries after failed login expected:<1000> but was:<XXX>"
              where XXX was less than 1000. This was because results was being cleared if all all audit failures were
              not available in the first loop. The results needed to cleared before the first loop rather than in every
              loop. For example an XXX value of 830 would simply indicate that the first loop had received 170 audit
              results and that a second loop was required to get the rest.
      45754: Merged V3.4 (3.4.12) to V3.4-BUG-FIX (3.4.13)
         45747: Correction to AuditComponentTest
            - Okay last commit did not work. Try just waiting a bit longer than a second if we don't have all records.
      45976: Merged DEV to V3.4-BUG-FIX
         45925: ALF-16992 : patch.fixAclInheritance is failing on sharedAclsThatDoNotInheritCorrectlyFromThePrimaryParent
            Added a detection on cyclic loop for "inherits from" field.
   46037: Merged V4.1.3 (4.1.3) to V4.1-BUG-FIX (4.1.4)
      46033: Build fixes
      46032: ALF-17628 (No information is displayed in My Activities and Site Activities dashlets for content creation)
   46095: 
   46100: ALF-17773, ALF-17774, ALF-17775, ALF-17776: Merged V4.0.2 (4.0.2.26) to V4.1-BUG-FIX (4.1.4)
      45469: MNT-280: Merge from HEAD to V4.0.2 (4.0.2.25)
         43617: Fix for     ALF-16795 CMIS 0.8 TCK - load of large content fails
      45875: Merged DEV to V4.0.2 (4.0.2.26)
         45874: MNT-282: Mbean error stemming from cmis create.
         Synchronize initiating ContentStore.
         Add tenant name to object name of ContentStore MBean for preventing overriding of tenant MBeans.
      45904: MNT-285 Content Stream Errors during CMIS load test (Continuation of MNT-280)
         - Added 'advice' above retrying transactions to supply a ReusableContentStream
      45910: MNT-285 Content Stream Errors during CMIS load test (Continuation of MNT-280)
         - Added unit tests - tests both new TempFileProvider method and AlfrescoCmisStreamInterceptor
         - Corrections to interceptor
   46104: ALF-15843: Upgrade swftools back to 0.9.2
   46109: Merged RECORD ONLY V4.1.3 (4.1.3) to V4.1-BUG-FIX (4.1.4)
      46106: Merged V4.1-BUG-FIX (4.1.4) to V4.1.3 (4.1.3)
         46100: ALF-17773, ALF-17774, ALF-17775, ALF-17776: Merged V4.0.2 (4.0.2.26) to V4.1-BUG-FIX (4.1.4)
            45469: MNT-280: Merge from HEAD to V4.0.2 (4.0.2.25)
               43617: Fix for     ALF-16795 CMIS 0.8 TCK - load of large content fails
            45875: Merged DEV to V4.0.2 (4.0.2.26)
               45874: MNT-282: Mbean error stemming from cmis create.
               Synchronize initiating ContentStore.
               Add tenant name to object name of ContentStore MBean for preventing overriding of tenant MBeans.
            45904: MNT-285 Content Stream Errors during CMIS load test (Continuation of MNT-280)
               - Added 'advice' above retrying transactions to supply a ReusableContentStream
            45910: MNT-285 Content Stream Errors during CMIS load test (Continuation of MNT-280)
               - Added unit tests - tests both new TempFileProvider method and AlfrescoCmisStreamInterceptor
               - Corrections to interceptor
      46087: Merge V4.1-BUG-FIX (4.1.4) to V4.1.3 (4.1.3)
         45480: ALF-17224: There will not be a "pageList" object in the freemarker model if a wiki page does not exist in a site and the wiki dashlet will cause an error on the site
   46112: Merged (4.1.3) to V4.1-BUG-FIX (4.1.4)
      46048: ALF-17727 - BM-0013: Soak: Run 03: Site creation leads to contention on sites container
      - disable auditable behaviour on "sites" container (when creating a site)
      46050: ALF-17727 - BM-0013: Soak: Run 03: Site creation leads to contention on sites container
      - disable auditable behaviour on "sites" container (when deleting a site)
      46055: ALF-17729 - BM-0013: Soak: Run 03: ADMRemoteStore optimization to reduce contention on share folders
      - disable auditable behaviour on parent folder (when creating / deleting file)
      46059: Fixed ALF-17756: Thumbnails are being indexed 
       - Add the cm:indexControl aspect to thumbnails at creation time
       - Also prevent timestamp propagation when adding or removing thumbnails
      46077: Following on from rev 46059 (ALF-17756): Fixed up the mock NodeService.createNode call as we now pass in indexControl properties
      46078: Build fix for SiteServiceImplTest.testGroupMembership(SiteServiceImplTest.java:1308)
      46079: Additional fix for out of transaction tests
   46124: Reverse merge
      << Will A. did not intend to commit this >>
      46095: 
   46159: Fixed ALF-16889, Enabled cookie support for /wcs/api/login, independent from SSOAuthenticationFilter, on by default.
   46165: Fix for ALF-17787 - Site Members 'All Members' link should not run query immediately
   46169: Fix for ALF-17787 - Site Members 'All Members' link should not run query immediately - missing file
   46184: Refactoring a test class to use JUnit Rules - as part of attempt to reproduce ALF-17797.
   Using JUnit Rules like this will make it much easier to switch users between test methods.
   Checking in separately from future work as this check-in is a pure refactor.
   46185: ALF-17503 : Lucene search with skipcount > hits fails when RM is installed
      Fix build failures
      - Correct tests which expected -ve number of rows returned in a resultset
   46192: Enhancement to JUnit Rule TemporaryNodes.java as required by fix for ALF-17797.
   This check-in enhances TemporaryNodes to allow for the easy creation of specific named quick files.
   Previously you could only easily create a quick file selected by MIME type.
   Now you can use e.g. 'quickCorrupt.pdf' to get that specific file.
   46194: Fix for ALF-17797. AddFailedThumbnailActionExecuter is failing.
   This check-in adds a test case that reproduces the issue and a fix.
   The fix was to have the AddFailedThumbnailActionExecuter action runAs system.
   This is consistent with the behaviour of the create-thumbnail action itself.
   There is no way via the ActionService to run an action (in this case a compensating action)
   as a nominated user, and therefore I have had to change the implementation of
   AddFailedThumbnailActionExecuter.executeImpl so that it always runs-as system.
   46202: ALF-17644: Document version was increased after canceling editing.
   - Also a better fix for ALF-17167
   46208: ALF-17517 Document does not revert to previous version if certain rule is applied to the parent folder.
      - fix build failures (may still be one left) - Not all actions are node based
   46230: Merged V3.4-BUG-FIX to V4.1-BUG-FIX (4.1.4)
      46227: Filter repository test resources from alfresco.war
   46272: ALF-17841: Upgrade 4.0 --> 4.1.4 ClassCastException from OnPropertyUpdateRuleTrigger
   - Only listen for updates of single-valued content properties and cope with it previously being multi-valued (as can be the case with the devious license property)
   46279: ALF-17810: Imagemagick requires installation of Visual C++ redistributables
   - x86 VC++ 2008 SP1 redistributables now installed to support ImageMagick
   46354: ALF-10569: Reversing r32622 as it was due to an invalid interpretation of a Microsoft spec and should be unnecessary for the correct support of WebDAV 'dead properties'.
   - Correct fix about to be merged in from V3.4-BUG-FIX
   46360: ALF-17697: Create proper source jars, to deploy to Maven repository
   46361: Merged V3.4-BUG-FIX to V4.1-BUG-FIX
      45756: ALF-14722: Repeat merge of V4.1-BUG-FIX to V3.4-BUG-FIX - previous merge in r43028 did not bring over all required changes
      42902: Merged DEV to V4.1-BUG-FIX
         42519: ALF-13588: Google Doc failed to authenticate after incorrect password being entered for google account
            Add ability to unregister class behaviours.
            Unregister googledocs behaviours when subsystem stops. 
      45948: Merged DEV/WABSON/V4.1-GOOGLEDOCS-BUG-FIX to DEV/V3.4-BUG_FIX
         45898: ALF-17704 / ALF-16167: 'Edit Offline' checks out document in Google docs
            - Edit in Google Docs action is now decoupled from Edit Offline action
            - The checkout to Google Docs is only performed if a new parameter 'gdc' is set as a paramter when calling the action web script
            - This paramter causes the web script to call a new method checkoutToGoogleDocs() on ScriptNode if the parameter is set
            - The new method simply calls the existing checkout() method after setting a custom property on the transaction
            - The Google Docs policies now check for the presence of this transaction property before sending the document to Google
      45976: ALF-17876: Merged DEV to V3.4-BUG-FIX
         45925: ALF-16992 : patch.fixAclInheritance is failing on sharedAclsThatDoNotInheritCorrectlyFromThePrimaryParent
            Added a detection on cyclic loop for "inherits from" field.
      46041: ALF-17877: Merged DEV to V3.4-BUG-FIX (with corrections)
         46013: ALF-17662 : The deleted via Sharepoint document is not removed from Alfresco but hidden aspect is added for it
         Documents marked with sys:hidden aspect should be invisible through SPP protocol and should be treated as nonexistent.
      46054: ALF-17878 / ALF-17633 add alfresco-mmt.jar in the SDK distribution
      46173: ALF-17879 / ALF-17806: Merged PATCHES/V3.4.10 to V3.4-BUG-FIX
         46099: MNT-293: Merged V4.0-BUG-FIX to PATCHES/V3.4.10
            37969: Fixes for:
            ALF-12772 'Path not found' error in Share if user has no permissions to parent folders in breadcrumb
            ALF-14527 Share - Error to display documents if user has no access to the parent folder
            - Share now correctly supports accessing documents and folders (and details page actions) where the user does not have Read permissions on the parent node.
         46101: MNT-293: AccessDenied using CMIS when user does not have access to parent folder
         - Fix by Vasily
         46125: MNT-293: Correct Kev's logic to do permission checks after resolving a path as system
         46127: Merged V3.4 to PATCHES/V3.4.10
            45743: Correction to AuditComponentTest
               - Test was reporting "Incorrect number of audit entries after failed login expected:<1000> but was:<XXX>"
                 where XXX was less than 1000. This was because results was being cleared if all all audit failures were
                 not available in the first loop. The results needed to cleared before the first loop rather than in every
                 loop. For example an XXX value of 830 would simply indicate that the first loop had received 170 audit
                 results and that a second loop was required to get the rest.  
            45747: Correction to AuditComponentTest
               - Okay last commit did not work. Try just waiting a bit longer than a second if we don't have all records.   
      46195: ALF-17880 / ALF-17378: Web content is not editable after cancelling the Edit Web Content Wizard
      - Fix by Andrey
      46227: Filter repository test resources from alfresco.war
      46324: Merged DEV to V3.4-BUG-FIX (with improvements)
         45602: ALF-10569 / ALF-17519 : SPP is setting residual properties with an unknown name space (urn:schemas-microsoft-com)
         Implemented special case for handling dead webdav properties. New webdav:object aspect was introduced. It is used to 
         store all dead properties that may be set on resource.
      46353: ALF-17881 / ALF-17272: TooManyClauses error due to syntax error in the query generated from UIComponentSelector
      - Fixed typo in Lucene query generation introduced in r20310
   46362: ALF-17876: Re-fix typo introduced in V3.4-BUG-FIX merge
   46363: Merged V3.4-BUG-FIX to V4.1-BUG-FIX (RECORD ONLY)
      46285: Merged V4.1-BUG-FIX to V3.4-BUG-FIX
         46279: ALF-17810: Imagemagick requires installation of Visual C++ redistributables
         - x86 VC++ 2008 SP1 redistributables now installed to support ImageMagick
      46325: ALF-17863: Merged V4.1-BUG-FIX to V3.4-BUG-FIX
         43649: ALF-16756: WebDAV: An error occurs on drag&drop content from local machine to alfresco when inbound move rule configured. 
         43651: ALF-16756: Fixed typos - I took this code in good faith!
         44988: Merged DEV to V4.1-BUG-FIX
            44937: ALF-16756: WebDAV: An error occurs on drag&drop content from local machine to alfresco when inbound move rule configured.
               Add check for content data length during determining existence of content on node.
   46395: Merged V4.1.3 (4.1.3) to V4.1-BUG-FIX (4.1.4)
      46121: Fixed code warnings
      46123: Further improvements on ALF-17702: BM-0013: Soak: Run 02: getCachedChildAuthorities is not caching result
       - Reduced cache entry size
       - Removed binary sort search for authority entries
       - PS: This is one of the most heavily used code paths in the system
      46153: Merged DEV to V4.1.3 (4.1.3)
         << Lots of other changes in addition to merged code>>
         46093: ALF-16149 : CLONE - User search retrieves all users from the DB regardless of search criteria
            - Re-implemented deprecated method PersonServiceImpl.getPeople(...) to use getPeopleCQ or FTS search
         - Replaced calls to deprecated getPeople with calls to other one where it would end up being called anyway.
         - Fixed PersonServiceTests
         - Fixed GetPeopleCannedQuery to use totalResultCount - tests failed otherwise
         - Added warning to PersonService.getPeopleFilteredByProperty(...) if PROP_FIRSTNAME, PROP_LASTNAME, PROP_USERNAME
           were not being used. This was the one place that 'could' called the deprecated getPeople(...) method with
      	 other properties. Other properties are not included in the search values.
      46178: ALF-17796 - BM-0013: Soak: Run 04: Contention on folder 'user' containing users
      - disable auditable behaviour on parent folders (see also ALF-17729)
      46244: Fix for     ALF-17801   BM-0013: Soak: Run 04: ConcurrentModificationException in AbstractLuceneQueryParser 
      - consistently name anonymous constraints defined on properties
      46265: ALF-17799 - BM-0013: Soak: Run 04: Regular timeouts getting site memberships
      - initial fix: make sure limit cut-off is also applied when processing "groups to expand"
      46286: Fix for     ALF-17801   BM-0013: Soak: Run 04: ConcurrentModificationException in AbstractLuceneQueryParser 
      - build fixes for 
         1) Anonymous over-ridden constraints defined to contain the wrong property definition (no matter)
         2) but above causes name collision on over-ridden anonymous constraints on properties
         3) fix -over ride order to set inherited property definition info before over-ridding the property
      46290: ALF-17799 - BM-0013: Soak: Run 04: Regular timeouts getting site memberships
      - fix SiteActivityTest fallout (and adhere to current API contract)
      46315: ALF-17788: WebSphere: QueryException occurs during the clean startup
      - Corrected regression where FeedNotifier tries to scroll past the end of a result set
      46316: ALF-17702: Fixed regression of MNT-279 fix
      - Avoid sequential search across massive user sets when evaluating ACLs
      46350: Update Maven POM files
       - Upgrade version to 4.1.3
       - Upgrade pdfbox to 1.7.0-alfresco-20130130, to catch up after r46000 fixing ALF-17574
      46370: ALF-17613: Merged V4.0.2 (4.0.2.27) to V4.1.3 (4.1.3)
         46368: MNT-298 HF - Replace file by drag-and-drop over CIFS on Mac OS X and passthru/LDAP-AD gets "is in use" message and deletes the file 
   46421: Fix for ALF-17886. DeleteRenditionActionExecuter Acces is denied.
   With test of course.
   46438: ALF-17622 (Activities with Google Docs are not displayed in My Site Activities and Site Activities dashlets)
   46445: Fix for  ALF-17327 Cannot retrieve documents with a Japanese keyword.
   46457: ALF-17904 (GoogleDocs action doesn't work in doclib view)
   46482: Fix for ALF-17858. NPE in formService webscript.
   46497: Fix for ALF-15371 Instances of java.util.Map interface cannot be accessed in JavaScript
   The fix was to have getDefaultValue(Class) return the map.toString. It was previously returning null.
   46533: ALF-17286: SPP (Cluster specific):Document workspace is not browseable via Share if alfresco.host is pointing to balancer host
    - Ensure that concurrency conditions from AclDAO get propagagedby NodeDAO
   46540: Fix for     ALF-17397  searching based on property value that contains dashes doesn't work in a crossloanguage context using Solr 
   - fixed - also added support for query/index time analysis control for the default cross-language analyser. 
   - Not required to resolve the bug but may be useful to reduce query complexity (e.g. do not generate concatenated tokens for query)
      which could have been used as a work around for this bug if available.
   46546: Merged DEV to V4.1-BUG-FIX
      46494: ALF-17899 TempFileProvider.createTempFile() is not debugable
      Added debug logs.
   46562: ALF-17917: Corrected internationalization of Imap Home folder
   - Unfinished business from ALF-15700
   46563: Fix for ALF-17572 - Grey background in 'Google Docs Theme' when uploading files with IE8
   46564: Fix for ALF-17150 - Edit Online action missing in Share for some mime types (incorrect mimetype for PowerPoint files with SLDM extension)
   46565: ALF-17917: Correction to previous fix
   - Use distinct key spaces.imap_home.childname, because spaces.imapConfig.childname was already being used for other purposes
   46568: Fix for ALF-17757 and ALF-1101
   RSS Dashlet cannot display RSS feed produced by Shareӳ blog / RSS Feed Dashlet unable to read internal Alfesco Share site RSS Feeds
   - Fix implementation from Will Abson
   NOTE: there is a cavet, suggest SSO style config as per ALF-16413 to avoid basic auth pop-up when displaying some feeds.
   46624: removed
   46625: Undo last commit
   46626: Merged V4.1.1 (4.1.1.21) to V4.1-BUG-FIX (4.1.4)
      46602: ALF-17953: Alfresco constantly running full GCs
      - Possible fix to TikaPoweredContentTransformer to make it wrap FileContentReaders as TikaInputStreams which can be cast to Files and appear not to need reading into memory in their entirety in uncompressed form!
      - Fix also required to TikaOfficeDetectParser to avoid it wrapping a TikaInputStream unnecessarily
   46629: RECORD ONLY Merged V4.1.3 (4.1.3) to V4.1-BUG-FIX (4.1.4)
      46622: ALF-17968: Merged V4.0.2 (4.1.1.21) to V4.1.3 (4.1.3)
         46602: ALF-17953: Alfresco constantly running full GCs
         - Possible fix to TikaPoweredContentTransformer to make it wrap FileContentReaders as TikaInputStreams which can be cast to Files and appear not to need reading into memory in their entirety in uncompressed form!
         - Fix also required to TikaOfficeDetectParser to avoid it wrapping a TikaInputStream unnecessarily
         46607: ALF-17953 Alfresco constantly running full GC's - some java.lang.threads holding around 9Gb of memory
            - Added transformation limits to the 8 TikaPoweredContentTransformer based transformers, so that the maxSourceSizeKBytes
              can be set for each transformer and for each source mimetype used by each transformer.
            - maxSourceSizeKBytes set to 40MB for the newer 2007 MS office types (4 char ext).
         46619: ALF-17953 Alfresco constantly running full GC's - some java.lang.threads holding around 9Gb of memory
            - Changed maxSourceSizeKBytes values from 40MB back to -1 for the newer 2007 MS office types (4 char ext).
   46636: Fix for     ALF-13442      Tomcat memory leak warnings occur during the shutdown
   46679: Merged DEV to V4.1-BUG-FIX (4.1.4)
      46659: ALF-17631 : Errors/Exception during stress tests of CMIS GET children
      RetryingTransactionHelper has now ability to handle pre-configured exceptions as retriable in addition to default list of exceptions.
   46683: Merge PATCHES/V4.1.3 to V4.1-BUG-FIX (4.1.4)
      46637: Update the notice.txt and licenses with the latest modifications
   Add Microsoft Visual C++ 2008 Redistributable Package in the notice.txt
   46693: RECORD ONLY Merged V3.4-BUG-FIX (3.4.13) to V4.1-BUG-FIX (4.1.4)
      46692: ALF-17984: Merged V3.4.12 (3.4.12.2) to V3.4-BUG-FIX (3.4.13)
         46680: MNT-307: DEV to V3.4.12 (3.4.12.2)
            46659: ALF-17631 : Errors/Exception during stress tests of CMIS GET children
            RetryingTransactionHelper has now ability to handle pre-configured exceptions as retriable in addition to default list of exceptions.
            - Change to opencmis-context.xml on DEV (based on 4.1.4) was made to cmis-ws-context.xml on V3.4.12
   46694: Merged DEV to V4.1-BUG-FIX (4.1.4)
      46686: ALF-17631 : Errors/Exception during stress tests of CMIS GET children
      Unit test add for RetryingTransactionHelper to test extra exceptions are rertied correctly.
   46724: create-site.css and create-site.js will be included in the header (share-config.xml) therefore there is no reason to include them in the freemarker templates.
   46759: Merged DEV to V4.1-BUG-FIX (4.1.4)
      46734: ALF-17873 Missing versionLabel property after Version2ServiceImpl.restore()
      1. In Version2ServiceImpl.restore() to props Map was added ContentModel.PROP_VERSION_LABEL property.
      2. In VersionServiceImplTest.testRestore() was added the check that ContentModel.PROP_VERSION_LABEL property is correct.
   46760: Merged DEV to V4.1-BUG-FIX (4.1.4)
      46433: ALF-16883: Incorrect message occurred when delete Workspace if document is locked.
      Not possible to change MS Office message - have improved alfresco log message
   46782: ALF-17317 4.0.2.23 HOT FIX: OpenOffice server conversion failed 
   46783: ALF-17546 OOXMLThumbnailContentTransformer is not registered to handle special Office document types, such as templates and macro-enabled variants of document / template 
   46797: Restore missing mergeinfo accidentally removed in r46562
   46799: ALF-17546 OOXMLThumbnailContentTransformer is not registered to handle special Office document types, such as templates and macro-enabled variants of document / template
      - typo in mimetype case
   46916: ALF-17174 pdf2swf supports converting N first pages but alfresco does not support it via the pageLimit 
   46933: ALF-8144: Drastically improving performance using lazy-loaded WorklfowTask properties and path + improved the way share pages workflow-tasks to prevent building full model for unneeded tasks
   46946: ALF-18000: Startup script depends on the working directory where it is run
   - Changed vti.properties to
   vti.server.ssl.keystore=${dir.keystore}/vti.ssl.keystore 
   46995: Improvement related to     ALF-17380   Solr queries running slowly 
   - reader -> acl cache is built on demand (and warmed via authority warming)
   - this will mean it is not eagerly built for the archive store where it would be little used, and could be configured off for this case
   47032: ALF-17804: cmisatom URL (opencmis backed by Apache Chemistry OpenCMIS) does not support External authentication
    - Now it supports all kinds of authentication because it sits behind Alfresco's authentication filters
    - Fix researched by Alex Mukha
   47033: Merged V3.4-BUG-FIX to V4.1-BUG-FIX
      46453: ALF-18122 / ALF-17708: Incorrect behavior of "Show/Hide Breadcrumb" button when RM is installed
      - ContentService.getReader() now triggers a transaction retry if content is found to have disappeared under its feet due to eager content cleaning
      46495: ALF-18122 / ALF-17708: Incorrect behavior of "Show/Hide Breadcrumb" button when RM is installed
      - lower impact fix will only throw retryable exception if stream is accessed
      46822: ALF-18123: Merge Dev to V3.4-BUG-FIX
        ALF-17408 : Content is not displayed in imap folder after recovering
      46823: ALF-18124 / ALF-18091: Fix for MNT-311 - authentication challenge not present when users open direct links below /share/proxy/alfresco/cmis/i
      46927: ALF-18124 / ALF-18091: Merged PATCHES/V3.4.10 to V3.4-BUG-FIX
         46925: Merged V3.4-BUG-FIX to PATCHES/V3.4.10 (with correction)
            46823: Fix for MNT-311 - authentication challenge not present when users open direct links below /share/proxy/alfresco/cmis/*/content
      46942: ALF-17990: Fix security descriptors for new FileFolderService isHidden setHidden methods
      47021: ALF-18125: Merged DEV to V3.4-BUG-FIX
         46825: ALF-17681 : Lucene Search queries with PATH doesn't work in tenants
         A JUnit test was implemented to show that the PATH Lucene indexes are not created correctly for tenants. 
         46968: ALF-17681 : Lucene Search queries with PATH doesn't work in tenants
         The creation of PATH indexes is now made in context of multi tenant System user to run the reindexing process correctly in unauthenticated threads.
   47034: Merged V3.4-BUG-FIX to V4.1-BUG-FIX (RECORD ONLY)
      47030: ALF-16102: Merged PATCHES/V3.4.10 to V3.4-BUG-FIX (RECORD ONLY)
         41755: ALF-16013: Merged V4.1-BUG-FIX to PATCHES/V3.4.10
            41539: ALF-15899: Inbound email does not support multiple recipient folders
               - Fix by Dmitry Vaserin
      47031: ALF-18121: Merged PATCHES/V3.4.11 to V3.4-BUG-FIX
         46978: MNT-320: Merged HEAD to PATCHES/V3.4.11:
            36623: ALF-10243: form-service date-control now allows configuring only to send date-component of date-only formfields (timezone and time-component is reset server-side to prevent unnecesairy timezone-issues)
   47035: Merged PATCHES/V4.1.3 to V4.1-BUG-FIX
      46398: Fix for     ALF-17889   Alfresco failing as constraint in extension model cannot be defined 
      - use the namespace from the containing model and not the over-ridden property.
      46426: Merged BRANCHES/DEV/V4.1-BUG-FIX to PATCHES/V4.1.3:
         46421: Fix for ALF-17886. DeleteRenditionActionExecuter Acces is denied.
      46446: ALF-17864: BM-0013: Soak: Run 05: SiteService.listSites(username, size) performance (=> via listSitesImpl)
      - isAuthorityContained made to prune its search drastically - it caches hits and misses speeding up the search in a deeply nested group hierarchy such as SAP's
      - To avoid huge memory impact with lots of duplicate copies of authority names a pool of authority names is shared across all threads
      - getContainingAuthoritesInZone reinstated for site listing as it warms the same caches as the ACLs
      - Derek's latest tests with the changes applied showed a good speed up
      46501: ALF-17929: BM-0013: Soak: Run 06: /api/sites/{shortname}/memberships/{authorityname} / SiteServiceImpl.getMembersRoleInfo performance poor
      - Possible fix to regression caused by ALF-16254
      - A very inefficient route was being taken towards checking a user's indirect site role
      46502: ALF-17930: BM-0013: Soak: Run 06: ConcurrentModificationException in AuthorityDAOImpl
      - Don't try to mutate the set returned by getContainingAuthorities()
      46503: ALF-17929: BM-0013: Soak: Run 06: /api/sites/{shortname}/memberships/{authorityname} / SiteServiceImpl.getMembersRoleInfo performance poor
      - Further optimizations to prevent unnecessary recursion in AuthorityDAOImpl.listAuthorities()
      46506: ALF-17929: BM-0013: Soak: Run 06: /api/sites/{shortname}/memberships/{authorityname} / SiteServiceImpl.getMembersRoleInfo performance poor
      - Fixed typo producing invalid membership results
      46627: ALF-17967: Error in org.alfresco.repo.workflow.WorkflowServiceImpl.getPooledTasks on StartUp.
      - Logic error in org.alfresco.repo.workflow.WorkflowServiceImpl.getPooledTasks() introduced in ALF-14861 / r45421
      - Rather than fixing the screwy logic (which I think would cause a major performance hit) I'm reinstating the 4.1.2 "cut off after 100 groups" behaviour
      46630: Merged 4.1-BUG-FIX to PATCHES/V4.1.3
         46562: ALF-17917: Corrected internationalization of Imap Home folder
         - Unfinished business from ALF-15700
         46565: ALF-17917: Correction to previous fix
         - Use distinct key spaces.imap_home.childname, because spaces.imapConfig.childname was already being used for other purposes
      46779: ALF-17967: Error in org.alfresco.repo.workflow.WorkflowServiceImpl.getPooledTasks on StartUp.
      - Improved fix that uses the bridge table cache if it is available
      - Groups queried for pooled tasks still limited to 100 by default but can be configured with system.workflow.maxAuthoritiesForPooledTasks
      - Overall number of results can be cut off with system.workflow.maxPooledTasks
      47013: Fix HiddenAspect to NOT use permission-checking NodeService
       - Should fix ALF-17605: CLONE - Severe performance problems with Group ACL checking under stress test 
      47018: (RECORD ONLY) Disabled EmailServiceImplTest.testEmailContributorsAuthority pending ALF-17979
   47036: Merged PATCHES/V4.1.2 to V4.1-BUG-FIX
      46180: Merged DEV to PATCHES/V4.1.2
         46170: MNT-299 : CLONE - Activity feeds get not generated in private sites for added files if username in LDAP-AD contains uppercase letters
            Improved debug logging for Activity Feed and Activity Post DAOs.
   47037: ALF-17973 (Incorrect name (title.single/title.multi) for "cloud target selection" window when RM is installed)
   47042: RM-601 (Copy/Move dialog causes an error in firebug console)
   47047: DE: Translation update based on EN r46507
   47048: SPANISH: Translation update based on EN r46507
   47049: FRENCH: Translation update based on EN r46507
   47050: ITALIAN: Translation update based on EN r46507
   47051: NORWEGIAN: Translation update based on EN r46507
   47052: JAPANESE: Translation update based on EN r46507
   47089: ALF-17089 (Displaying Url Name instead of site Name in Select form)
   47102: New Norwegian translations from Gloria plus Bitrock configuration to enable them
   47110: ALF-10243: Merged V3.4-BUG-FIX to V4.1-BUG-FIX
      47105: ALF-18121: Merged PATCHES/V3.4.11 to V3.4-BUG-FIX
         47040: MNT-323: Fixed issue with passing empty due date when starting workflow
         47101: MNT-320: also applied fix to wcmquickstart module
      47109: ALF-18121: Merged PATCHES/V3.4.11 to V3.4-BUG-FIX
         47106: MNT-320: Merged V4.1-BUG-FIX to PATCHES/V3.4.11
            41010: ALF-15697: Not possible to start workflow not specifying the Due Date
               - Regression caused by ALF-10243
   47135: DUTCH: Translation update based on EN r46507
   47137: RUSSIAN: Translation update based on EN r46507
   47138: CHINESE: Translation update based on EN r46507
   47141: Fix for     ALF-17979    EmailServiceImplTest intermittently failing
   47147: Part 2 of    ALF-17979   EmailServiceImplTest intermittently failing 
   - fix related cache to avoid any future issue
   47148: ALF-17804: Fix NPE
   47171: ALF-18060: removing obsolete expensive sorting and preventing too many variable-queries to be performed when listing COMPLETED WorkflowTask


git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@47186 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
2013-02-27 11:56:13 +00:00

3113 lines
108 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.filesys.repo;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.InetAddress;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.filesys.alfresco.AlfrescoContext;
import org.alfresco.filesys.alfresco.AlfrescoDiskDriver;
import org.alfresco.filesys.alfresco.ExtendedDiskInterface;
import org.alfresco.filesys.alfresco.PseudoFileOverlayImpl;
import org.alfresco.filesys.alfresco.RepositoryDiskInterface;
import org.alfresco.jlan.server.SrvSession;
import org.alfresco.jlan.server.core.DeviceContext;
import org.alfresco.jlan.server.core.DeviceContextException;
import org.alfresco.jlan.server.filesys.AccessDeniedException;
import org.alfresco.jlan.server.filesys.DirectoryNotEmptyException;
import org.alfresco.jlan.server.filesys.DiskDeviceContext;
import org.alfresco.jlan.server.filesys.DiskFullException;
import org.alfresco.jlan.server.filesys.DiskInterface;
import org.alfresco.jlan.server.filesys.DiskSizeInterface;
import org.alfresco.jlan.server.filesys.FileInfo;
import org.alfresco.jlan.server.filesys.FileName;
import org.alfresco.jlan.server.filesys.FileOpenParams;
import org.alfresco.jlan.server.filesys.FileStatus;
import org.alfresco.jlan.server.filesys.IOControlNotImplementedException;
import org.alfresco.jlan.server.filesys.IOCtlInterface;
import org.alfresco.jlan.server.filesys.NetworkFile;
import org.alfresco.jlan.server.filesys.PermissionDeniedException;
import org.alfresco.jlan.server.filesys.SearchContext;
import org.alfresco.jlan.server.filesys.SrvDiskInfo;
import org.alfresco.jlan.server.filesys.TreeConnection;
import org.alfresco.jlan.server.filesys.cache.FileState;
import org.alfresco.jlan.server.filesys.pseudo.PseudoFile;
import org.alfresco.jlan.server.filesys.pseudo.PseudoFileList;
import org.alfresco.jlan.server.filesys.pseudo.PseudoNetworkFile;
import org.alfresco.jlan.server.filesys.quota.QuotaManager;
import org.alfresco.jlan.server.filesys.quota.QuotaManagerException;
import org.alfresco.jlan.server.locking.FileLockingInterface;
import org.alfresco.jlan.server.locking.LockManager;
import org.alfresco.jlan.server.locking.OpLockInterface;
import org.alfresco.jlan.server.locking.OpLockManager;
import org.alfresco.jlan.smb.SMBException;
import org.alfresco.jlan.smb.server.SMBServer;
import org.alfresco.jlan.util.DataBuffer;
import org.alfresco.jlan.util.MemorySize;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.encoding.ContentCharsetFinder;
import org.alfresco.repo.content.filestore.FileContentReader;
import org.alfresco.repo.model.filefolder.HiddenAspect;
import org.alfresco.repo.node.archive.NodeArchiveService;
import org.alfresco.repo.node.archive.RestoreNodeReport;
import org.alfresco.repo.policy.BehaviourFilter;
import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.service.cmr.coci.CheckOutCheckInService;
import org.alfresco.service.cmr.lock.LockService;
import org.alfresco.service.cmr.lock.NodeLockedException;
import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.repository.ContentData;
import org.alfresco.service.cmr.repository.ContentIOException;
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.MimetypeService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.security.AccessStatus;
import org.alfresco.service.cmr.security.AuthenticationService;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.PropertyCheck;
import org.alfresco.util.TempFileProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.extensions.config.ConfigElement;
/**
* Alfresco Content repository filesystem driver class
* <p>
* Provides a JLAN ContentDiskDriver for various JLAN protocols
* such as SMB/CIFS, NFS and FTP.
*
*/
public class ContentDiskDriver2 extends AlfrescoDiskDriver implements ExtendedDiskInterface,
DiskInterface,
DiskSizeInterface,
IOCtlInterface,
RepositoryDiskInterface,
OpLockInterface,
FileLockingInterface
{
// Logging
private static final Log logger = LogFactory.getLog(ContentDiskDriver2.class);
private static final Log readLogger = LogFactory.getLog("org.alfresco.filesys.repo.ContentDiskDriver2.Read");
private static final Log writeLogger = LogFactory.getLog("org.alfresco.filesys.repo.ContentDiskDriver2.Write");
// Services and helpers
private CifsHelper cifsHelper;
private NamespaceService namespaceService;
private NodeService nodeService;
private SearchService searchService;
private ContentService contentService;
private MimetypeService mimetypeService;
private PermissionService permissionService;
private FileFolderService fileFolderService;
private LockService lockService;
private CheckOutCheckInService checkOutCheckInService;
private AuthenticationContext authContext;
private AuthenticationService authService;
private BehaviourFilter policyBehaviourFilter;
private NodeMonitorFactory m_nodeMonitorFactory;
private ContentComparator contentComparator;
private NodeArchiveService nodeArchiveService;
private HiddenAspect hiddenAspect;
// TODO Should not be here - should be specific to a context.
private boolean isLockedFilesAsOffline;
/**
*
*/
public void init()
{
PropertyCheck.mandatory(this, "checkOutCheckInService", checkOutCheckInService);
PropertyCheck.mandatory(this, "cifsHelper", cifsHelper);
PropertyCheck.mandatory(this, "namespaceService", namespaceService);
PropertyCheck.mandatory(this, "nodeService", nodeService);
PropertyCheck.mandatory(this, "searchService", searchService);
PropertyCheck.mandatory(this, "contentService", contentService);
PropertyCheck.mandatory(this, "mimetypeService", mimetypeService);
PropertyCheck.mandatory(this, "permissionService", permissionService);
PropertyCheck.mandatory(this, "fileFolderService", fileFolderService);
PropertyCheck.mandatory(this, "lockService",lockService);
PropertyCheck.mandatory(this, "authContext", authContext);
PropertyCheck.mandatory(this, "authService", authService);
PropertyCheck.mandatory(this, "policyBehaviourFilter", policyBehaviourFilter);
PropertyCheck.mandatory(this, "m_nodeMonitorFactory", m_nodeMonitorFactory);
PropertyCheck.mandatory(this, "ioControlHandler", ioControlHandler);
PropertyCheck.mandatory(this, "contentComparator", getContentComparator());
PropertyCheck.mandatory(this, "nodeArchiveService", nodeArchiveService);
PropertyCheck.mandatory(this, "hiddenAspect", hiddenAspect);
}
/**
* Return the CIFS helper
*
* @return CifsHelper
*/
public final CifsHelper getCifsHelper()
{
return this.cifsHelper;
}
/**
* Return the authentication service
*
* @return AuthenticationService
*/
public final AuthenticationService getAuthenticationService()
{
return authService;
}
/**
* Return the authentication context
*
* @return AuthenticationContext
*/
public final AuthenticationContext getAuthenticationContext() {
return authContext;
}
/**
* Return the node service
*
* @return NodeService
*/
public final NodeService getNodeService()
{
return this.nodeService;
}
/**
* Return the content service
*
* @return ContentService
*/
public final ContentService getContentService()
{
return this.contentService;
}
/**
* Return the namespace service
*
* @return NamespaceService
*/
public final NamespaceService getNamespaceService()
{
return this.namespaceService;
}
/**
* Return the search service
*
* @return SearchService
*/
public final SearchService getSearchService(){
return this.searchService;
}
/**
* Return the file folder service
*
* @return FileFolderService
*/
public final FileFolderService getFileFolderService() {
return this.fileFolderService;
}
/**
* Return the permission service
*
* @return PermissionService
*/
public final PermissionService getPermissionService() {
return this.permissionService;
}
/**
* Return the lock service
*
* @return LockService
*/
public final LockService getLockService() {
return lockService;
}
/**
* Get the policy behaviour filter, used to inhibit versioning on a per transaction basis
*/
public BehaviourFilter getPolicyFilter()
{
return policyBehaviourFilter;
}
/**
* @param contentService the content service
*/
public void setContentService(ContentService contentService)
{
this.contentService = contentService;
}
/**
* @param namespaceService the namespace service
*/
public void setNamespaceService(NamespaceService namespaceService)
{
this.namespaceService = namespaceService;
}
/**
* @param nodeService the node service
*/
public void setNodeService(NodeService nodeService)
{
this.nodeService = nodeService;
}
/**
* @param searchService the search service
*/
public void setSearchService(SearchService searchService)
{
this.searchService = searchService;
}
/**
* Set the permission service
*
* @param permissionService PermissionService
*/
public void setPermissionService(PermissionService permissionService)
{
this.permissionService = permissionService;
}
/**
* Set the authentication context
*
* @param authContext AuthenticationContext
*/
public void setAuthenticationContext(AuthenticationContext authContext)
{
this.authContext = authContext;
}
/**
* Set the authentication service
*
* @param authService AuthenticationService
*/
public void setAuthenticationService(AuthenticationService authService)
{
this.authService = authService;
}
/**
* Set the file folder service
*
* @param fileService FileFolderService
*/
public void setFileFolderService(FileFolderService fileService)
{
fileFolderService = fileService;
}
/**
* @param mimetypeService service for helping with mimetypes and encoding
*/
public void setMimetypeService(MimetypeService mimetypeService)
{
this.mimetypeService = mimetypeService;
}
/**
* Set the node monitor factory
*
* @param nodeMonitorFactory NodeMonitorFactory
*/
public void setNodeMonitorFactory(NodeMonitorFactory nodeMonitorFactory) {
m_nodeMonitorFactory = nodeMonitorFactory;
}
/**
* Set the lock service
*
* @param lockService LockService
*/
public void setLockService(LockService lockService) {
this.lockService = lockService;
}
/**
* Set the policy behaviour filter, used to inhibit versioning on a per transaction basis
*
* @param policyFilter PolicyBehaviourFilter
*/
public void setPolicyFilter(BehaviourFilter policyFilter)
{
this.policyBehaviourFilter = policyFilter;
}
/**
* @param hiddenAspect
*/
public void setHiddenAspect(HiddenAspect hiddenAspect)
{
this.hiddenAspect = hiddenAspect;
}
// Configuration key names
private static final String KEY_STORE = "store";
private static final String KEY_ROOT_PATH = "rootPath";
private static final String KEY_RELATIVE_PATH = "relativePath";
/**
* Parse and validate the parameter string and create a device context object for this instance
* of the shared device. The same DeviceInterface implementation may be used for multiple
* shares.
* <p>
* @deprecated - no longer used. Construction of context is via spring now.
* @param deviceName The name of the device
* @param cfg ConfigElement the configuration of the device context.
* @return DeviceContext
* @exception DeviceContextException
*/
public DeviceContext createContext(String deviceName, ConfigElement cfg) throws DeviceContextException
{
logger.error("Obsolete method called");
throw new DeviceContextException("Obsolete Method called");
}
/*
* Register context implementation
* <p>
* Results in various obscure bits and pieces being initialised, most importantly the
* calculation of the root node ref.
* <p>
* There's a load of initialisation that needs to be moved out of this method, like the
* instantiation of the lock manager, quota manager and node monitor.
*/
public void registerContext(DeviceContext ctx) throws DeviceContextException
{
logger.debug("registerContext");
super.registerContext(ctx);
final ContentContext context = (ContentContext)ctx;
final String rootPath = context.getRootPath();
final String storeValue = context.getStoreName();
/**
* Work using the repo needs to run as system.
*/
RunAsWork<Void> runAsSystem = new RunAsWork<Void>()
{
@Override
public Void doWork() throws Exception
{
StoreRef storeRef = new StoreRef(storeValue);
// Connect to the repo and ensure that the store exists
if (! nodeService.exists(storeRef))
{
throw new DeviceContextException("Store not created prior to application startup: " + storeRef);
}
NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);
// Find the root node for this device
List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, rootPath, null, namespaceService, false);
NodeRef rootNodeRef = null;
if (nodeRefs.size() > 1)
{
throw new DeviceContextException("Multiple possible roots for device: \n" +
" root path: " + rootPath + "\n" +
" results: " + nodeRefs);
}
else if (nodeRefs.size() == 0)
{
// Nothing found
throw new DeviceContextException("No root found for device: \n" +
" root path: " + rootPath);
}
else
{
// We found the root node ref
rootNodeRef = nodeRefs.get(0);
}
// Check if a relative path has been specified
String relPath = context.getRelativePath();
try
{
if ( relPath != null && relPath.length() > 0)
{
// Find the node and validate that the relative path is to a folder
NodeRef relPathNode = cifsHelper.getNodeRef( rootNodeRef, relPath);
if ( cifsHelper.isDirectory( relPathNode) == false)
{
throw new DeviceContextException("Relative path is not a folder, " + relPath);
}
// Use the relative path node as the root of the filesystem
rootNodeRef = relPathNode;
}
else
{
// Make sure the default root node is a folder
if ( cifsHelper.isDirectory( rootNodeRef) == false)
{
throw new DeviceContextException("Root node is not a folder type node");
}
}
}
catch (Exception ex)
{
if(logger.isDebugEnabled())
{
logger.debug("Error during create context", ex);
}
throw new DeviceContextException("Unable to find root node.", ex);
}
// Record the root node ref
if(logger.isDebugEnabled())
{
logger.debug("set root node ref:" + rootNodeRef);
}
context.setRootNodeRef(rootNodeRef);
return null;
}
};
/**
* Run the above code as system - in particular resolves root node ref.
*/
AuthenticationUtil.runAs(runAsSystem, AuthenticationUtil.getSystemUserName());
/*
* Now we have some odds and ends below that should really be configured elsewhere
*/
// Check if locked files should be marked as offline
if ( context.getOfflineFiles() )
{
// Enable marking locked files as offline
isLockedFilesAsOffline = true;
logger.info("Locked files will be marked as offline");
}
// Enable file state caching
// context.enableStateCache(serverConfig, true);
// context.getStateCache().setCaseSensitive( false);
logger.debug("initialise the node monitor");
// Install the node service monitor
if ( !context.getDisableNodeMonitor() && m_nodeMonitorFactory != null)
{
NodeMonitor nodeMonitor = m_nodeMonitorFactory.createNodeMonitor(context);
context.setNodeMonitor( nodeMonitor);
}
logger.debug("initialise the file state lock manager");
// Check if oplocks are enabled
if ( context.getDisableOplocks() == true)
{
logger.warn("Oplock support disabled for filesystem " + context.getDeviceName());
}
// Start the quota manager, if enabled
if ( context.hasQuotaManager())
{
try
{
// Start the quota manager
context.getQuotaManager().startManager( this, context);
logger.info("Quota manager enabled for filesystem");
}
catch ( QuotaManagerException ex)
{
logger.error("Failed to start quota manager", ex);
}
}
// TODO mode to spring
PseudoFileOverlayImpl ps = new PseudoFileOverlayImpl();
ps.setContext(context);
ps.setNodeService(nodeService);
ps.setSysAdminParams(context.getSysAdminParams());
context.setPseudoFileOverlay(ps);
ps.init();
}
/**
* Determine if the disk device is read-only.
*
* @param sess Server session
* @param ctx Device context
* @return boolean
* @exception java.io.IOException If an error occurs.
*/
public boolean isReadOnly(SrvSession sess, DeviceContext ctx) throws IOException
{
if(logger.isDebugEnabled())
{
logger.debug("isReadOnly");
}
return !m_transactionService.getAllowWrite();
}
/**
* Get the file information for the specified file.
*
* @param sess Server session
* @param tree Tree connection
* @param name File name/path that information is required for.
* @return File information if valid, else null
* @exception java.io.IOException The exception description.
*/
public FileInfo getFileInformation(SrvSession session, TreeConnection tree, String path) throws IOException
{
if(logger.isDebugEnabled())
{
logger.debug("getFileInformation:" + path + ", session:" + session.getUniqueId());
}
ContentContext ctx = (ContentContext) tree.getContext();
if ( path == null || path.length() == 0)
{
path = FileName.DOS_SEPERATOR_STR;
}
String infoPath = path;
try
{
FileInfo finfo = null;
// Is the node a pseudo file ?
if(session.isPseudoFilesEnabled() && ctx.isPseudoFilesEnabled())
{
String[] paths = FileName.splitPath(path);
// lookup parent directory
NodeRef dirNodeRef = getNodeForPath(tree, paths[0]);
// Check whether we are opening a pseudo file
if(ctx.getPseudoFileOverlay().isPseudoFile(dirNodeRef, paths[1]))
{
PseudoFile pfile = ctx.getPseudoFileOverlay().getPseudoFile(dirNodeRef, paths[1]);
FileInfo pseudoFileInfo = pfile.getFileInfo();
if(logger.isDebugEnabled())
{
logger.debug("returning psuedo file details:" + pseudoFileInfo);
}
return pseudoFileInfo;
}
}
// no - this is not a specially named pseudo file.
NodeRef nodeRef = getNodeForPath(tree, infoPath);
if ( nodeRef != null)
{
// Get the file information for the node
finfo = getCifsHelper().getFileInformation(nodeRef, false, isLockedFilesAsOffline);
/**
* Special processing for root node
*/
if(path.equals(FileName.DOS_SEPERATOR_STR))
{
finfo.setFileName("");
}
// DEBUG
if ( logger.isDebugEnabled())
{
logger.debug("getFileInformation found nodeRef for nodeRef :"+ nodeRef + ", path: " + path);
}
// Moved to CIFS Helper
// // Set the file id from the node's DBID
// long id = DefaultTypeConverter.INSTANCE.convert(Long.class, nodeService.getProperty(nodeRef, ContentModel.PROP_NODE_DBID));
// finfo.setFileId((int) (id & 0xFFFFFFFFL));
}
// Return the file information or null if the node ref does not exist
return finfo;
}
catch (FileNotFoundException e)
{
// Debug
if (logger.isDebugEnabled())
{
// exception not logged - cifs does lots of these
logger.debug("Get file info - file not found, " + path);
}
throw e;
}
catch (org.alfresco.repo.security.permissions.AccessDeniedException ex)
{
// Debug
if ( logger.isDebugEnabled())
{
logger.debug("Get file info - access denied, " + path, ex);
}
// Convert to a filesystem access denied status
throw new AccessDeniedException("Get file information " + path);
}
catch (AlfrescoRuntimeException ex)
{
if ( logger.isDebugEnabled())
{
logger.debug("Get file info error" + path, ex);
}
// Convert to a general I/O exception
throw new IOException("Get file information " + path, ex);
}
}
/**
* Start a new search on the filesystem using the specified searchPath that may contain
* wildcards.
*
* @param sess Server session
* @param tree Tree connection
* @param searchPath File(s) to search for, may include wildcards.
* @param attrib Attributes of the file(s) to search for, see class SMBFileAttribute.
* @return SearchContext
* @exception java.io.FileNotFoundException If the search could not be started.
*/
public SearchContext startSearch(SrvSession session, TreeConnection tree, String searchPath, int attributes) throws FileNotFoundException
{
if(logger.isDebugEnabled())
{
logger.debug("startSearch: "+ searchPath + ", session:" + session.getUniqueId());
}
// Access the device context
ContentContext ctx = (ContentContext) tree.getContext();
try
{
String searchFileSpec = searchPath;
NodeRef searchRootNodeRef = ctx.getRootNode();
String[] paths = FileName.splitPath(searchPath);
String dotPath = paths[0];
// lookup parent directory
NodeRef dirNodeRef = getNodeForPath(tree, dotPath);
if(dirNodeRef != null)
{
searchRootNodeRef = dirNodeRef;
searchFileSpec = paths[1];
}
// Convert the all files wildcard
if ( searchFileSpec.equals( "*.*"))
{
searchFileSpec = "*";
}
// Debug
long startTime = 0L;
if ( logger.isDebugEnabled())
{
startTime = System.currentTimeMillis();
}
// Perform the search
logger.debug("Call repo to do search");
List<NodeRef> results = getCifsHelper().getNodeRefs(searchRootNodeRef, searchFileSpec);
// Debug
if ( logger.isDebugEnabled())
{
long endTime = System.currentTimeMillis();
if (( endTime - startTime) > 500)
{
logger.debug("Search for searchPath=" + searchPath + ", searchSpec=" + searchFileSpec + ", searchRootNode=" + searchRootNodeRef + " took "
+ ( endTime - startTime) + "ms results=" + results.size());
}
}
/**
* Search pseudo files if they are enabled
*/
PseudoFileList pseudoList = null;
if(session.isPseudoFilesEnabled() && ctx.isPseudoFilesEnabled())
{
logger.debug("search pseudo files");
pseudoList = ctx.getPseudoFileOverlay().searchPseudoFiles(dirNodeRef, searchFileSpec);
}
DotDotContentSearchContext searchCtx = new DotDotContentSearchContext(getCifsHelper(), results, searchFileSpec, pseudoList, paths[0], isLockedFilesAsOffline);
FileInfo dotInfo = getCifsHelper().getFileInformation(searchRootNodeRef, false, isLockedFilesAsOffline);
if ( searchPath.equals( FileName.DOS_SEPERATOR_STR)) {
// Searching the root folder, re-use the search folder file information for the '..' pseudo entry
FileInfo dotDotInfo = new FileInfo();
dotDotInfo.copyFrom(dotInfo);
searchCtx.setDotInfo(dotInfo);
searchCtx.setDotDotInfo( dotDotInfo);
}
else
{
String[] parent = FileName.splitPath(dotPath);
NodeRef parentNodeRef = getNodeForPath(tree, parent[0]);
if(parentNodeRef != null)
{
FileInfo dotDotInfo = getCifsHelper().getFileInformation(parentNodeRef, false, isLockedFilesAsOffline);
searchCtx.setDotDotInfo(dotDotInfo);
}
// Searching a normal, non root, folder
// Need to set dot and dotdot
searchCtx.setDotInfo(dotInfo);
}
// Debug
if (logger.isDebugEnabled())
{
logger.debug("Started search: search path=" + searchPath + " attributes=" + attributes + ", ctx=" + searchCtx);
}
// TODO --
// Need to resolve the file info here so it's within the transaction boundary.
return searchCtx;
}
catch (org.alfresco.repo.security.permissions.AccessDeniedException ex)
{
// Debug
if ( logger.isDebugEnabled())
{
logger.debug("Start search - access denied, " + searchPath);
}
// Convert to a file not found status
throw new FileNotFoundException("Start search " + searchPath);
}
catch (AlfrescoRuntimeException ex)
{
// This is an error even though we "handle" it here.
if ( logger.isErrorEnabled())
{
logger.error("Exception in Start search", ex);
}
// Convert to a file not found status
throw new FileNotFoundException("Start search " + searchPath);
}
}
/**
* Check if the specified file exists, and whether it is a file or directory.
*
*
* @param sess Server session
* @param tree Tree connection
* @param name the path of the file
* @return FileStatus (0: NotExist, 1 : FileExist, 2: DirectoryExists)
* @see FileStatus
*/
public int fileExists(SrvSession session, TreeConnection tree, String name)
{
if(logger.isDebugEnabled())
{
logger.debug("fileExists:" + name + ", session:" + session.getUniqueId());
}
ContentContext ctx = (ContentContext) tree.getContext();
int status = FileStatus.Unknown;
try
{
if(session.isPseudoFilesEnabled() && ctx.isPseudoFilesEnabled())
{
String[] paths = FileName.splitPath(name);
// lookup parent directory
NodeRef dirNodeRef = getNodeForPath(tree, paths[0]);
// Check whether we are opening a pseudo file
if(ctx.getPseudoFileOverlay().isPseudoFile(dirNodeRef, paths[1]))
{
return FileStatus.FileExists;
}
}
// Get the file information to check if the file/folder exists
FileInfo info = getFileInformation(session, tree, name);
if (info.isDirectory())
{
if(logger.isDebugEnabled())
{
logger.debug("is directory");
}
status = FileStatus.DirectoryExists;
}
else
{
if(logger.isDebugEnabled())
{
logger.debug("is file");
}
status = FileStatus.FileExists;
}
if (logger.isDebugEnabled())
{
logger.debug("File status determined: name=" + name + " status=" + status);
}
return status;
}
catch (FileNotFoundException e)
{
if(logger.isDebugEnabled())
{
logger.debug("file does not exist");
}
status = FileStatus.NotExist;
return status;
}
catch (IOException e)
{
// Debug
if ( logger.isDebugEnabled())
{
logger.debug("File exists error, " + name, e);
}
status = FileStatus.NotExist;
return status;
}
}
/**
* Open a file or folder - obsolete implementation.
*
* @param sess SrvSession
* @param tree TreeConnection
* @param params FileOpenParams
* @return NetworkFile
* @exception IOException
*/
public NetworkFile openFile(SrvSession session, TreeConnection tree, FileOpenParams params) throws IOException
{
// obsolete
logger.error("Obsolete method called");
throw new AlfrescoRuntimeException("obsolete method called");
}
/**
* Create a new file on the file system.
*
* @param sess Server session
* @param tree Tree connection
* @param params File create parameters
* @return NetworkFile
* @exception java.io.IOException If an error occurs.
*/
public NetworkFile createFile(SrvSession sess, final TreeConnection tree, final FileOpenParams params) throws IOException
{
// Obsolete
logger.error("Obsolete method called");
throw new AlfrescoRuntimeException("obsolete method called");
}
/**
* Create a new directory on this file system.
*
*
* @param sess Server session
* @param tree Tree connection.
* @param params Directory create parameters
* @exception java.io.IOException If an error occurs.
*/
public void createDirectory(SrvSession sess, final TreeConnection tree, final FileOpenParams params) throws IOException
{
final ContentContext ctx = (ContentContext) tree.getContext();
if (logger.isDebugEnabled())
{
logger.debug("createDirectory :" + params);
}
try
{
NodeRef dirNodeRef;
String folderName;
String path = params.getPath();
String[] paths = FileName.splitPath(path);
if (paths[0] != null && paths[0].length() > 1)
{
// lookup parent directory
dirNodeRef = getNodeForPath(tree, paths[0]);
folderName = paths[1];
}
else
{
dirNodeRef = ctx.getRootNode();
folderName = path;
}
if(dirNodeRef == null)
{
throw new IOException("Create directory parent folder not found" + params.getFullPath());
}
NodeRef nodeRef = getCifsHelper().createNode(dirNodeRef, folderName, ContentModel.TYPE_FOLDER);
if (logger.isDebugEnabled())
{
logger.debug("Created directory: path=" + params.getPath() + " file open params=" + params + " node=" + nodeRef);
}
// void return
}
catch (org.alfresco.repo.security.permissions.AccessDeniedException ex)
{
// Debug
if ( logger.isDebugEnabled())
{
logger.debug("Create directory - access denied, " + params.getFullPath());
}
// Convert to a filesystem access denied status
throw new AccessDeniedException("Create directory " + params.getFullPath());
}
catch (AlfrescoRuntimeException ex)
{
// Debug
if ( logger.isDebugEnabled())
{
logger.debug("Create directory error", ex);
}
// Convert to a general I/O exception
throw new IOException("Create directory " + params.getFullPath(), ex);
}
}
/**
* Delete the directory from the filesystem.
* <p>
* The directory must be empty in order to be able to delete ity
*
* @param sess Server session
* @param tree Tree connection
* @param dir Directory name.
* @exception java.io.IOException The exception description.
*/
public void deleteDirectory(SrvSession session, TreeConnection tree, final String dir) throws IOException
{
// get the device root
if (logger.isDebugEnabled())
{
logger.debug("deleteDirectory: " + dir + ", session:" + session.getUniqueId());
}
ContentContext ctx = (ContentContext) tree.getContext();
final NodeRef deviceRootNodeRef = ctx.getRootNode();
try
{
// Get the node for the folder
NodeRef nodeRef = getCifsHelper().getNodeRef(deviceRootNodeRef, dir);
if (fileFolderService.exists(nodeRef))
{
// Check if the folder is empty
if ( getCifsHelper().isFolderEmpty( nodeRef))
{
// Delete the folder node
fileFolderService.delete(nodeRef);
}
else
{
throw new DirectoryNotEmptyException( dir);
}
}
// Debug
if (logger.isDebugEnabled())
{
logger.debug("Deleted directory: directory=" + dir + " node=" + nodeRef);
}
// void return
}
catch (FileNotFoundException e)
{
// Debug
if (logger.isDebugEnabled())
{
logger.debug("Delete directory - file not found, " + dir);
}
}
catch (org.alfresco.repo.security.permissions.AccessDeniedException ex)
{
// Debug
if ( logger.isDebugEnabled())
{
logger.debug("Delete directory - access denied, " + dir);
}
// Convert to a filesystem access denied status
throw new AccessDeniedException("Delete directory, access denied :" + dir);
}
catch (AlfrescoRuntimeException ex)
{
// Debug
if ( logger.isDebugEnabled() && ctx.hasDebug(AlfrescoContext.DBG_FILE))
logger.debug("Delete directory", ex);
// Convert to a general I/O exception
throw new IOException("Delete directory " + dir, ex);
}
}
/**
* Flush any buffered output for the specified file.
*
* @param sess Server session
* @param tree Tree connection
* @param file Network file context.
* @exception java.io.IOException The exception description.
*/
public void flushFile(SrvSession session, TreeConnection tree, NetworkFile file) throws IOException
{
// Debug
ContentContext ctx = (ContentContext) tree.getContext();
if ( logger.isDebugEnabled())
{
logger.debug("Flush file=" + file.getFullName()+ ", session:" + session.getUniqueId());
}
// Flush the file data
file.flushFile();
}
/**
* Close the file.
*
* @param sess Server session
* @param tree Tree connection.
* @param param Network file context.
*
* @exception java.io.IOException If an error occurs.
*/
public void closeFile(SrvSession session, TreeConnection tree, final NetworkFile file) throws IOException
{
throw new AlfrescoRuntimeException("obsolete method called");
}
public void deleteFile(final SrvSession session, final TreeConnection tree, final String name) throws IOException
{
throw new AlfrescoRuntimeException("obsolete method called");
}
/**
* Delete the specified file.
*
* @param sess Server session
* @param tree Tree connection
* @param file NetworkFile
* @exception java.io.IOException The exception description.
* @return NodeRef of deletedFile
*/
public NodeRef deleteFile2(final SrvSession session, final TreeConnection tree, NodeRef rootNode, String path) throws IOException
{
// Get the device context
final ContentContext ctx = (ContentContext) tree.getContext();
if(logger.isDebugEnabled())
{
logger.debug("deleteFile:" + path + ", session:" + session.getUniqueId());
}
try
{
if(session.isPseudoFilesEnabled() && ctx.isPseudoFilesEnabled())
{
String[] paths = FileName.splitPath(path);
// lookup parent directory
NodeRef dirNodeRef = getNodeForPath(tree, paths[0]);
// Check whether we are opening a pseudo file
if(ctx.getPseudoFileOverlay().isPseudoFile(dirNodeRef, paths[1]))
{
return null;
}
}
// Check if there is a quota manager enabled, if so then we need to save the current file size
final QuotaManager quotaMgr = ctx.getQuotaManager();
// Get the node and delete it
final NodeRef nodeRef = getNodeForPath(tree, path);
if (fileFolderService.exists(nodeRef))
{
// Get the size of the file being deleted
final FileInfo fInfo = quotaMgr == null ? null : getFileInformation(session, tree, path);
if(logger.isDebugEnabled())
{
logger.debug("deleted file" + path);
}
fileFolderService.delete(nodeRef);
//TODO Needs to be post-commit
if (quotaMgr != null)
{
quotaMgr.releaseSpace(session, tree, fInfo.getFileId(), path, fInfo.getSize());
}
// Debug
if (logger.isDebugEnabled())
{
logger.debug("Deleted file: " + path + ", nodeRef=" + nodeRef);
}
// void return
return nodeRef;
}
}
catch (NodeLockedException ex)
{
if ( logger.isDebugEnabled())
{
logger.debug("Delete file - access denied (locked)", ex);
}
// Convert to a filesystem access denied status
throw new AccessDeniedException("Unable to delete " + path);
}
catch (org.alfresco.repo.security.permissions.AccessDeniedException ex)
{
// Debug
if ( logger.isDebugEnabled())
{
logger.debug("Delete file - access denied", ex);
}
// Convert to a filesystem access denied status
throw new AccessDeniedException("Unable to delete " + path);
}
catch (IOException ex)
{
// Allow I/O Exceptions to pass through
if ( logger.isDebugEnabled())
{
logger.debug("Delete file error - pass through IO Exception", ex);
}
throw ex;
}
catch (Exception ex)
{
// Debug
if ( logger.isDebugEnabled())
{
logger.debug("Delete file error", ex);
}
// Convert to a general I/O exception
IOException ioe = new IOException("Delete file " + path);
ioe.initCause(ex);
throw ioe;
}
return null;
}
public void renameFile(final SrvSession session, final TreeConnection tree, final String oldName, final String newName)
throws IOException
{
throw new AlfrescoRuntimeException("obsolete method called");
}
/**
* Rename the specified file.
*
* @param rootNode
* @param oldName path/name of old file
* @param newName path/name of new file
* @exception java.io.IOException The exception description.
*/
public void renameFile(NodeRef rootNode, final String oldName, final String newName, boolean soft)
throws IOException
{
if (logger.isDebugEnabled())
{
logger.debug("RenameFile oldName=" + oldName + ", newName=" + newName + ", soft" + soft);
}
try
{
// Get the file/folder to move
final NodeRef nodeToMoveRef = getCifsHelper().getNodeRef(rootNode, oldName);
// Check if the node is a link node
if ( nodeToMoveRef != null && nodeService.getProperty(nodeToMoveRef, ContentModel.PROP_LINK_DESTINATION) != null)
{
throw new AccessDeniedException("Cannot rename link nodes");
}
// Get the new target folder - it must be a folder
String[] splitPaths = FileName.splitPath(newName);
String[] oldPaths = FileName.splitPath(oldName);
final NodeRef targetFolderRef = getCifsHelper().getNodeRef(rootNode, splitPaths[0]);
final NodeRef sourceFolderRef = getCifsHelper().getNodeRef(rootNode, oldPaths[0]);
final String name = splitPaths[1];
// Check if this is a rename within the same folder
final boolean sameFolder = splitPaths[0].equalsIgnoreCase(oldPaths[0]);
// Check if we are renaming a folder, or the rename is to a different folder
boolean isFolder = getCifsHelper().isDirectory(nodeToMoveRef);
if ( isFolder == true || sameFolder == false)
{
// Rename or move the file/folder to another folder
if (sameFolder == true)
{
fileFolderService.rename(nodeToMoveRef, name);
if (logger.isDebugEnabled())
{
logger.debug(" Renamed " + (isFolder ? "folder" : "file") + ":" +
" Old name: " + oldName + "\n" +
" New name: " + newName + "\n" );
}
}
else
{
fileFolderService.moveFrom(nodeToMoveRef, sourceFolderRef, targetFolderRef, name);
logger.debug(
"Moved between different folders: \n" +
" Old name: " + oldName + "\n" +
" New name: " + newName + "\n" +
" Source folder: " + sourceFolderRef + "\n" +
" Target folder: " + targetFolderRef + "\n" +
" Node: " + nodeToMoveRef + "\n" +
" Aspects: " + nodeService.getAspects(nodeToMoveRef));
}
if (logger.isDebugEnabled())
{
logger.debug(" Renamed " + (isFolder ? "folder" : "file") + " using "
+ (sameFolder ? "rename" : "move"));
}
}
else
{
// Rename a file within the same folder
if (logger.isDebugEnabled())
{
logger.debug(
"Rename file within same folder: \n" +
" Old name: " + oldName + "\n" +
" New name: " + newName + "\n" +
" Source folder: " + sourceFolderRef + "\n" +
" Target folder: " + targetFolderRef + "\n" +
" Node: " + nodeToMoveRef + "\n" +
" Aspects: " + nodeService.getAspects(nodeToMoveRef));
}
if(soft)
{
logger.debug("this is a soft delete - use copy rather than rename");
fileFolderService.copy(nodeToMoveRef, null, name);
nodeService.addAspect(nodeToMoveRef, ContentModel.ASPECT_SOFT_DELETE, null);
}
else
{
fileFolderService.rename(nodeToMoveRef, name);
}
}
}
catch (org.alfresco.service.cmr.model.FileNotFoundException e)
{
if (logger.isDebugEnabled())
{
logger.debug("Rename file - about to throw file not exists exception file:" + oldName, e);
}
throw new java.io.FileNotFoundException("renameFile: file not found file: + oldName");
}
catch (org.alfresco.service.cmr.model.FileExistsException e)
{
if (logger.isDebugEnabled())
{
logger.debug("Rename file - about to throw file exists exception", e);
}
throw new org.alfresco.jlan.server.filesys.FileExistsException(newName);
}
catch (org.alfresco.repo.security.permissions.AccessDeniedException ex)
{
if (logger.isDebugEnabled())
{
logger.debug("Rename file - about to throw permissions denied exception", ex);
}
throw new org.alfresco.jlan.server.filesys.PermissionDeniedException("renameFile: No permissions to rename file:" + oldName);
}
catch (NodeLockedException ex)
{
if (logger.isDebugEnabled())
{
logger.debug("Rename file - about to throw access denied exception", ex);
}
// Convert to an filesystem access denied exception
throw new AccessDeniedException("renameFile: Access Denied - Node locked file:" + oldName);
}
catch (AlfrescoRuntimeException ex)
{
if (logger.isDebugEnabled())
{
logger.debug("Rename file about to throw access denied exception", ex);
}
throw new AlfrescoRuntimeException("renameFile failed: \n" +
" Old name: " + oldName + "\n" +
" New name: " + newName + "\n" +
ex);
}
}
/**
* Set file information
*
* @param sess SrvSession
* @param tree TreeConnection
* @param name String
* @param info FileInfo
* @exception IOException
*/
public void setFileInformation(SrvSession sess, final TreeConnection tree, final String name, final FileInfo info) throws IOException
{
// Get the device context
final ContentContext ctx = (ContentContext) tree.getContext();
if (logger.isDebugEnabled())
{
logger.debug("setFileInformation name=" + name + ", info=" + info);
}
NetworkFile networkFile = info.getNetworkFile();
try
{
if(sess.isPseudoFilesEnabled() && ctx.isPseudoFilesEnabled())
{
String[] paths = FileName.splitPath(name);
// lookup parent directory
NodeRef dirNodeRef = getNodeForPath(tree, paths[0]);
// Check whether we are opening a pseudo file
if(ctx.getPseudoFileOverlay().isPseudoFile(dirNodeRef, paths[1]))
{
if(logger.isDebugEnabled())
{
logger.debug("pseudo file so do nothing");
}
return;
}
}
// Get the file/folder node
NodeRef nodeRef = getNodeForPath(tree, name);
// Check permissions on the file/folder node
if ( permissionService.hasPermission(nodeRef, PermissionService.WRITE) == AccessStatus.DENIED)
{
if(logger.isDebugEnabled())
{
logger.debug("write access denied to :" + name);
}
throw new AccessDeniedException("No write access to " + name);
}
// Inhibit versioning for this transaction
getPolicyFilter().disableBehaviour( ContentModel.ASPECT_VERSIONABLE);
// Check if the file is being marked for deletion, if so then check if the file is locked
/*
* Which DeleteOnClose flag has priority?
* SetDeleteOnClose is not set or used in this method.
* The NTProtocolHandler sets the deleteOnClose in both
* info and the NetworkFile - it's the one in NetworkFile that results in the file being deleted.
*/
if ( info.hasSetFlag(FileInfo.SetDeleteOnClose) && info.hasDeleteOnClose())
{
if(logger.isDebugEnabled())
{
logger.debug("Set Delete On Close for :" + name);
}
// Check for delete permission
if ( permissionService.hasPermission(nodeRef, PermissionService.DELETE) == AccessStatus.DENIED)
{
throw new PermissionDeniedException("No delete access to :" + name);
}
// Check if the node is locked
lockService.checkForLock(nodeRef);
// Get the node for the folder
if (fileFolderService.exists(nodeRef))
{
// Check if it is a folder that is being deleted, make sure it is empty
boolean isFolder = true;
ContentFileInfo cInfo = getCifsHelper().getFileInformation(nodeRef, false, isLockedFilesAsOffline);
if ( cInfo != null && cInfo.isDirectory() == false)
{
isFolder = false;
}
// Check if the folder is empty
if ( isFolder == true && getCifsHelper().isFolderEmpty( nodeRef) == false)
{
throw new DirectoryNotEmptyException( name);
}
}
}
if(info.hasSetFlag(FileInfo.SetAttributes))
{
if ( logger.isDebugEnabled())
{
logger.debug("Set attributes" + name + ", file attrs = " + info.getFileAttributes());
}
//TODO MER Think we may need to implement, Temporary, Hidden, System, Archive
if(info.isSystem())
{
logger.debug("Set system aspect (not yet implemented)" + name);
}
if(info.isTemporary())
{
logger.debug("Set temporary aspect (not yet implemented)" + name);
}
if(info.isHidden())
{
// yes is hidden
if ( logger.isDebugEnabled())
{
logger.debug("Set hidden aspect" + name);
}
hiddenAspect.hideNodeExplicit(nodeRef);
}
else
{
// not hidden
if(nodeService.hasAspect(nodeRef, ContentModel.ASPECT_HIDDEN))
{
if ( logger.isDebugEnabled())
{
logger.debug("Reset hidden aspect" + name);
}
hiddenAspect.unhideExplicit(nodeRef);
}
}
} // End of setting attributes
if( info.hasSetFlag(FileInfo.SetAllocationSize))
{
if ( logger.isDebugEnabled())
{
logger.debug("Set allocation size" + name + info.getAllocationSize());
}
// Not yet implemented
}
if( info.hasSetFlag(FileInfo.SetFileSize))
{
if ( logger.isDebugEnabled())
{
logger.debug("Set file size" + name + info.getSize());
}
// Not yet implemented
}
if( info.hasSetFlag(FileInfo.SetMode))
{
if ( logger.isDebugEnabled())
{
logger.debug("Set Mode" + name + info.getMode());
}
// Not yet implemented - set the unix mode e.g. 777
}
// Set the creation and modified date/time
Map<QName, Serializable> auditableProps = new HashMap<QName, Serializable>(5);
if ( info.hasSetFlag(FileInfo.SetCreationDate) && info.hasCreationDateTime())
{
// Set the creation date on the file/folder node
Date createDate = new Date(info.getCreationDateTime());
auditableProps.put(ContentModel.PROP_CREATED, createDate);
if ( logger.isDebugEnabled())
{
logger.debug("Set creation date" + name + ", " + createDate);
}
}
if ( info.hasSetFlag(FileInfo.SetModifyDate) && info.hasModifyDateTime())
{
// Set the modification date on the file/folder node
Date modifyDate = new Date( info.getModifyDateTime());
auditableProps.put(ContentModel.PROP_MODIFIED, modifyDate);
// Set the network file so we don't reverse this change in close file.
if(networkFile != null && !networkFile.isReadOnly())
{
networkFile.setModifyDate(info.getModifyDateTime());
if(networkFile instanceof TempNetworkFile)
{
TempNetworkFile tnf = (TempNetworkFile)networkFile;
tnf.setModificationDateSetDirectly(true);
}
}
if ( logger.isDebugEnabled())
{
logger.debug("Set modification date" + name + ", " + modifyDate);
}
}
// Change Date is last write ?
if ( info.hasSetFlag(FileInfo.SetChangeDate) && info.hasChangeDateTime())
{
Date changeDate = new Date( info.getChangeDateTime());
if ( logger.isDebugEnabled())
{
logger.debug("Set change date (Not implemented)" + name + ", " + changeDate);
}
}
if ( info.hasSetFlag(FileInfo.SetAccessDate) && info.hasAccessDateTime())
{
Date accessDate = new Date( info.getAccessDateTime());
if ( logger.isDebugEnabled())
{
logger.debug("Set access date (Not implemented)" + name + ", " + accessDate);
}
}
// Did we have any cm:auditable properties?
if (auditableProps.size() > 0)
{
getPolicyFilter().disableBehaviour(nodeRef, ContentModel.ASPECT_AUDITABLE);
nodeService.addProperties(nodeRef, auditableProps);
// DEBUG
if ( logger.isDebugEnabled())
{
logger.debug("Set auditable props: " + auditableProps + " file=" + name);
}
}
return;
}
catch (org.alfresco.repo.security.permissions.AccessDeniedException ex)
{
if ( logger.isDebugEnabled())
{
logger.debug("Set file information - access denied, " + name);
}
// Convert to a filesystem access denied status
throw new AccessDeniedException("Set file information " + name);
}
catch (AlfrescoRuntimeException ex)
{
if ( logger.isDebugEnabled())
{
logger.debug("Open file error", ex);
}
// Convert to a general I/O exception
throw new IOException("Set file information " + name, ex);
}
}
/**
* Truncate a file to the specified size
*
* @param sess Server session
* @param tree Tree connection
* @param file Network file details
* @param size New file length
* @exception java.io.IOException The exception description.
*/
public void truncateFile(SrvSession sess, TreeConnection tree, NetworkFile file, long size) throws IOException
{
// Keep track of the allocation/release size in case the file resize fails
ContentContext ctx = (ContentContext) tree.getContext();
if (logger.isDebugEnabled())
{
logger.debug("truncateFile file:" + file + ", size: "+ size);
}
long allocSize = 0L;
long releaseSize = 0L;
// Check if there is a quota manager
QuotaManager quotaMgr = ctx.getQuotaManager();
if ( ctx.hasQuotaManager()) {
// Check if the file content has been opened, we need the content to be opened to get the
// current file size
if ( file instanceof ContentNetworkFile) {
ContentNetworkFile contentFile = (ContentNetworkFile) file;
if ( contentFile.hasContent() == false)
{
contentFile.openContent( false, false);
}
}
else if( file instanceof TempNetworkFile)
{
}
else
{
throw new IOException("Invalid file class type, " + file.getClass().getName());
}
// Determine if the new file size will release space or require space allocating
if ( size > file.getFileSize())
{
// Calculate the space to be allocated
allocSize = size - file.getFileSize();
// Allocate space to extend the file
quotaMgr.allocateSpace(sess, tree, file, allocSize);
}
else
{
// Calculate the space to be released as the file is to be truncated, release the space if
// the file truncation is successful
releaseSize = file.getFileSize() - size;
}
}
// Check if this is a file extend, update the cached allocation size if necessary
if ( file instanceof ContentNetworkFile) {
// Get the cached state for the file
ContentNetworkFile contentFile = (ContentNetworkFile) file;
FileState fstate = contentFile.getFileState();
if ( fstate != null && size > fstate.getAllocationSize())
{
fstate.setAllocationSize(size);
}
}
if( file instanceof TempNetworkFile)
{
TempNetworkFile contentFile = (TempNetworkFile) file;
FileState fstate = contentFile.getFileState();
if ( fstate != null && size > fstate.getAllocationSize())
{
fstate.setAllocationSize(size);
}
}
// Set the file length
try
{
file.truncateFile(size);
}
catch (IOException ex)
{
if(logger.isDebugEnabled())
{
logger.debug("unable to truncate the file + :" + file.getFullName(), ex);
}
// Check if we allocated space to the file
if ( allocSize > 0 && quotaMgr != null)
{
quotaMgr.releaseSpace(sess, tree, file.getFileId(), null, allocSize);
}
// Rethrow the exception
throw ex;
}
// Check if space has been released by the file resizing
if ( releaseSize > 0 && quotaMgr != null)
{
quotaMgr.releaseSpace(sess, tree, file.getFileId(), null, releaseSize);
}
// Debug
if (logger.isDebugEnabled())
{
logger.debug("Truncated file: network file=" + file + " size=" + size);
}
}
/**
* Read a block of data from the specified file.
*
* @param sess Session details
* @param tree Tree connection
* @param file Network file
* @param buf Buffer to return data to
* @param bufPos Starting position in the return buffer
* @param siz Maximum size of data to return
* @param filePos File offset to read data
* @return Number of bytes read
* @exception java.io.IOException The exception description.
*/
public int readFile(
SrvSession sess, TreeConnection tree, NetworkFile file,
byte[] buffer, int bufferPosition, int size, long fileOffset) throws IOException
{
// Check if the file is a directory
if(readLogger.isDebugEnabled())
{
readLogger.debug("read File:" + file + ", size" + size);
}
if(file.isDirectory())
{
if(logger.isDebugEnabled())
{
logger.debug("read file called for a directory - throw AccessDeniedException");
}
throw new AccessDeniedException("read called for a directory");
}
// Read a block of data from the file
int count = file.readFile(buffer, size, bufferPosition, fileOffset);
if ( count == -1)
{
// Read count of -1 indicates a read past the end of file
count = 0;
}
// Debug
//ContentContext ctx = (ContentContext) tree.getContext();
if (readLogger.isDebugEnabled())
{
readLogger.debug("Read bytes from file: network file=" + file + " buffer size=" + buffer.length + " buffer pos=" + bufferPosition +
" size=" + size + " file offset=" + fileOffset + " bytes read=" + count);
}
return count;
}
/**
* Seek to the specified file position.
*
* @param sess Server session
* @param tree Tree connection
* @param file Network file.
* @param pos Position to seek to.
* @param typ Seek type.
* @return New file position, relative to the start of file.
*/
public long seekFile(SrvSession sess, TreeConnection tree, NetworkFile file, long pos, int typ) throws IOException
{
if(logger.isDebugEnabled())
{
logger.debug("seek File");
}
// Check if the file is a directory
if ( file.isDirectory())
{
throw new AccessDeniedException();
}
// Set the file position
return file.seekFile(pos, typ);
}
/**
* Write a block of data to the file.
*
* @param sess Server session
* @param tree Tree connection
* @param file Network file details
* @param buf byte[] Data to be written
* @param bufoff Offset within the buffer that the data starts
* @param siz int Data length
* @param fileoff Position within the file that the data is to be written.
* @return Number of bytes actually written
* @exception java.io.IOException The exception description.
*/
public int writeFile(SrvSession sess, TreeConnection tree, NetworkFile file,
byte[] buffer, int bufferOffset, int size, long fileOffset) throws IOException
{
if(writeLogger.isDebugEnabled())
{
writeLogger.debug("write File:" + file + " size:" + size);
}
// Check if there is a quota manager
ContentContext ctx = (ContentContext) tree.getContext();
QuotaManager quotaMgr = ctx.getQuotaManager();
long curSize = file.getFileSize();
if ( quotaMgr != null)
{
// Check if the file requires extending
long extendSize = 0L;
long endOfWrite = fileOffset + size;
if ( endOfWrite > curSize)
{
// Calculate the amount the file must be extended
extendSize = endOfWrite - file.getFileSize();
// Allocate space for the file extend
if(writeLogger.isDebugEnabled())
{
writeLogger.debug("writeFile: allocate more space fileName:" + file.getName() + ", extendTo:"+ extendSize);
}
long alloc = quotaMgr.allocateSpace(sess, tree, file, extendSize);
if(file instanceof TempNetworkFile)
{
TempNetworkFile tnf = (TempNetworkFile)file;
FileState fstate = tnf.getFileState();
if(fstate != null)
{
fstate.setAllocationSize(alloc);
}
}
}
}
// Write to the file
file.writeFile(buffer, size, bufferOffset, fileOffset);
// Check if the file size was reduced by the write, may have been extended previously
if ( quotaMgr != null)
{
// Check if the file size reduced
if ( file.getFileSize() < curSize)
{
// Release space that was freed by the write
quotaMgr.releaseSpace( sess, tree, file.getFileId(), file.getFullName(), curSize - file.getFileSize());
}
}
// Debug
if (writeLogger.isDebugEnabled())
{
writeLogger.debug("Wrote bytes to file: network file=" + file + " buffer size=" + buffer.length + " size=" + size + " file offset=" + fileOffset);
}
return size;
}
/**
* Get the node for the specified path
*
* @param tree TreeConnection
* @param path String
* @return NodeRef
* @exception FileNotFoundException
*/
private NodeRef getNodeForPath(TreeConnection tree, String path)
throws FileNotFoundException
{
ContentContext ctx = (ContentContext) tree.getContext();
return getCifsHelper().getNodeRef(ctx.getRootNode(), path);
}
/**
* Get the node for the specified path
*
* @param tree TreeConnection
* @param path String
* @return NodeRef
* @exception FileNotFoundException
*/
public NodeRef getNodeForPath(NodeRef rootNode, String path)
throws FileNotFoundException
{
if(logger.isDebugEnabled())
{
logger.debug("getNodeRefForPath:" + path);
}
return getCifsHelper().getNodeRef(rootNode, path);
}
/**
* Convert a node into a share relative path
*
* @param tree TreeConnection
* @param nodeRef NodeRef
* @return String
* @exception FileNotFoundException
*/
// private String getPathForNode( TreeConnection tree, NodeRef nodeRef)
// throws FileNotFoundException
// {
// // Convert the target node to a path
// ContentContext ctx = (ContentContext) tree.getContext();
//
// return getPathForNode(ctx.getRootNode(), nodeRef);
//
// }
//
/**
* Convert a node into a share relative path
*
* @param tree rootNode
* @param nodeRef NodeRef
* @return String
* @exception FileNotFoundException
*/
private String getPathForNode( NodeRef rootNode, NodeRef nodeRef)
throws FileNotFoundException
{
if(logger.isDebugEnabled())
{
logger.debug("getPathForNode:" + nodeRef);
}
List<org.alfresco.service.cmr.model.FileInfo> linkPaths = null;
try
{
linkPaths = fileFolderService.getNamePath( rootNode, nodeRef);
}
catch ( org.alfresco.service.cmr.model.FileNotFoundException ex)
{
throw new FileNotFoundException();
}
// Build the share relative path to the node
StringBuilder pathStr = new StringBuilder();
for ( org.alfresco.service.cmr.model.FileInfo fInfo : linkPaths)
{
pathStr.append( FileName.DOS_SEPERATOR);
pathStr.append( fInfo.getName());
}
// Return the share relative path
return pathStr.toString();
}
/**
* Return the lock manager used by this filesystem
*
* @param sess SrvSession
* @param tree TreeConnection
* @return LockManager
*/
public LockManager getLockManager(SrvSession sess, TreeConnection tree)
{
AlfrescoContext alfCtx = (AlfrescoContext) tree.getContext();
return alfCtx.getLockManager();
}
/**
* Disk Size Interface implementation
*/
private interface DiskSizeInterfaceConsts
{
static final int DiskBlockSize = 512; // bytes per block
static final long DiskAllocationUnit = 32 * MemorySize.KILOBYTE;
static final long DiskBlocksPerUnit = DiskAllocationUnit / DiskBlockSize;
// Disk size returned in the content store does not support free/total size
static final long DiskSizeDefault = 1 * MemorySize.TERABYTE;
static final long DiskFreeDefault = DiskSizeDefault / 2;
}
/**
* Get the disk information for this shared disk device.
*
* @param ctx DiskDeviceContext
* @param diskDev SrvDiskInfo
* @exception IOException
*/
public void getDiskInformation(DiskDeviceContext ctx, SrvDiskInfo diskDev) throws IOException
{
if(logger.isDebugEnabled())
{
logger.debug("getDiskInformation");
}
// Set the block size and blocks per allocation unit
diskDev.setBlockSize( DiskSizeInterfaceConsts.DiskBlockSize);
diskDev.setBlocksPerAllocationUnit( DiskSizeInterfaceConsts.DiskBlocksPerUnit);
// Get the free and total disk size in bytes from the content store
long freeSpace = contentService.getStoreFreeSpace();
long totalSpace= contentService.getStoreTotalSpace();
if ( totalSpace == -1L) {
// Use a fixed value for the total space, content store does not support size information
totalSpace = DiskSizeInterfaceConsts.DiskSizeDefault;
freeSpace = DiskSizeInterfaceConsts.DiskFreeDefault;
}
// Convert the total/free space values to allocation units
diskDev.setTotalUnits( totalSpace / DiskSizeInterfaceConsts.DiskAllocationUnit);
diskDev.setFreeUnits( freeSpace / DiskSizeInterfaceConsts.DiskAllocationUnit);
if(logger.isDebugEnabled())
{
logger.debug("getDiskInformation returning diskDev:" + diskDev);
}
}
public void setCifsHelper(CifsHelper cifsHelper)
{
this.cifsHelper = cifsHelper;
}
@Override
public void treeOpened(SrvSession sess, TreeConnection tree)
{
// Nothing to do
}
@Override
public void treeClosed(SrvSession sess, TreeConnection tree)
{
// Nothing to do
}
// Implementation of IOCtlInterface
/**
* Process a filesystem I/O control request
*
* @param sess Server session
* @param tree Tree connection.
* @param ctrlCode I/O control code
* @param fid File id
* @param dataBuf I/O control specific input data
* @param isFSCtrl true if this is a filesystem control, or false for a device control
* @param filter if bit0 is set indicates that the control applies to the share root handle
* @return DataBuffer
* @exception IOControlNotImplementedException
* @exception SMBException
*/
public org.alfresco.jlan.util.DataBuffer processIOControl(SrvSession sess, TreeConnection tree, int ctrlCode, int fid, DataBuffer dataBuf,
boolean isFSCtrl, int filter)
throws IOControlNotImplementedException, SMBException
{
// Validate the file id
if(logger.isDebugEnabled())
{
logger.debug("processIOControl ctrlCode: 0x" + Integer.toHexString(ctrlCode) + ", fid:" + fid);
}
final ContentContext ctx = (ContentContext) tree.getContext();
try
{
org.alfresco.jlan.util.DataBuffer buff = ioControlHandler.processIOControl(sess, tree, ctrlCode, fid, dataBuf, isFSCtrl, filter, this, ctx);
return buff;
}
catch(SMBException smbException)
{
if(logger.isDebugEnabled())
{
logger.debug("SMB Exception fid:" + fid, smbException);
}
throw smbException;
}
catch(IOControlNotImplementedException ioException)
{
if(logger.isDebugEnabled())
{
logger.debug("IO Control Not Implemented Exception fid:" + fid, ioException);
}
throw ioException;
}
}
public void setCheckOutCheckInService(CheckOutCheckInService service)
{
this.checkOutCheckInService = service;
}
/**
* @return the service to provide check-in and check-out data
*/
public final CheckOutCheckInService getCheckOutCheckInService()
{
return checkOutCheckInService;
}
// Implementation of RepositoryDiskInterface
@Override
public void copyContent(NodeRef rootNode, String fromPath, String toPath) throws FileNotFoundException
{
if(logger.isDebugEnabled())
{
logger.debug("copyContent from:" + fromPath + " to:" + toPath);
}
NodeRef sourceNodeRef = getNodeForPath(rootNode, fromPath);
NodeRef targetNodeRef = getNodeForPath(rootNode, toPath);
Serializable prop = nodeService.getProperty(sourceNodeRef, ContentModel.PROP_CONTENT);
if(prop != null)
{
if(prop instanceof ContentData)
{
ContentData data = (ContentData)prop;
if(data.getMimetype().equalsIgnoreCase(MimetypeMap.MIMETYPE_BINARY))
{
if(logger.isDebugEnabled())
{
logger.debug("mimetype is binary - guess mimetype has failed");
}
Serializable targetProp = nodeService.getProperty(targetNodeRef, ContentModel.PROP_CONTENT);
if(targetProp != null && targetProp instanceof ContentData)
{
ContentData targetData = (ContentData)targetProp;
logger.debug("copy the existing mimetype");
prop = ContentData.setMimetype(data, targetData.getMimetype());
}
}
}
nodeService.setProperty(targetNodeRef, ContentModel.PROP_CONTENT, prop);
}
else
{
// No content to set
logger.debug("no content to save");
}
}
@Override
public NetworkFile createFile(NodeRef rootNode, String path, long allocationSize)
throws IOException
{
if (logger.isDebugEnabled())
{
logger.debug("createFile :" + path);
}
try
{
NodeRef dirNodeRef;
String folderName;
String[] paths = FileName.splitPath(path);
if (paths[0] != null && paths[0].length() > 1)
{
// lookup parent directory
dirNodeRef = getNodeForPath(rootNode, paths[0]);
folderName = paths[1];
}
else
{
dirNodeRef = rootNode;
folderName = path;
}
boolean soft = false;
NodeRef existing = fileFolderService.searchSimple(dirNodeRef, folderName);
if (existing != null)
{
if(nodeService.hasAspect(existing, ContentModel.ASPECT_SOFT_DELETE))
{
logger.debug("existing node has soft delete aspect");
soft = true;
}
}
NodeRef nodeRef = null;
if(soft)
{
nodeRef = existing;
}
else
{
nodeRef = cifsHelper.createNode(dirNodeRef, folderName, ContentModel.TYPE_CONTENT);
nodeService.addAspect(nodeRef, ContentModel.ASPECT_NO_CONTENT, null);
}
File file = TempFileProvider.createTempFile("cifs", ".bin");
TempNetworkFile netFile = new TempNetworkFile(file, path);
netFile.setChanged(true);
Serializable created = nodeService.getProperty(nodeRef, ContentModel.PROP_CREATED);
if(created != null && created instanceof Date)
{
Date d = (Date)created;
if(logger.isDebugEnabled())
{
logger.debug("replacing create date to date:" + d);
}
netFile.setCreationDate(d.getTime());
netFile.setModifyDate(d.getTime());
}
// Always allow write access to a newly created file
netFile.setGrantedAccess(NetworkFile.READWRITE);
netFile.setAllowedAccess(NetworkFile.READWRITE);
// Generate a file id for the file
if ( netFile != null)
{
long id = DefaultTypeConverter.INSTANCE.convert(Long.class, nodeService.getProperty(nodeRef, ContentModel.PROP_NODE_DBID));
netFile.setFileId((int) (id & 0xFFFFFFFFL));
}
if (logger.isDebugEnabled())
{
logger.debug("Created file: path=" + path + " node=" + nodeRef + " network file=" + netFile);
}
// Return the new network file
return netFile;
}
catch (org.alfresco.repo.security.permissions.AccessDeniedException ex)
{
// Debug
if ( logger.isDebugEnabled())
{
logger.debug("Create file - access denied, " + path);
}
// Convert to a filesystem access denied status
throw new AccessDeniedException("Unable to create file " + path);
}
catch (IOException ex)
{
// Debug
if ( logger.isDebugEnabled())
{
logger.debug("Create file - content I/O error, " + path);
}
throw ex;
}
catch (ContentIOException ex)
{
// Debug
if ( logger.isDebugEnabled())
{
logger.debug("Create file - content I/O error, " + path);
}
// Convert to a filesystem disk full status
throw new DiskFullException("Unable to create file " + path);
}
catch (AlfrescoRuntimeException ex)
{
// Debug
if ( logger.isDebugEnabled())
{
logger.debug("Create file error", ex);
}
// Convert to a general I/O exception
throw new IOException("Unable to create file " + path, ex);
}
}
/**
* Open the file - Repo Specific implementation
*/
public NetworkFile openFile(SrvSession session, TreeConnection tree, NodeRef rootNode, String path, OpenFileMode mode, boolean truncate) throws IOException
{
ContentContext ctx = (ContentContext) tree.getContext();
if(logger.isDebugEnabled())
{
logger.debug("openFile :" + path + ", mode:" + mode );
}
try
{
String name = path;
if(session.isPseudoFilesEnabled() && ctx.isPseudoFilesEnabled())
{
String[] paths = FileName.splitPath(name);
// lookup parent directory
NodeRef dirNodeRef = getNodeForPath(rootNode, paths[0]);
// Check whether we are opening a pseudo file
if(ctx.getPseudoFileOverlay().isPseudoFile(dirNodeRef, paths[1]))
{
PseudoFile pfile = ctx.getPseudoFileOverlay().getPseudoFile(dirNodeRef, paths[1]);
if(logger.isDebugEnabled())
{
logger.debug("Opened pseudo file :" + pfile);
}
return pfile.getFile( path);
}
}
// not a psudo file
NodeRef nodeRef = getNodeForPath(rootNode, path);
boolean readOnly=false;
// Check permissions on the file/folder
switch(mode)
{
case READ_ONLY:
// follow through
case ATTRIBUTES_ONLY:
if(permissionService.hasPermission(nodeRef, PermissionService.READ) == AccessStatus.DENIED)
{
if(logger.isDebugEnabled())
{
logger.debug("about to throw an no read access denied exception path:" +path);
}
throw new AccessDeniedException("No read access to " + path);
}
readOnly = true;
break;
case READ_WRITE:
case WRITE_ONLY:
if(permissionService.hasPermission(nodeRef, PermissionService.WRITE) == AccessStatus.DENIED)
{
if(logger.isDebugEnabled())
{
logger.debug("about to throw an no write access denied exception path:" + path);
}
throw new AccessDeniedException("No write access to " + path);
}
lockService.checkForLock(nodeRef);
readOnly=false;
break;
case DELETE:
lockService.checkForLock(nodeRef);
}
// Check if the node is a link node
NodeRef linkRef = (NodeRef) nodeService.getProperty(nodeRef, ContentModel.PROP_LINK_DESTINATION);
NetworkFile netFile = null;
if ( linkRef == null)
{
// A normal node, not a link node
// TODO MER REWRITE HERE
FileInfo fileInfo = cifsHelper.getFileInformation(nodeRef, "", false, false);
// TODO this is wasteful - the isDirectory is in the params. We should split off an openDirectory method.
if(fileInfo.isDirectory())
{
logger.debug("open file - is a directory!");
netFile = new AlfrescoFolder(path, fileInfo, readOnly);
}
else
{
// A normal file
switch (mode)
{
case READ_ONLY:
logger.debug("open file for read only");
netFile = ContentNetworkFile.createFile(nodeService, contentService, mimetypeService, getCifsHelper(), nodeRef, path, true, false, session);
netFile.setGrantedAccess( NetworkFile.READONLY);
break;
case READ_WRITE:
{
logger.debug("open file for read write");
File file = TempFileProvider.createTempFile("cifs", ".bin");
if(!truncate)
{
// Need to open a temp file with a copy of the content.
ContentReader reader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
if(reader != null)
{
reader.getContent(file);
}
}
netFile = new TempNetworkFile(file, name);
netFile.setCreationDate(fileInfo.getCreationDateTime());
netFile.setModifyDate(fileInfo.getModifyDateTime());
netFile.setGrantedAccess( NetworkFile.READWRITE);
if(truncate)
{
netFile.truncateFile(0);
}
if (logger.isDebugEnabled())
{
logger.debug("Created file: path=" + name + " node=" + nodeRef + " network file=" + netFile);
}
}
break;
case ATTRIBUTES_ONLY:
logger.debug("open file for attributes only");
netFile = ContentNetworkFile.createFile(nodeService, contentService, mimetypeService, getCifsHelper(), nodeRef, path, true, true, session);
netFile.setGrantedAccess( NetworkFile.READONLY);
break;
case DELETE:
//TODO Not sure about this one.
logger.debug("open file for delete");
netFile = ContentNetworkFile.createFile(nodeService, contentService, mimetypeService, getCifsHelper(), nodeRef, path, true, false, session);
netFile.setGrantedAccess( NetworkFile.READONLY);
break;
case WRITE_ONLY:
{
// consider this as open read/write/truncate)
logger.debug("open file write only");
File file = TempFileProvider.createTempFile("cifs", ".bin");
netFile = new TempNetworkFile(file, name);
// Needs to be READWRITE for JavaNetworkFile - there's no such thing as WRITEONLY!
netFile.setGrantedAccess( NetworkFile.READWRITE);
if (logger.isDebugEnabled())
{
logger.debug("Created temporary file: path=" + name + " node=" + nodeRef + " network file=" + netFile);
}
}
}
} // end of a normal file
}
else
{
// This is a link node
// TODO - This server name stuff should be replaced In particular the
// See PseudoFileOverlayImp
// Get the CIFS server name
String srvName = null;
SMBServer cifsServer = (SMBServer) session.getServer().getConfiguration().findServer( "CIFS");
if ( cifsServer != null)
{
// Use the CIFS server name in the URL
srvName = cifsServer.getServerName();
}
else
{
// Use the local server name in the URL
srvName = InetAddress.getLocalHost().getHostName();
}
// Convert the target node to a path, convert to URL format
String pathl = getPathForNode( rootNode, linkRef);
path = pathl.replace( FileName.DOS_SEPERATOR, '/');
// Build the URL file data
StringBuilder urlStr = new StringBuilder();
urlStr.append("[InternetShortcut]\r\n");
urlStr.append("URL=file://");
urlStr.append( srvName);
urlStr.append("/");
urlStr.append( tree.getSharedDevice().getName());
urlStr.append( path);
urlStr.append("\r\n");
// Create the in memory pseudo file for the URL link
byte[] urlData = urlStr.toString().getBytes();
// Get the file information for the link node
FileInfo fInfo = getCifsHelper().getFileInformation( nodeRef, false, isLockedFilesAsOffline);
// Set the file size to the actual data length
fInfo.setFileSize( urlData.length);
// Create the network file using the in-memory file data
netFile = new LinkMemoryNetworkFile( fInfo.getFileName(), urlData, fInfo, nodeRef);
netFile.setFullName( path);
}
// Generate a file id for the file
if ( netFile != null)
{
long id = DefaultTypeConverter.INSTANCE.convert(Long.class, nodeService.getProperty(nodeRef, ContentModel.PROP_NODE_DBID));
netFile.setFileId(( int) ( id & 0xFFFFFFFFL));
// Indicate the file is open
netFile.setClosed( false);
}
if (logger.isDebugEnabled())
{
logger.debug("Opened network file: path=" + path + " network file=" + netFile);
}
// Return the network file
return netFile;
}
catch (NodeLockedException nle)
{
if ( logger.isDebugEnabled())
{
logger.debug("Open file - node is locked, " + path);
}
throw new AccessDeniedException("File is locked, no write access to " + path);
}
catch (org.alfresco.repo.security.permissions.AccessDeniedException ex)
{
// Debug
if ( logger.isDebugEnabled())
{
logger.debug("Open file - access denied, " + path);
}
// Convert to a filesystem access denied status
throw new AccessDeniedException("Open file " + path);
}
catch (AlfrescoRuntimeException ex)
{
// Debug
if (logger.isDebugEnabled())
{
logger.debug("Open file error", ex);
}
// Convert to a general I/O exception
throw new IOException("Open file " + path, ex);
}
}
/**
* Close the file.
*
* @exception java.io.IOException If an error occurs.
* @return node ref of deleted file
*/
public NodeRef closeFile(NodeRef rootNode, String path, NetworkFile file) throws IOException
{
if ( logger.isDebugEnabled())
{
logger.debug("Close file:" + path + ", readOnly=" + file.isReadOnly() );
}
if( file instanceof PseudoNetworkFile)
{
file.close();
return null;
}
/**
* Delete on close attribute - node needs to be deleted.
*/
if(file.hasDeleteOnClose())
{
NodeRef target = null;
if(logger.isDebugEnabled())
{
logger.debug("closeFile has delete on close set path:" + path);
}
try
{
target = getCifsHelper().getNodeRef(rootNode, path);
if(target!=null)
{
nodeService.deleteNode(target);
}
}
catch (org.alfresco.repo.security.permissions.AccessDeniedException ex)
{
if ( logger.isDebugEnabled())
{
logger.debug("Delete file from close file- access denied", ex);
}
// Convert to a filesystem access denied status
throw new AccessDeniedException("Unable to delete " + path);
}
// Still need to close the open file handle.
file.close();
if (logger.isDebugEnabled())
{
logger.debug("Closed file: network file=" + file + " delete on close=" + file.hasDeleteOnClose());
}
return target;
}
// Check for a temp file - which will be a new file or a read/write file
if ( file instanceof TempNetworkFile)
{
if(logger.isDebugEnabled())
{
logger.debug("Got a temp network file to close path:" + path);
}
// Some content was written to the temp file.
TempNetworkFile tempFile =(TempNetworkFile)file;
NodeRef target = getCifsHelper().getNodeRef(rootNode, tempFile.getFullName());
if(nodeService.hasAspect(target, ContentModel.ASPECT_NO_CONTENT))
{
if(logger.isDebugEnabled())
{
logger.debug("removed no content aspect");
}
nodeService.removeAspect(target, ContentModel.ASPECT_NO_CONTENT);
}
if(tempFile.isChanged())
{
tempFile.flushFile();
tempFile.close();
/*
* Need to work out whether content has changed. Some odd situations do not change content.
*/
boolean contentChanged = true;
ContentReader existingContent = contentService.getReader(target, ContentModel.PROP_CONTENT);
if(existingContent != null)
{
existingContent.getSize();
existingContent.getMimetype();
contentChanged = isContentChanged(existingContent, tempFile);
/*
* MNT-248 fix
* No need to create a version of a zero byte file
*/
if (file.getFileSize() > 0 && existingContent.getSize() == 0 && nodeService.hasAspect(target, ContentModel.ASPECT_VERSIONABLE))
{
getPolicyFilter().disableBehaviour(target, ContentModel.ASPECT_VERSIONABLE);
}
}
if(contentChanged)
{
logger.debug("content has changed, need to create a new content item");
/**
* Take over the behaviour of the auditable aspect
*/
getPolicyFilter().disableBehaviour(target, ContentModel.ASPECT_AUDITABLE);
nodeService.setProperty(target, ContentModel.PROP_MODIFIER, authService.getCurrentUserName());
if(tempFile.isModificationDateSetDirectly())
{
logger.debug("modification date set directly");
nodeService.setProperty(target, ContentModel.PROP_MODIFIED, new Date(tempFile.getModifyDate()));
}
else
{
logger.debug("modification date not set directly");
nodeService.setProperty(target, ContentModel.PROP_MODIFIED, new Date());
}
// Take an initial guess at the mimetype (if it has not been set by something already)
String mimetype = mimetypeService.guessMimetype(tempFile.getFullName(), new FileContentReader(tempFile.getFile()));
logger.debug("guesssed mimetype:" + mimetype);
String encoding;
// Take a guess at the locale
InputStream is = new BufferedInputStream(new FileInputStream(tempFile.getFile()));
try
{
ContentCharsetFinder charsetFinder = mimetypeService.getContentCharsetFinder();
Charset charset = charsetFinder.getCharset(is, mimetype);
encoding = charset.name();
}
finally
{
if(is != null)
{
try
{
is.close();
}
catch (IOException e)
{
// Ignore
}
}
}
ContentWriter writer = contentService.getWriter(target, ContentModel.PROP_CONTENT, true);
writer.setMimetype(mimetype);
writer.setEncoding(encoding);
writer.putContent(tempFile.getFile());
} // if content changed
}
}
try
{
// Defer to the network file to close the stream and remove the content
file.close();
// DEBUG
if (logger.isDebugEnabled())
{
logger.debug("Closed file: network file=" + file + " delete on close=" + file.hasDeleteOnClose() + ", write count" + file.getWriteCount());
if ( file.hasDeleteOnClose() == false && file instanceof ContentNetworkFile)
{
ContentNetworkFile cFile = (ContentNetworkFile) file;
logger.debug(" File " + file.getFullName() + ", version=" + nodeService.getProperty( cFile.getNodeRef(), ContentModel.PROP_VERSION_LABEL));
}
}
return null;
}
catch (IOException e)
{
if ( logger.isDebugEnabled())
{
logger.debug("Exception in closeFile - path:" + path, e);
}
throw new IOException("Unable to closeFile :" + path + e.toString(), e);
}
catch (Error e)
{
if ( logger.isDebugEnabled())
{
logger.debug("Exception in closeFile - path:" + path, e);
}
throw e;
}
}
/**
*
* @param session
* @param tree
* @param file
*/
public void reduceQuota(SrvSession session, TreeConnection tree, NetworkFile file)
{
if(file.hasDeleteOnClose())
{
final ContentContext ctx = (ContentContext) tree.getContext();
if(logger.isDebugEnabled())
{
logger.debug("closeFile has delete on close set");
}
if(file instanceof TempNetworkFile)
{
TempNetworkFile tnf = (TempNetworkFile)file;
final QuotaManager quotaMgr = ctx.getQuotaManager();
if (quotaMgr != null)
{
try
{
quotaMgr.releaseSpace(session, tree, file.getFileId(), file.getName(), tnf.getFileSizeInt());
}
catch (IOException e)
{
logger.error(e);
}
}
}
}
}
public void deleteEmptyFile(NodeRef rootNode, String path)
{
try
{
NodeRef target = getCifsHelper().getNodeRef(rootNode, path);
if(target!=null)
{
if (nodeService.hasAspect(target, ContentModel.ASPECT_NO_CONTENT))
{
nodeService.deleteNode(target);
}
}
}
catch(IOException ne)
{
// Do nothing
if ( logger.isDebugEnabled())
{
logger.debug("Unable to delete empty file:" + path, ne);
}
}
}
@Override
public OpLockManager getOpLockManager(SrvSession sess, TreeConnection tree)
{
AlfrescoContext alfCtx = (AlfrescoContext) tree.getContext();
return alfCtx.getOpLockManager();
}
@Override
public boolean isOpLocksEnabled(SrvSession sess, TreeConnection tree)
{
if(getOpLockManager(sess, tree) != null)
{
return true;
}
return false;
}
/**
* Compare the content for significant changes. For example Project and Excel play with headers,
* which should not result in new versions being created.
* @param existingContent
* @param newFile
* @return true the content has changed, false the content has not changed significantly.
*/
private boolean isContentChanged(ContentReader existingContent, TempNetworkFile newFile)
{
return !contentComparator.isContentEqual(existingContent, newFile.getFile());
}
public void setContentComparator(ContentComparator contentComparator)
{
this.contentComparator = contentComparator;
}
public ContentComparator getContentComparator()
{
return contentComparator;
}
@Override
public NetworkFile restoreFile(
SrvSession sess,
TreeConnection tree,
NodeRef rootNode,
String path,
long allocationSize,
NodeRef originalNodeRef) throws IOException
{
// First attempt to restore the node
if(logger.isDebugEnabled())
{
logger.debug("restore node:" + originalNodeRef + ", path:" + path);
}
NodeRef archivedNodeRef = getNodeArchiveService().getArchivedNode(originalNodeRef);
RestoreNodeReport report = getNodeArchiveService().restoreArchivedNode(archivedNodeRef);
if(report.getStatus().isSuccess())
{
NodeRef newNodeRef = report.getRestoredNodeRef();
if (logger.isDebugEnabled())
{
logger.debug("node has been restored");
}
return openFile(sess, tree, rootNode, path, OpenFileMode.READ_WRITE, true);
}
else
{
return createFile(rootNode, path, allocationSize);
}
}
public void setNodeArchiveService(NodeArchiveService nodeArchiveService)
{
this.nodeArchiveService = nodeArchiveService;
}
public NodeArchiveService getNodeArchiveService()
{
return nodeArchiveService;
}
}