Dave Ward 6ebc200a0e Merged V3.4-TEAM to HEAD
26804: Fixed line endings and removed sundry svn:mime-type properties after merge rev 26779
   26805: Merged BRANCHES/V3.4/ to BRANCHES/V3.4-TEAM:
      26803: Fixes: ALF-8138, adds a i18n property for a ToDo list's attachment title.
   26817: Fixes: ALF-7813 - Mini Calendar now highlights all events rather than only the ones valid for the current view.
   26821: Fixed ALF-7889: Auditable data should not change during archive and restore
    - NodeService archive (private method) and restore (public method) switch off cm:auditable behaviour
    - This is system-wide and not configurable
   26823: ALF-8152 - Simple view: incorrect file type icon
   26826: GDoc: Collections are now being correctly created in GDoc when document is checked out
   
   26829: Change initial load event back to onContentReady to keep Firefox & Firebug happy.
   26830: ALF-8151 - Filetype icon or is incorrectly displayed at the Content I'm editing dashlet. (Copied mappings across from alfresco.js)
   26833: Fixed ALF-8060 "Collaborator can't edit created links by other users"
   26836: Fix for ALF-8126
   26837: Fixes ALF-8124: Override default BitRock NLS readme strings
   26840: Fixed ALF-8127 "Inconsistence between Create and Edit user page"
   26841: Fix for ALF-1044. (Searching for groups whose names contain regex reserved chars.)
     The fix was to add [] as reserved chars to the RegEx SimpleLanguageDef. Thanks AndyH.
   26844: Fixed ALF-8000, ALF-7997, ALF-8108 and ALF-7721. Partial fix for ALF-8156. All these issues relate to admin console form configuration.
   26845: Fix for ALF-8181 - Admin console - sometimes displays the 'previous' tool, one step behind mouse click
   26854: Fixed ALF-8179: The new HTML email templates are bootstrapped with a mimetype of text/html they should be text/plain as they are freemarker files. Being plain text allows the content to be edited without TinyMCE corrupting the raw source. I also made all the templates inline editable.
   
   NOTE: To see these changes you must start with a clean database as these changes are only applied during initial bootstrap.
   26865: Merged V3.4-BUG-FIX to V3.4-TEAM
      26864: ALF-8025: JMX forms will no longer persist invalid values and subsystem auto-start errors are non-fatal
         - Errors on bootstrap subsystem startup are logged and absorbed. So should still always be possible to bring the server up to a level where its configuration can be corrected
         - The JMX setAttributes() method, which sets multiple attributes at once, is now handled differently from an individual setAttribute()
         - It attempts to restart the subsystem with the new properties. If successful these are persisted and a reload message is broadcast across the cluster. If unsuccessful it rolls back to the old properties and restarts the subsystem with those. Then the error is passed on to the caller.
         - Unit tested through JMX by AuthenticationChainTest
   26871: Refactor of fix to ALF-7888 to address clarified/extended requirements.
     After discussions with various engineers & the product manager, it has been agreed that sites should not appear in the recycle bin as they cannot be recovered from there. This is not a change to existing behaviour.
     However, formerly sites were only hard-deleted if deleted via the SiteService & remained archivable via the Explorer client and presumably other protocols such as CIFS.
     Now sites will by default not be deletable at all. So any attempt to delete a site via Explorer, CIFS etc will fail with an exception. This is achieved with a policy/behaviour on Site deletion.
     But that behaviour is disabled within the SiteService.deleteSite thus allowing deletion (and hard deletion at that) via that service only.
     End result is that admins can't accidentally delete sites as most interfaces prevent it and Share allows it after the normal warning dialogs.
   
     Had to tweak the SiteLoadPatch to delete a site via the SiteService rather than the NodeService.
   26873: Merged BRANCHES/V3.4 to BRANCHES/V3.4-TEAM:
      26860: ALF-7101 and ALF-7866 - don't show the rules options to collaborators, as they shouldn't be able to create/manage rules
   26874: Previous check-in (svn r. 26871 for ALF-7888) slightly broke the sample site for Team.
   Refactored the SiteLoadPatch to fix that.
   26875: ALF-7835 - args["itemTitle"] and args["page"] are already decoded, so don't try to decodeURIComponent them a second time when building the activity feed, otherwise it'll fail with special characters
   26893: Fixed ALF-7821 & ALF-7967 by making the OpenOffice read-only as it's all pre-installed for Team and shouldn't be editable. Also removed the (Subsystem) from the OpenOffice label.
   
   Also updated forms to remove the 'operations' button and move back to a Save/Cancel button as since Dave's changes to setAttributes() all the logic (including rollback of invalid properties) is now handled, meaning we no longer have to call the start() operation on the MBean.
   26901: Merged V3.4 to V3.4-TEAM
      26900: ALF-8180: The installer shouldn't randomly delete a directory called tomcat that it didn't create
         - Fix provided by Bitrock
   26905: Fix for ALF-8207 - Themes are not translated (not resolving title ids)
   26910: Fixed ALF-8206 "ES - Layout dashlets"
   26913: ALF-7838 - When paging the comments, do the reverse ordering before we page, rather than after
   26920: More on ALF-7004. The notification templates (used in the send email action of a rule) now follow the look and feel of the mockups Linton did originally.
   
   For this to work the MailActionExcecuter action needed the shareUrl, as all other email sending processes go through this action they no longer need to pass the shareUrl in. There was some inconsistency in how the URL was structured (sometimes with a trailing slash, sometimes not) so this has been cleaned up, which did mean more template updates.
   
   As before, this will require a clean database to see the updated templates.
   26921: Merged BRANCHES/DEV/V3.4-BUG-FIX to BRANCHES/V3.4-TEAM:
      26349: ALF-6062 - Add sorting by display name to the Group REST APIs that support paging
      26375: ALF-6062 - Make sorting of groups in the rest API case insensitive.
      26376: Correct long-incorrect indent and style stuff (at Gav's request)
      26402: ALF-6062 - Paging and Sorting (Case Insensitive) for the Groups REST APIs
      26423: ALF-6062 - Support sorting and paging of the child authorities and users of a group in the REST API, where previously only child groups were sortable and pageable
   26924: Some of ALF-8223: Added form config for GoogleDocs properties currently present on MBean
   26931: ALF-8092 - Convert the archived nodes webscript to the new style paging, which fixes an array index issue
   26933: Fixed ALF-8156: Too many detailed options for filesystem configuration in Admin Console
   
   Also made the position of 'enabled' properties consistent i.e. the first thing in the form/section.
   26937: Build fix for FeedCleanerTest. Also a refactoring of the Site deletion prevention behaviour for ALF-7888.
   This pattern should now be reusable outside the site service.
   
   I took my BeforeDeleteNode behaviour off the st:site node type. It was registered in SiteAspect.java.
   This was causing the test case failure as when I disabled behaviours on a site node before deletion, I was
   disabling all behaviours, including the necessary FeedCleaner behaviour.
   
   Added new aspect cm:undeletable
   Sites now have cm:undeletable as a mandatory aspect
   
   The BeforeDeleteNode behaviour that was attached to sites is now attached to cm:undeletable in UndeletableAspect.java
   
   site-services-context.xml defines an undeletableAspect bean which registers the behaviour on cm:undeletable.
   This could perhaps be moved into the NodeService. Will discuss on Monday.
   
   26938: Fixes ALF-8196: Ensure that WebView title bar link is updated as soon as its set
   26940: Fix for ALF-8036. Incorrect permissions copied when copying folder with permissions from one site to another.
     Permissions on nodes held within share sites are now cleaned after a move or a copy to a different share site.
     Cleaning in this context means permissions relating to the old site are removed and permission inheritance is turned on again. In this way the relocated nodes will look like they have just been uploaded, as requested in the issue comments.
     A new method in the SiteService stack (cleanSitePermissions) is used to initiate this clean-up from the move-to, copy-to slingshot webscripts.
     This is delegated to a new class/bean SitesPermissionCleaner which encapsulates the clean-up operation.
     The cleanup must be recursive as there could be nodes anywhere within the relocated tree which have permissions directly set on them. The tree is walked using nodeDAOs for efficiency. The cleanup is performed with aclDAOs, again for efficiency.
   
     This fix was developed on 3.4.2, but was backed out of there and is now checked in (effectively for the first time) on Team. This check-in will need to be merged to 3.4.3 at some point.
   26941: Updating svn properties on root associated with check-in 26940 for ALF-8036.
   Sorry. I forgot to check these in a moment ago.
   
   26949: Merged BRANCHES/DEV/V3.4-BUG-FIX to BRANCHES/V3.4-TEAM:
      26945: ALF-3554 / ALF-8257 - Adding rules to a node applies a marker aspect, so update the Rules Service to remove this when all removes are deleted.
   26950: Fix failing tests caused by r26920. Now that we rely on the Mail Action Executor to set the share URL for the templates, it's no longer available at the mock level when not calling the MailActionExecutor. Switch to a different model variable to check
   26954: ALF-8232 - Paging controls in doclib can overlay on top of sorting controls at 1024 screen res when 8+ pages are present
   26955: Follow-up to r26954 (ALF-8232). Remove local i18n messages for Links component.
   26956: Fixed ALF-8223 "Google integration needs Admin Console to configure options"
   26963: Fixed ALF-8223 "Google integration needs Admin Console to configure options"
   26964: Fixed ALF-8226 "ES FR DE Site pages in Customise Site to be spaced"
   - tested in FF3.5, SF3 & IE6,7,8
   26966: Added missing theme ID string
   26968: Merged V3.4-BUG-FIX to V3.4-TEAM
      26967: Fix for ALF-8259 - Static Asset Cache use of the /res resource servlet has overwritten the cachecontrol values set by the filter.
   26969: Moving the cm:undeletable aspect out of the SiteService and into the NodeService. Loosely related to ALF-7888.
   The cm:deletable aspect has been renamed to sys:undeletable.
   The class which registers the default behaviour, UndeletableAspect, has been moved into repo/node.
   Various minor changes in model files & spring config required.
   26970: ALF-8267 - Data Lists: search for user should not require minimum characters
   26971: Fixed ALF-8280 "ALL LANG - conversor pdf2swf - untranslated"
   26976: ALF-8271 - "Repository" appears as a destination when creating/editing linked rules in Doc Library.
   Rules picker now switches available modes based on whether Repository browsing is allowed or not. Removed reference to non-existent file. Also made rules picker sensitive to changing picker mode or site.
   26977: Fixes: ALF-7812: Adds support for multiday events.
   26978: Fixes: ALF-6107 - Fixes Tab order isses with Add event form.
   26979: Fix for ALF-8264. My Tasks incorrect capitalization.
   26991: ALF-8276 - "Select" dialog when adding items to workflow shows more information than in should
   26992: Fix for ALF-8288 - ES - Typo in serach result and also variable doesn't seem to work. Translation error, corrupted {0} strings pattern.
   26993: ALF-8148 - Details page Permissions incorrectly shows No privileges
   26994: Follow-up to r26993 (ALF-8148) for folders.
   26995: ALF-8265 - Data Lists: inconsistent capitalization; tooltip text is wordy
   26998: Fixes ALF-8091: Decode page URLs when removing dynamic welcome dashlets
   27000: Merged V3.4-BUG-FIX to V3.4-TEAM
      26999: Update to correct latest spring-webscripts-api jar
   27001: Fixes: ALF-8119 (IE8 bugs) & ALF-8118 - Clears event data from form.
   27005: Fixes: ALF-8168 - JSON encoding issue in Calendar API
   27025: Slight tweak to login dialog for iOS user usability
   27026: Fixes ALF-7764: Remove fade effect on title bar actions in IE to ensure correct image rendering
   27035: ALF-8314 - Document Library: Comment displays poorly when first word of comment is short.
   27040: Fix for ALF-8126 - Incorrect title of Transformer ImageMagick - missed labels
   27076: Merged V3.4-BUG-FIX to V3.4-TEAM
      26668: Fixes ALF-7920: Updated Linux/OSX config to add support for missing TIFF files in ImageMagic (dependant upon r26667 in ALF-BINARIES)
   27084: Merged V3.4 to V3.4-TEAM
      27083: ALF-8124: Corrected ${} placeholders in Japanese installer strings
   27091: Merged V3.4 to V3.4-TEAM
      26834: Fixes ALF-7904, ALF-8063: BitRock config updates
   27093: Fix for ALF-8308. Cannot like a folder that has rules defined for it.
     Added a necessary fix which prevents the exception being thrown.
   27094: Fixed ALF-8223: Google integration needs Admin Console to configure options.
   
   Also fixed a couple of other strings broken in a previous commit.
   27102: Further fix for ALF-8223: Google integration needs Admin Console to configure options. Removed application name to leave just enabled checkbox, username and password fields.
   27105: Fixed ALF-8277 & ALF-8253: Tooltips are not translated
   
   The JMX attribute description is no longer returned by the form processor as 99% of the time they don't contain anything useful and they are not localised.
   27106: Fix for ALF-8321: Cancel workflows move it to trashcan
   27115: ALF-7826, ALF-7949, ALF-8180, ALF-7904, ALF-8063: Reconciled project-team.xml with changes in project.xml
   27118: Merged V3.4-BUG-FIX to V3.4-TEAM
      26669: Fixes ALF-7987: Ensure rollback directories are removed on uninstall
   27119: ALF-8128: Propagate Team project name into Linux installer builder
   27137: Merged V3.4 to V3.4-TEAM
      27136: Installer string updates from Gloria
   27140: Temporary workaround to prevent rules running on cm:rating nodes (which happened for 'liked' folders ALF-8308 & ALF-8382)
   
   27162: Fixed ALF-8427 "Language packs: It's impossible to view any version of the wiki page if it contains native characters"
   27166: Updates to the invitation email templates following delivery of new l10n files.
   These changes were 'hand-merged' due to missing styling markup in the delivered l10n files.
   The new files had all styling markup removed.
   
   For the record, here's what I did:
   
   I compared the new and old files foreach {de, es, fr, it, ja} and found that all changes were short, simple and easy to merge.
   So I pasted in the main content div from the new l10n files, leaving all other styling markup (meaning css) unchanged.
   For the record, here's what diff says changed in this check-in:
   
   DE
   53c53
   <                                              
   ---
   > 
   55c55
   <                                              hat Sie eingeladen, als ${args["inviteeSiteRole"]} an der Site  ${args["siteName"]} teilzunehmen.</p>
   ---
   >                                              hat Sie eingeladen, mit der Rolle ${args["inviteeSiteRole"]} an der Site <b>${args["siteName"]}</b> teilzunehmen.</p>
   62,63c62,63
   <                                              <br />Benutzername: ${args["inviteeUserName"]}
   <                                              <br />Passwort: ${args["inviteeGenPassword"]}
   ---
   >                                              <br />Benutzername: <b>${args["inviteeUserName"]}</b>
   >                                              <br />Passwort: <b>${args["inviteeGenPassword"]}</b>
   66c66
   <                                              <p>Wir legen Ihnen nahe, das Passwort bei der ersten Anmeldung zu ändern.
   ---
   >                                              <p><b>Wir legen Ihnen nahe, das Passwort bei der ersten Anmeldung zu ändern.</b><br />
   
   ES
   52,53c52,53
   <                                              <p>Hola ${inviteePerson.properties["cm:firstName"]!""}:</p>
   <                                              
   ---
   >                                              <p>Hola, ${inviteePerson.properties["cm:firstName"]!""}:</p>
   > 
   55c55
   <                                              le ha invitado a unirse al sitio ${args["siteName"]} con el rol de ${args["inviteeSiteRole"]}.</p>
   ---
   >                                              le ha invitado a unirse al sitio <b>${args["siteName"]}</b> con el rol de ${args["inviteeSiteRole"]}.</p>
   62,63c62,63
   <                                              <br />Nombre de usuario: ${args["inviteeUserName"]}
   <                                              <br />Contraseña: ${args["inviteeGenPassword"]}
   ---
   >                                              <br />Nombre de usuario: <b>${args["inviteeUserName"]}</b>
   >                                              <br />Contraseña: <b>${args["inviteeGenPassword"]}</b>
   66,67c66,67
   <                                              <p>Le recomendamos que cambie la contraseña la primera vez que inicie una sesión.
   <                                              Para hacerlo, vaya a <b>Mi Perfil</b> y seleccione <b>Cambiar contraseña</b>.</p>
   ---
   >                                              <p><b>Le recomendamos que cambie la contraseña la primera vez que inicie sesión.</b><br />
   >                                              Para hacerlo, vaya a <b>Mi perfil</b> y seleccione <b>Cambiar contraseña</b>.</p>
   
   FR
   53c53
   <                                              
   ---
   > 
   55c55
   <                                              vous invite à rejoindre le site ${args["siteName"]} avec un rôle de ${args["inviteeSiteRole"]}.</p>
   ---
   >                                              vous invite à rejoindre le site <b>${args["siteName"]}</b> avec un rôle de ${args["inviteeSiteRole"]}.</p>
   62,63c62,63
   <                                              <br />Nom d'utilisateur : ${args["inviteeUserName"]}
   <                                              <br />Mot de passe : ${args["inviteeGenPassword"]}
   ---
   >                                              <br />Nom d'utilisateur : <b>${args["inviteeUserName"]}</b>
   >                                              <br />Mot de passe : <b>${args["inviteeGenPassword"]}</b>
   66c66
   <                                              <p>Nous vous conseillons vivement de modifier votre mot de passe lors de votre première connexion.
   ---
   >                                              <p><b>Nous vous conseillons vivement de modifier votre mot de passe lors de votre première connexion.</b><br />
   70c70
   <                                              <p>Si vous souhaitez décliner l'invitation de ${inviterPerson.properties["cm:firstName"]!""} cliquez sur ce lien :<br />
   ---
   >                                              <p>Si vous souhaitez décliner l'invitation de ${inviterPerson.properties["cm:firstName"]!""}’, cliquez sur ce lien :<br />
   
   
   IT
   53c53
   <                                              
   ---
   > 
   55c55
   <                                              ti ha  inviatato a partecipare al sito ${args["siteName"]} con il ruolo di ${args["inviteeSiteRole"]}.</p>
   ---
   >                                              sei stato inviatato a partecipare al sito <b>${args["siteName"]}</b> con il ruolo di ${args["inviteeSiteRole"]}.</p>
   57c57
   <                                              <p>Fare clic sul collegamento per accettare l’invito dell'${inviterPerson.properties["cm:firstName"]!""}':<br />
   ---
   >                                              <p>Fare clic sul collegamento per accettare ${inviterPerson.properties["cm:firstName"]!""}'s l'invito:<br />
   62,63c62,63
   <                                              <br />Nome utente: ${args["inviteeUserName"]}
   <                                              <br />Password: ${args["inviteeGenPassword"]}
   ---
   >                                              <br />Nome utente: <b>${args["inviteeUserName"]}</b>
   >                                              <br />Password: <b>${args["inviteeGenPassword"]}</b>
   66c66
   <                                              <p>Si consiglia di cambiare la password quando si effettua l'eccesso per la prima volta.
   ---
   >                                              <p><b>Si consiglia di cambiare la password quando si effettua l'eccesso per la prima volta.</b><br />
   70c70
   <                                              <p>Per rifiutare l’invito dell’${inviterPerson.properties["cm:firstName"]!""}, fare clic su questo collegamento:<br />
   ---
   >                                              <p>Per rifiutare ${inviterPerson.properties["cm:firstName"]!""}’s l'invito, fare clic su questo collegamento:<br />
   
   
   JA
   53c53
   <                                              
   ---
   > 
   55c55
   <                                              ????${args["siteName"]} ??????${args["inviteeSiteRole"]}?????????????????????</p>
   ---
   >                                              ????<b>${args["siteName"]}</b> ????? ${args["inviteeSiteRole"]} ????????????????????</p>
   62,63c62,63
   <                                              <br />????: ${args["inviteeUserName"]}
   <                                              <br />?????: ${args["inviteeGenPassword"]}
   ---
   >                                              <br />????: <b>${args["inviteeUserName"]}</b>
   >                                              <br />?????: <b>${args["inviteeGenPassword"]}</b>
   66c66
   <                                              <p>?????????????????????????????
   ---
   >                                              <p><b>?????????????????????????????</b><br />
   
   27172: Fixed ALF-7856 "Team: DocLib action displaying incorrect tooltip text"
   27339: ALF-8330 - ALL LANG - "Assigned To" in Data List created displays untranslated
   27340: Fixes Encoding issue in L10N files.
   27471: Fix for ALF-8150 - check for visibility before applying focus to element for IE.
   27499: Drop one and two of updates from translators based on rev26820
   27501: ALF-8151 - Filetype icon or is incorrectly displayed at the Content I'm editing dashlet
   27507: ALF-8478: Default repeat interval for activity email notifications should be 1 day
   27520: Fixed ALF-8329 "Consumer can add comments to files, folders, links and blogs"
   27527: Fixes ALF-8409: Ensure that UTF-8 encoded characters in file names can be uploaded to folders (that may also contain UTF-8 encoded characters) via DND in FireFox 3.6
   27531: Merged V3.4-BUG-FIX to V3.4-TEAM
      27525: Merged V3.4 to V3.4-BUG-FIX
         27120: Resolve ALF-8187: Transaction retries of CMIS webscripts failing
   27543: Fixed ALF-8464 "Start Workflow: Search for groups still requires minimum 1 character"
   27562: Merged V3.4-BUG-FIX to V3.4-TEAM
      27560: Fix for ALF-8434 - AVMRemoteStore not setting UTF-8 response encoding for some methods
   27572: Fixes: ALF-7596 - Config values not being correctly read in FTL
   27573: Fixed ALF-8504: Non-admin users are warned about license expiry too soon
    - ALF-8502 Adjust admin warning period from 30 to 21 days
    - ALF-7259 RTEAM 33: RepoAdmin Web Script to report Red/Amber/Green
   27592: Fixes: ALF-8444 - JA properties file in incorrect location.
   27594: ALF-8508 - Document Library: Google Docs actions not correct
   27596: Fixed ALF-8484	"Consumer and Contributor should not be able to choose button "Revert" of the document"
   27598: Annotated properties file to indicate which text is exposed to the UI and therefore needs translating. Needed for: ALF-8442
   27615: Fix for ALF-8501 - License warning box needs to be toned down in colour
   27616: Tweak for IE
   27617: Fixes: ALF-8423 - string missed in earlier merge
   27619: ALF-7904: Synchronize alfresco-customteam-settings.xml with alfresco-customstack-postgres-settings.xml!
   27625: ALF-7518 - Update Team Help and Tutorial URLs once finalised. * DO NOT MERGE *
   Note: version.edition cannot be used as a placeholder due to the mismatch between "edition=Enterprise" and help URL containing "team"
   27626: Change default value for "useTitle" to true for Site DocLib
   27648: Fix for ALF-8552
   27649: Fixed ALF-8495: Alfresco Logo is incorrectly displayed in notify user letter
   
   Usual note with these checkins applies, clean database will be required to see the updated templates.
   27650: Fixed ALF-8425: Select Tags button is missing at the Edit Properties page for msg files
   27664: Issue checking in XSLX Google Docs (related to ALF-8580)
   
   27667: ALF-7518 - Update Team Help and Tutorial URLs once finalised
   New tutorial URL for Share, now hosted within main docs system; uh-tutorial.html topic page.
   27683: Merged BRANCHES/DEV/dwebsterTeam to BRANCHES/V3.4-TEAM:
      27675: DE: Drop 3 & 4 for Team translations based on r27552
      27676: ES: Drop 3 & 4 for Team translations based on r27552
      27677: FR: Drop 3 & 4 for Team translations based on r27552
      27678: IT: Drop 3 & 4 for Team translations based on r27552
      27679: JA: Drop 3 & 4 for Team translations based on r27552
      27680: L10N updates to system-messages.properties (for License messages exposed to UI)
   27686: Fixes: ALF-8266
   27694: Change related to ALF-8556. Sometimes Google Docs cannot be checked out.
   This change was suggested by Roy. cm:failedThumbnail nodes were deleted onUpdateProperties. Now they are only deleted if there are no locks preventing their deletion (e.g. due to being checked out.)
   27710: Fixed ALF-7721: There are no field rescrtictions on 'Edit: Fileservers' form and ALF-8558: There is no pattern for Username field in Google Docs
   27711: ALF-8590 - Check Out for some documents is not working
   ALF-8591 - CheckIn form Google docs for some documents is not working
   
   Google Docs-specific filter code added to Manage Aspects UI to remove "gd:googleEditable from the list of addable aspects unless the file's mimetype is supported (i.e. txt, doc, xls, ppt). Google Docs enabled ootb in team-config.
   27713: GDoc - Fix for checkout of .odt files (see ALF-8599)
   
   27723: Added back theme name string that was removed in rev 26971
   27740: Updates from Gloria following bundle completeness analysis.
   27755: Removed extra unused Japanese translation files.
   27756: ALF-8207 - ALL LANG - Themes are not translated
   27759: Merged BRANCHES/DEV/V3.4-BUG-FIX to BRANCHES/V3.4-TEAM:
      27758: Merged BRANCHES/V3.4 to BRANCHES/DEV/V3.4-BUG-FIX:
           27757: Fix for ALF-8430.
   27761: JA Updates from Gloria following bundle completeness analysis.
   27767: Fixes: ALF-8279 - reloads translation Gloria sent.
   27768: ALF-8213 - Manage My Subscription link now directs to team.alfresco.com - tooltip from label added
   27769: Fixes ALF-8652: Add removed quotes and revert translations back to correct language
   27770: Fixes: ALF-8228: Column widening needed
   27771: Initial commit of these translated files from Gloria.
   27772: ALF-8555 - Incorrect behavior of enabling Google docs (Really: Forms get submitted twice in certain circumstances)
   27773: ALF-8329 - Consumer can add comments to files, folders, links and blogs
   Fixed: 8. Open details page for file and try to add comment --> comment added successfully;
   27774: Spanish Gender Changes following review from Gloria.
   27779: Final fixes from L10N completeness check.
   27792: Remove debugging code from r27772
   27804: ALF-8207 - ALL LANG - SpringSurf issue with default theme definition
   27826: Manually reverts (to a version prior to r27683) a file in each language that was incorrectly supplied in English, and ensures they match the current EN properties.
   27827: Fixes: ALF-8210
   27843: Fix for ALF-8449 - ALL LANG - site themes are not translated (Customise Site page)
   27873: Merged V3.4 to V3.4-TEAM:
      27871: Fixes ALF-8124: Ensure Spanish locale for installer shows product name correctly
   27883: Implementation of ALF-8737 Support for thumbnailing/previewing of additional mimetypes (Adobe). Also video/audio playbac
   k.
   
   This check in enables thumbnails for Adobe Photoshop, recent Adobe Illustrator files and previews for Adobe Photoshop, recent Adobe Illustrator files
   as well as metadata extraction for Adobe Illustrator files (PDF-based formats).
   
   It also enables video playback of .m4v files, where the browser supports it.
   I have also added placeholder icons for .m4v files.
   Adobe Photoshop (.psd) files are handled by ImageMagick. However our existing ImageMagick-based content transformer excludes most mimetypes that don't start with "image/". By allowing "application/photoshop" to be accepted, that transformer
    will now perform thumbnails and previews.
   Recent Adobe Illustrator file formats are pdf files and so can use the PDF transformers/extractors i.e. PDFRenderer and 
   PDFBox and pdf2swf.
   I have added a new complex transformer for .ai files which uses the existing PDF/ImageMagick component transformers.
   
   New JUnit test cases for these transforms.
   
   As part of testing, we discovered that IE9 will not play mp3s of mimetype == audio/x-mpeg, only audio/mpeg.
   The latter is the correct mimetype, the former is out of date, but Alfresco was using the former. So we've updated that MIME type in various places in the code.
   27888: Google Docs 
     - Updated client google doc api jars
     - Fixes ALF-8592: Incorrect behavior on permissions for Google docs
   
   27894: Minor fixes for iOS:
   . overflow content shown by default in dashlets
   . doclib long filenames no longer cause screen to resize
   . ipad css overrides
   . YUI dialogs no longer jump around the page during text entry input
   27904: Minor fixes for iOS usability:
   . Drag&drop doclist help removed for mobile devices
   . Create New DataList shows list as full height (not scrollable)
   . Removed default webkit inner shadow from input fields
   27915: Minor fixes for iOS usability: Forced scrollbar appearance on overflowed div elements


git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@27939 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
2011-05-20 13:30:26 +00:00

2382 lines
93 KiB
Java

/*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.node.db;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.domain.node.ChildAssocEntity;
import org.alfresco.repo.domain.node.Node;
import org.alfresco.repo.domain.node.NodeDAO;
import org.alfresco.repo.domain.node.NodeDAO.ChildAssocRefQueryCallback;
import org.alfresco.repo.domain.qname.QNameDAO;
import org.alfresco.repo.node.AbstractNodeServiceImpl;
import org.alfresco.repo.node.StoreArchiveMap;
import org.alfresco.repo.node.archive.NodeArchiveService;
import org.alfresco.repo.node.index.NodeIndexer;
import org.alfresco.repo.policy.BehaviourFilter;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.TransactionalResourceHelper;
import org.alfresco.service.cmr.dictionary.AspectDefinition;
import org.alfresco.service.cmr.dictionary.AssociationDefinition;
import org.alfresco.service.cmr.dictionary.ClassDefinition;
import org.alfresco.service.cmr.dictionary.InvalidAspectException;
import org.alfresco.service.cmr.dictionary.InvalidTypeException;
import org.alfresco.service.cmr.dictionary.PropertyDefinition;
import org.alfresco.service.cmr.dictionary.TypeDefinition;
import org.alfresco.service.cmr.repository.AssociationExistsException;
import org.alfresco.service.cmr.repository.AssociationRef;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.InvalidChildAssociationRefException;
import org.alfresco.service.cmr.repository.InvalidNodeRefException;
import org.alfresco.service.cmr.repository.InvalidStoreRefException;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeRef.Status;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.Path;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.namespace.QNamePattern;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.alfresco.util.EqualsHelper;
import org.alfresco.util.GUID;
import org.alfresco.util.Pair;
import org.alfresco.util.ParameterCheck;
import org.alfresco.util.PropertyMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Node service using database persistence layer to fulfill functionality
*
* @author Derek Hulley
*/
public class DbNodeServiceImpl extends AbstractNodeServiceImpl
{
private static Log logger = LogFactory.getLog(DbNodeServiceImpl.class);
private QNameDAO qnameDAO;
private NodeDAO nodeDAO;
private StoreArchiveMap storeArchiveMap;
private NodeService avmNodeService;
private NodeIndexer nodeIndexer;
private BehaviourFilter policyBehaviourFilter;
private final static String KEY_PRE_COMMIT_ADD_NODE = "DbNodeServiceImpl.PreCommitAddNode";
private final static String KEY_DELETED_NODES = "DbNodeServiceImpl.DeletedNodes";
public DbNodeServiceImpl()
{
storeArchiveMap = new StoreArchiveMap(); // in case it is not set
}
public void setQnameDAO(QNameDAO qnameDAO)
{
this.qnameDAO = qnameDAO;
}
public void setNodeDAO(NodeDAO nodeDAO)
{
this.nodeDAO = nodeDAO;
}
public void setStoreArchiveMap(StoreArchiveMap storeArchiveMap)
{
this.storeArchiveMap = storeArchiveMap;
}
public void setAvmNodeService(NodeService avmNodeService)
{
this.avmNodeService = avmNodeService;
}
/**
* @param nodeIndexer the indexer that will be notified of node additions,
* modifications and deletions
*/
public void setNodeIndexer(NodeIndexer nodeIndexer)
{
this.nodeIndexer = nodeIndexer;
}
/**
*
* @param policyBehaviourFilter component used to enable and disable behaviours
*/
public void setPolicyBehaviourFilter(BehaviourFilter policyBehaviourFilter)
{
this.policyBehaviourFilter = policyBehaviourFilter;
}
/**
* Performs a null-safe get of the node
*
* @param nodeRef the node to retrieve
* @return Returns the node entity (never null)
* @throws InvalidNodeRefException if the referenced node could not be found
*/
private Pair<Long, NodeRef> getNodePairNotNull(NodeRef nodeRef) throws InvalidNodeRefException
{
ParameterCheck.mandatory("nodeRef", nodeRef);
Pair<Long, NodeRef> unchecked = nodeDAO.getNodePair(nodeRef);
if (unchecked == null)
{
throw new InvalidNodeRefException("Node does not exist: " + nodeRef, nodeRef);
}
return unchecked;
}
public boolean exists(StoreRef storeRef)
{
return nodeDAO.exists(storeRef);
}
public boolean exists(NodeRef nodeRef)
{
ParameterCheck.mandatory("nodeRef", nodeRef);
return nodeDAO.exists(nodeRef);
}
public Status getNodeStatus(NodeRef nodeRef)
{
ParameterCheck.mandatory("nodeRef", nodeRef);
NodeRef.Status status = nodeDAO.getNodeRefStatus(nodeRef);
return status;
}
/**
* {@inheritDoc}
*/
public List<StoreRef> getStores()
{
// Get the ADM stores
List<Pair<Long, StoreRef>> stores = nodeDAO.getStores();
List<StoreRef> storeRefs = new ArrayList<StoreRef>(50);
for (Pair<Long, StoreRef> pair : stores)
{
StoreRef storeRef = pair.getSecond();
if (storeRef.getProtocol().equals(StoreRef.PROTOCOL_DELETED))
{
// Ignore
continue;
}
storeRefs.add(storeRef);
}
// Now get the AVMStores.
List<StoreRef> avmStores = avmNodeService.getStores();
storeRefs.addAll(avmStores);
// Return them all.
return storeRefs;
}
/**
* Defers to the typed service
* @see StoreDaoService#createWorkspace(String)
*/
public StoreRef createStore(String protocol, String identifier)
{
StoreRef storeRef = new StoreRef(protocol, identifier);
// invoke policies
invokeBeforeCreateStore(ContentModel.TYPE_STOREROOT, storeRef);
// create a new one
Pair<Long, NodeRef> rootNodePair = nodeDAO.newStore(storeRef);
NodeRef rootNodeRef = rootNodePair.getSecond();
// invoke policies
invokeOnCreateStore(rootNodeRef);
// Index
ChildAssociationRef assocRef = new ChildAssociationRef(null, null, null, rootNodeRef);
nodeIndexer.indexCreateNode(assocRef);
// Done
return storeRef;
}
/**
* @throws UnsupportedOperationException Always
*/
public void deleteStore(StoreRef storeRef) throws InvalidStoreRefException
{
// Delete the index
nodeIndexer.indexDeleteStore(storeRef);
// Rename the store
StoreRef deletedStoreRef = new StoreRef(StoreRef.PROTOCOL_DELETED, GUID.generate());
nodeDAO.moveStore(storeRef, deletedStoreRef);
// Done
if (logger.isDebugEnabled())
{
logger.debug("Marked store for deletion: " + storeRef + " --> " + deletedStoreRef);
}
}
public NodeRef getRootNode(StoreRef storeRef) throws InvalidStoreRefException
{
Pair<Long, NodeRef> rootNodePair = nodeDAO.getRootNode(storeRef);
if (rootNodePair == null)
{
throw new InvalidStoreRefException("Store does not exist: " + storeRef, storeRef);
}
// done
return rootNodePair.getSecond();
}
/**
* @see #createNode(NodeRef, QName, QName, QName, Map)
*/
public ChildAssociationRef createNode(
NodeRef parentRef,
QName assocTypeQName,
QName assocQName,
QName nodeTypeQName)
{
return this.createNode(parentRef, assocTypeQName, assocQName, nodeTypeQName, null);
}
/**
* {@inheritDoc}
*/
public ChildAssociationRef createNode(
NodeRef parentRef,
QName assocTypeQName,
QName assocQName,
QName nodeTypeQName,
Map<QName, Serializable> properties)
{
ParameterCheck.mandatory("parentRef", parentRef);
ParameterCheck.mandatory("assocTypeQName", assocTypeQName);
ParameterCheck.mandatory("assocQName", assocQName);
ParameterCheck.mandatory("nodeTypeQName", nodeTypeQName);
if(assocQName.getLocalName().length() > QName.MAX_LENGTH)
{
throw new IllegalArgumentException("Localname is too long");
}
// Get the parent node
Pair<Long, NodeRef> parentNodePair = getNodePairNotNull(parentRef);
StoreRef parentStoreRef = parentRef.getStoreRef();
// null property map is allowed
if (properties == null)
{
properties = Collections.emptyMap();
}
// get an ID for the node
String newUuid = generateGuid(properties);
/**
* Check the parent node has not been deleted in this txn.
*/
if(isDeletedNodeRef(parentRef))
{
throw new InvalidNodeRefException("The parent node has been deleted", parentRef);
}
// Invoke policy behaviour
invokeBeforeCreateNode(parentRef, assocTypeQName, assocQName, nodeTypeQName);
// check the node type
TypeDefinition nodeTypeDef = dictionaryService.getType(nodeTypeQName);
if (nodeTypeDef == null)
{
throw new InvalidTypeException(nodeTypeQName);
}
// Ensure child uniqueness
String newName = extractNameProperty(properties);
// create the node instance
ChildAssocEntity assoc = nodeDAO.newNode(
parentNodePair.getFirst(),
assocTypeQName,
assocQName,
parentStoreRef,
newUuid,
nodeTypeQName,
newName,
properties);
ChildAssociationRef childAssocRef = assoc.getRef(qnameDAO);
Pair<Long, NodeRef> childNodePair = assoc.getChildNode().getNodePair();
addAspectsAndProperties(
childNodePair,
nodeTypeQName,
null,
Collections.<QName>emptySet(),
Collections.<QName, Serializable>emptyMap(),
Collections.<QName>emptySet(),
properties,
true,
false);
Map<QName, Serializable> propertiesAfter = nodeDAO.getNodeProperties(childNodePair.getFirst());
// Invoke policy behaviour
invokeOnCreateNode(childAssocRef);
invokeOnCreateChildAssociation(childAssocRef, true);
Map<QName, Serializable> propertiesBefore = PropertyMap.EMPTY_MAP;
invokeOnUpdateProperties(
childAssocRef.getChildRef(),
propertiesBefore,
propertiesAfter);
untrackDeletedNodeRef(childAssocRef.getChildRef());
// Index
nodeIndexer.indexCreateNode(childAssocRef);
// Ensure that the parent node has the required aspects
addAspectsAndPropertiesAssoc(parentNodePair, assocTypeQName, null, null, null, null, false);
// done
return childAssocRef;
}
/**
* Track a deleted node
*
* The deleted node set is used to break an infinite loop which can happen when adding a new node into a path containing a
* deleted node. This transactional list is used to detect and prevent that from
* happening.
*
* @param nodeRef the deleted node to track
* @return <tt>true</tt> if the node was not already tracked
*/
private boolean trackDeletedNodeRef(NodeRef deletedNodeRef)
{
Set<NodeRef> deletedNodes = TransactionalResourceHelper.getSet(KEY_DELETED_NODES);
return deletedNodes.add(deletedNodeRef);
}
/**
* Untrack a deleted node ref
*
* Used when a deleted node is restored.
*
* @param deletedNodeRef
*/
private void untrackDeletedNodeRef(NodeRef deletedNodeRef)
{
Set<NodeRef> deletedNodes = TransactionalResourceHelper.getSet(KEY_DELETED_NODES);
if (deletedNodes.size() > 0)
{
deletedNodes.remove(deletedNodeRef);
}
}
private boolean isDeletedNodeRef(NodeRef deletedNodeRef)
{
Set<NodeRef> deletedNodes = TransactionalResourceHelper.getSet(KEY_DELETED_NODES);
return deletedNodes.contains(deletedNodeRef);
}
/**
* loose interest in tracking a node ref
*
* for example if its been deleted or moved
* @param nodeRef the node ref to untrack
*/
private void untrackNewNodeRef(NodeRef nodeRef)
{
Set<NodeRef> newNodes = TransactionalResourceHelper.getSet(KEY_PRE_COMMIT_ADD_NODE);
if (newNodes.size() > 0)
{
newNodes.remove(nodeRef);
}
}
/**
* Adds all the aspects and properties required for the given node, along with mandatory aspects
* and related properties.
* Existing values will not be overridden. All required pre- and post-update notifications
* are sent for missing aspects.
*
* @param nodePair the node to which the details apply
* @param classQName the type or aspect QName for which the defaults must be applied.
* If this is <tt>null</tt> then properties and aspects are only applied
* for 'extra' aspects and 'extra' properties.
* @param existingAspects the existing aspects or <tt>null</tt> to have them fetched
* @param existingProperties the existing properties or <tt>null</tt> to have them fetched
* @param extraAspects any aspects that should be added to the 'missing' set (may be <tt>null</tt>)
* @param extraProperties any properties that should be added the the 'missing' set (may be <tt>null</tt>)
* @param overwriteExistingProperties <tt>true</tt> if the extra properties must completely overwrite
* the existing properties
* @return <tt>true</tt> if properties or aspects were added
*/
private boolean addAspectsAndProperties(
Pair<Long, NodeRef> nodePair,
QName classQName,
Set<QName> existingAspects,
Map<QName, Serializable> existingProperties,
Set<QName> extraAspects,
Map<QName, Serializable> extraProperties,
boolean overwriteExistingProperties)
{
return addAspectsAndProperties(nodePair, classQName, null, existingAspects, existingProperties, extraAspects, extraProperties, overwriteExistingProperties, true);
}
private boolean addAspectsAndPropertiesAssoc(
Pair<Long, NodeRef> nodePair,
QName assocTypeQName,
Set<QName> existingAspects,
Map<QName, Serializable> existingProperties,
Set<QName> extraAspects,
Map<QName, Serializable> extraProperties,
boolean overwriteExistingProperties)
{
return addAspectsAndProperties(nodePair, null, assocTypeQName, existingAspects, existingProperties, extraAspects, extraProperties, overwriteExistingProperties, true);
}
private boolean addAspectsAndProperties(
Pair<Long, NodeRef> nodePair,
QName classQName,
QName assocTypeQName,
Set<QName> existingAspects,
Map<QName, Serializable> existingProperties,
Set<QName> extraAspects,
Map<QName, Serializable> extraProperties,
boolean overwriteExistingProperties,
boolean invokeOnUpdateProperties)
{
ParameterCheck.mandatory("nodePair", nodePair);
Long nodeId = nodePair.getFirst();
NodeRef nodeRef = nodePair.getSecond();
// Ensure that have a type that has no mandatory aspects or properties
if (classQName == null)
{
classQName = ContentModel.TYPE_BASE;
}
// Ensure we have 'extra' aspects and properties to play with
if (extraAspects == null)
{
extraAspects = Collections.emptySet();
}
if (extraProperties == null)
{
extraProperties = Collections.emptyMap();
}
// Get the existing aspects and properties, if necessary
if (existingAspects == null)
{
existingAspects = nodeDAO.getNodeAspects(nodeId);
}
if (existingProperties == null)
{
existingProperties = nodeDAO.getNodeProperties(nodeId);
}
// To determine the 'missing' aspects, we need to determine the full set of properties
Map<QName, Serializable> allProperties = new HashMap<QName, Serializable>(37);
allProperties.putAll(existingProperties);
allProperties.putAll(extraProperties);
// Copy incoming existing values so that we can modify appropriately
existingAspects = new HashSet<QName>(existingAspects);
// Get the 'missing' aspects and append the 'extra' aspects
Set<QName> missingAspects = getMissingAspects(existingAspects, allProperties, classQName);
missingAspects.addAll(extraAspects);
if (assocTypeQName != null)
{
missingAspects.addAll(getMissingAspectsAssoc(existingAspects, allProperties, assocTypeQName));
}
// Notify 'before' adding aspect
for (QName missingAspect : missingAspects)
{
invokeBeforeAddAspect(nodeRef, missingAspect);
}
// Get all missing properties for aspects that are missing.
// This will include the type if the type was passed in.
Set<QName> allClassQNames = new HashSet<QName>(13);
allClassQNames.add(classQName);
allClassQNames.addAll(missingAspects);
Map<QName, Serializable> missingProperties = getMissingProperties(existingProperties, allClassQNames);
missingProperties.putAll(extraProperties);
// Bulk-add the properties
boolean changedProperties = false;
if (overwriteExistingProperties)
{
// Overwrite properties
changedProperties = nodeDAO.setNodeProperties(nodeId, missingProperties);
}
else
{
// Append properties
changedProperties = nodeDAO.addNodeProperties(nodeId, missingProperties);
}
if (changedProperties && invokeOnUpdateProperties)
{
Map<QName, Serializable> propertiesAfter = nodeDAO.getNodeProperties(nodeId);
invokeOnUpdateProperties(nodeRef, existingProperties, propertiesAfter);
}
// Bulk-add the aspects
boolean changedAspects = nodeDAO.addNodeAspects(nodeId, missingAspects);
if (changedAspects)
{
for (QName missingAspect : missingAspects)
{
invokeOnAddAspect(nodeRef, missingAspect);
}
}
// Done
return changedAspects || changedProperties;
}
private Set<QName> getMissingAspectsAssoc(
Set<QName> existingAspects,
Map<QName, Serializable> existingProperties,
QName assocTypeQName)
{
AssociationDefinition assocDef = dictionaryService.getAssociation(assocTypeQName);
if (assocDef == null)
{
return Collections.emptySet();
}
ClassDefinition classDefinition = assocDef.getSourceClass();
return getMissingAspects(existingAspects, existingProperties, classDefinition.getName());
}
/**
* Get any aspects that should be added given the type, properties and existing aspects.
* Note that this <b>does not</b> included a search for properties required for the missing
* aspects.
*
* @param classQName the type, aspect or association
* @return Returns any aspects that should be added
*/
private Set<QName> getMissingAspects(
Set<QName> existingAspects,
Map<QName, Serializable> existingProperties,
QName classQName)
{
// Copy incoming existing values so that we can modify appropriately
existingAspects = new HashSet<QName>(existingAspects);
ClassDefinition classDefinition = dictionaryService.getClass(classQName);
if (classDefinition == null)
{
return Collections.emptySet();
}
Set<QName> missingAspects = new HashSet<QName>(7);
// Check that the aspect itself is present (only applicable for aspects)
if (classDefinition.isAspect() && !existingAspects.contains(classQName))
{
missingAspects.add(classQName);
}
// Find all aspects that should be present on the class
List<AspectDefinition> defaultAspectDefs = classDefinition.getDefaultAspects();
for (AspectDefinition defaultAspectDef : defaultAspectDefs)
{
QName defaultAspect = defaultAspectDef.getName();
if (!existingAspects.contains(defaultAspect))
{
missingAspects.add(defaultAspect);
}
}
// Find all aspects that should be present given the existing properties
for (QName existingPropQName : existingProperties.keySet())
{
PropertyDefinition existingPropDef = dictionaryService.getProperty(existingPropQName);
if (existingPropDef == null || !existingPropDef.getContainerClass().isAspect())
{
continue; // Property is undefined or belongs to a class
}
QName existingPropDefiningType = existingPropDef.getContainerClass().getName();
if (!existingAspects.contains(existingPropDefiningType))
{
missingAspects.add(existingPropDefiningType);
}
}
// If there were missing aspects, recurse to find further missing aspects
// Don't re-add ones we know about or we can end in infinite recursion.
// Don't send any properties because we don't want to reprocess them each time
Set<QName> allTypesAndAspects = new HashSet<QName>(13);
allTypesAndAspects.add(classQName);
allTypesAndAspects.addAll(existingAspects);
allTypesAndAspects.addAll(missingAspects);
Set<QName> missingAspectsCopy = new HashSet<QName>(missingAspects);
for (QName missingAspect : missingAspectsCopy)
{
Set<QName> furtherMissingAspects = getMissingAspects(
allTypesAndAspects,
Collections.<QName, Serializable>emptyMap(),
missingAspect);
missingAspects.addAll(furtherMissingAspects);
allTypesAndAspects.addAll(furtherMissingAspects);
}
// Done
return missingAspects;
}
/**
* @param existingProperties existing node properties
* @param classQNames the types or aspects to introspect
* @return Returns any properties that should be added
*/
private Map<QName, Serializable> getMissingProperties(Map<QName, Serializable> existingProperties, Set<QName> classQNames)
{
Map<QName, Serializable> allDefaultProperties = new HashMap<QName, Serializable>(17);
for (QName classQName : classQNames)
{
ClassDefinition classDefinition = dictionaryService.getClass(classQName);
if (classDefinition == null)
{
continue;
}
// Get the default properties for this type/aspect
Map<QName, Serializable> defaultProperties = getDefaultProperties(classQName);
if (defaultProperties.size() > 0)
{
allDefaultProperties.putAll(defaultProperties);
}
}
// Work out what is missing
Map<QName, Serializable> missingProperties = new HashMap<QName, Serializable>(allDefaultProperties);
missingProperties.keySet().removeAll(existingProperties.keySet());
// Done
return missingProperties;
}
public void setChildAssociationIndex(ChildAssociationRef childAssocRef, int index)
{
// get nodes
Pair<Long, NodeRef> parentNodePair = getNodePairNotNull(childAssocRef.getParentRef());
Pair<Long, NodeRef> childNodePair = getNodePairNotNull(childAssocRef.getChildRef());
Long parentNodeId = parentNodePair.getFirst();
Long childNodeId = childNodePair.getFirst();
QName assocTypeQName = childAssocRef.getTypeQName();
QName assocQName = childAssocRef.getQName();
// set the index
int updated = nodeDAO.setChildAssocIndex(
parentNodeId, childNodeId, assocTypeQName, assocQName, index);
if (updated < 1)
{
throw new InvalidChildAssociationRefException(
"Unable to set child association index: \n" +
" assoc: " + childAssocRef + "\n" +
" index: " + index,
childAssocRef);
}
}
public QName getType(NodeRef nodeRef) throws InvalidNodeRefException
{
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
return nodeDAO.getNodeType(nodePair.getFirst());
}
/**
* @see org.alfresco.service.cmr.repository.NodeService#setType(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.namespace.QName)
*/
public void setType(NodeRef nodeRef, QName typeQName) throws InvalidNodeRefException
{
// check the node type
TypeDefinition nodeTypeDef = dictionaryService.getType(typeQName);
if (nodeTypeDef == null)
{
throw new InvalidTypeException(typeQName);
}
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
// Invoke policies
invokeBeforeUpdateNode(nodeRef);
// Set the type
nodeDAO.updateNode(nodePair.getFirst(), null, null, typeQName);
// Add the default aspects and properties required for the given type. Existing values will not be overridden.
addAspectsAndProperties(nodePair, typeQName, null, null, null, null, false);
// Index
nodeIndexer.indexUpdateNode(nodeRef);
// Invoke policies
invokeOnUpdateNode(nodeRef);
}
/**
* @see Node#getAspects()
*/
public void addAspect(
NodeRef nodeRef,
QName aspectTypeQName,
Map<QName, Serializable> aspectProperties)
throws InvalidNodeRefException, InvalidAspectException
{
// check that the aspect is legal
AspectDefinition aspectDef = dictionaryService.getAspect(aspectTypeQName);
if (aspectDef == null)
{
throw new InvalidAspectException("The aspect is invalid: " + aspectTypeQName, aspectTypeQName);
}
// Check the properties
if (aspectProperties == null)
{
// Make a map
aspectProperties = Collections.emptyMap();
}
// Make the properties immutable to be sure that they are not used incorrectly
aspectProperties = Collections.unmodifiableMap(aspectProperties);
// Invoke policy behaviours
invokeBeforeUpdateNode(nodeRef);
// Add aspect and defaults
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
boolean modified = addAspectsAndProperties(
nodePair,
aspectTypeQName,
null,
null,
Collections.singleton(aspectTypeQName),
aspectProperties,
false);
if (modified)
{
// Invoke policy behaviours
invokeOnUpdateNode(nodeRef);
// Index
nodeIndexer.indexUpdateNode(nodeRef);
}
}
public void removeAspect(NodeRef nodeRef, QName aspectTypeQName)
throws InvalidNodeRefException, InvalidAspectException
{
/**
* Note: Aspect and property removal is resilient to missing dictionary definitions
*/
// get the node
final Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
final Long nodeId = nodePair.getFirst();
boolean hadAspect = nodeDAO.hasNodeAspect(nodeId, aspectTypeQName);
// Invoke policy behaviours
invokeBeforeUpdateNode(nodeRef);
if (hadAspect)
{
invokeBeforeRemoveAspect(nodeRef, aspectTypeQName);
nodeDAO.removeNodeAspects(nodeId, Collections.singleton(aspectTypeQName));
}
AspectDefinition aspectDef = dictionaryService.getAspect(aspectTypeQName);
boolean updated = false;
if (aspectDef != null)
{
// Remove default properties
Map<QName,PropertyDefinition> propertyDefs = aspectDef.getProperties();
Set<QName> propertyToRemoveQNames = propertyDefs.keySet();
nodeDAO.removeNodeProperties(nodeId, propertyToRemoveQNames);
// Remove child associations
// We have to iterate over the associations and remove all those between the parent and child
final List<Pair<Long, ChildAssociationRef>> assocsToDelete = new ArrayList<Pair<Long, ChildAssociationRef>>(5);
final List<Pair<Long, NodeRef>> nodesToDelete = new ArrayList<Pair<Long, NodeRef>>(5);
NodeDAO.ChildAssocRefQueryCallback callback = new NodeDAO.ChildAssocRefQueryCallback()
{
public boolean handle(
Pair<Long, ChildAssociationRef> childAssocPair,
Pair<Long, NodeRef> parentNodePair,
Pair<Long, NodeRef> childNodePair
)
{
// Double check that it's not a primary association. If so, we can't delete it and
// have to delete the child node directly and with full archival.
if (childAssocPair.getSecond().isPrimary())
{
nodesToDelete.add(childNodePair);
}
else
{
assocsToDelete.add(childAssocPair);
}
// More results
return true;
}
public boolean preLoadNodes()
{
return true;
}
public void done()
{
}
};
// Get all the QNames to remove
Set<QName> assocTypeQNamesToRemove = new HashSet<QName>(aspectDef.getChildAssociations().keySet());
nodeDAO.getChildAssocs(nodeId, assocTypeQNamesToRemove, callback);
// Delete all the collected associations
for (Pair<Long, ChildAssociationRef> assocPair : assocsToDelete)
{
updated = true;
Long assocId = assocPair.getFirst();
ChildAssociationRef assocRef = assocPair.getSecond();
// delete the association instance - it is not primary
invokeBeforeDeleteChildAssociation(assocRef);
nodeDAO.deleteChildAssoc(assocId);
invokeOnDeleteChildAssociation(assocRef);
}
// Cascade-delete any nodes that were attached to primary associations
for (Pair<Long, NodeRef> childNodePair : nodesToDelete)
{
NodeRef childNodeRef = childNodePair.getSecond();
this.deleteNode(childNodeRef);
}
// Remove regular associations
Map<QName, AssociationDefinition> nodeAssocDefs = aspectDef.getAssociations();
Set<QName> nodeAssocTypeQNamesToRemove = new HashSet<QName>(13);
for (Map.Entry<QName, AssociationDefinition> entry : nodeAssocDefs.entrySet())
{
if (entry.getValue().isChild())
{
// Not interested in child assocs
continue;
}
nodeAssocTypeQNamesToRemove.add(entry.getKey());
}
int assocsDeleted = nodeDAO.removeNodeAssocsToAndFrom(nodeId, nodeAssocTypeQNamesToRemove);
updated = updated || assocsDeleted > 0;
}
// Invoke policy behaviours
if (updated)
{
invokeOnUpdateNode(nodeRef);
}
if (hadAspect)
{
invokeOnRemoveAspect(nodeRef, aspectTypeQName);
}
// Index
nodeIndexer.indexUpdateNode(nodeRef);
}
/**
* Performs a check on the set of node aspects
*/
public boolean hasAspect(NodeRef nodeRef, QName aspectQName) throws InvalidNodeRefException, InvalidAspectException
{
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
return nodeDAO.hasNodeAspect(nodePair.getFirst(), aspectQName);
}
public Set<QName> getAspects(NodeRef nodeRef) throws InvalidNodeRefException
{
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
return nodeDAO.getNodeAspects(nodePair.getFirst());
}
/**
* Delete Node
*/
public void deleteNode(NodeRef nodeRef)
{
// Pair contains NodeId, NodeRef
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
Long nodeId = nodePair.getFirst();
Boolean requiresDelete = null;
// get the primary parent-child relationship before it is gone
Pair<Long, ChildAssociationRef> childAssocPair = nodeDAO.getPrimaryParentAssoc(nodeId);
ChildAssociationRef childAssocRef = childAssocPair.getSecond();
// get type and aspect QNames as they will be unavailable after the delete
QName nodeTypeQName = nodeDAO.getNodeType(nodeId);
Set<QName> nodeAspectQNames = nodeDAO.getNodeAspects(nodeId);
StoreRef storeRef = nodeRef.getStoreRef();
StoreRef archiveStoreRef = storeArchiveMap.get(storeRef);
/**
* Work out whether we need to archive or delete the node.
*/
if (archiveStoreRef == null)
{
// The store does not specify archiving
requiresDelete = true;
}
else
{
// get the type and check if we need archiving.
TypeDefinition typeDef = dictionaryService.getType(nodeTypeQName);
if (typeDef != null)
{
Boolean requiresArchive = typeDef.getArchive();
if (requiresArchive != null)
{
requiresDelete = !requiresArchive;
}
}
// If the type hasn't asked for deletion, check whether any applied aspects have
Iterator<QName> i = nodeAspectQNames.iterator();
while ((requiresDelete == null || !requiresDelete) && i.hasNext())
{
QName nodeAspectQName = i.next();
AspectDefinition aspectDef = dictionaryService.getAspect(nodeAspectQName);
if (aspectDef != null)
{
Boolean requiresArchive = aspectDef.getArchive();
if (requiresArchive != null)
{
requiresDelete = !requiresArchive;
}
}
}
}
/**
* Now we have worked out whether to archive or delete, go ahead and do it
*/
if (requiresDelete == null || requiresDelete)
{
// remove the deleted node from the list of new nodes
untrackNewNodeRef(nodeRef);
// track the deletion of this node - so we can prevent new associations to it.
trackDeletedNodeRef(nodeRef);
// Invoke policy behaviours
invokeBeforeDeleteNode(nodeRef);
// Cascade delecte as required
deletePrimaryChildrenNotArchived(nodePair);
// perform a normal deletion
nodeDAO.deleteNode(nodeId);
// Invoke policy behaviours
invokeOnDeleteNode(childAssocRef, nodeTypeQName, nodeAspectQNames, false);
// Index
nodeIndexer.indexDeleteNode(childAssocRef);
}
else
{
/*
* Go ahead and archive the node
*
* Archiving will take responsibility for firing the policy behaviours on
* the nodes it modifies.
*/
archiveNode(nodeRef, archiveStoreRef);
}
}
/**
* delete primary children - private method for deleteNode.
*
* recurses through children when deleting a node. Does not archive.
*/
private void deletePrimaryChildrenNotArchived(Pair<Long, NodeRef> nodePair)
{
Long nodeId = nodePair.getFirst();
// Get the node's primary children
final List<Pair<Long, NodeRef>> childNodePairs = new ArrayList<Pair<Long, NodeRef>>(5);
final Map<Long, ChildAssociationRef> childAssocRefsByChildId = new HashMap<Long, ChildAssociationRef>(5);
NodeDAO.ChildAssocRefQueryCallback callback = new NodeDAO.ChildAssocRefQueryCallback()
{
public boolean handle(
Pair<Long, ChildAssociationRef> childAssocPair,
Pair<Long, NodeRef> parentNodePair,
Pair<Long, NodeRef> childNodePair
)
{
// Add it
childNodePairs.add(childNodePair);
childAssocRefsByChildId.put(childNodePair.getFirst(), childAssocPair.getSecond());
// More results
return true;
}
public boolean preLoadNodes()
{
return true;
}
public void done()
{
}
};
// Get all the QNames to remove
nodeDAO.getChildAssocs(nodeId, null, null, null, Boolean.TRUE, null, callback);
// Each child must be deleted
for (Pair<Long, NodeRef> childNodePair : childNodePairs)
{
// Fire node policies. This ensures that each node in the hierarchy gets a notification fired.
Long childNodeId = childNodePair.getFirst();
NodeRef childNodeRef = childNodePair.getSecond();
QName childNodeType = nodeDAO.getNodeType(childNodeId);
Set<QName> childNodeQNames = nodeDAO.getNodeAspects(childNodeId);
ChildAssociationRef childParentAssocRef = childAssocRefsByChildId.get(childNodeId);
// remove the deleted node from the list of new nodes
untrackNewNodeRef(childNodeRef);
// track the deletion of this node - so we can prevent new associations to it.
trackDeletedNodeRef(childNodeRef);
invokeBeforeDeleteNode(childNodeRef);
// Cascade first
// This ensures that the beforeDelete policy is fired for all nodes in the hierarchy before
// the actual delete starts.
deletePrimaryChildrenNotArchived(childNodePair);
// Delete the child
nodeDAO.deleteNode(childNodeId);
invokeOnDeleteNode(childParentAssocRef, childNodeType, childNodeQNames, false);
// lose interest in tracking this node ref
untrackNewNodeRef(childNodeRef);
}
}
public ChildAssociationRef addChild(NodeRef parentRef, NodeRef childRef, QName assocTypeQName, QName assocQName)
{
return addChild(Collections.singletonList(parentRef), childRef, assocTypeQName, assocQName).get(0);
}
public List<ChildAssociationRef> addChild(Collection<NodeRef> parentRefs, NodeRef childRef, QName assocTypeQName, QName assocQName)
{
// Get the node's name, if present
Pair<Long, NodeRef> childNodePair = getNodePairNotNull(childRef);
Long childNodeId = childNodePair.getFirst();
Map<QName, Serializable> childNodeProperties = nodeDAO.getNodeProperties(childNodePair.getFirst());
String childNodeName = extractNameProperty(childNodeProperties);
if (childNodeName == null)
{
childNodeName = childRef.getId();
}
List <ChildAssociationRef> childAssociationRefs = new ArrayList<ChildAssociationRef>(parentRefs.size());
List<Pair<Long, NodeRef>> parentNodePairs = new ArrayList<Pair<Long, NodeRef>>(parentRefs.size());
for (NodeRef parentRef : parentRefs)
{
if (isDeletedNodeRef(parentRef))
{
throw new InvalidNodeRefException("The parent node has been deleted", parentRef);
}
Pair<Long, NodeRef> parentNodePair = getNodePairNotNull(parentRef);
Long parentNodeId = parentNodePair.getFirst();
parentNodePairs.add(parentNodePair);
// make the association
Pair<Long, ChildAssociationRef> childAssocPair = nodeDAO.newChildAssoc(
parentNodeId, childNodeId,
assocTypeQName, assocQName,
childNodeName);
childAssociationRefs.add(childAssocPair.getSecond());
}
// check that the child addition of the child has not created a cyclic relationship
// this functionality is provided for free in getPath
getPaths(childRef, false);
// Invoke policy behaviours
for (ChildAssociationRef childAssocRef : childAssociationRefs)
{
invokeOnCreateChildAssociation(childAssocRef, false);
}
// Get the type associated with the association
// The association may be sourced on an aspect, which may itself mandate further aspects
for (Pair<Long, NodeRef> parentNodePair : parentNodePairs)
{
addAspectsAndPropertiesAssoc(parentNodePair, assocTypeQName, null, null, null, null, false);
}
// Index
for (ChildAssociationRef childAssocRef : childAssociationRefs)
{
nodeIndexer.indexCreateChildAssociation(childAssocRef);
}
return childAssociationRefs;
}
public void removeChild(NodeRef parentRef, NodeRef childRef) throws InvalidNodeRefException
{
final Pair<Long, NodeRef> parentNodePair = getNodePairNotNull(parentRef);
final Long parentNodeId = parentNodePair.getFirst();
final Pair<Long, NodeRef> childNodePair = getNodePairNotNull(childRef);
final Long childNodeId = childNodePair.getFirst();
// Get the primary parent association for the child
Pair<Long, ChildAssociationRef> primaryChildAssocPair = nodeDAO.getPrimaryParentAssoc(childNodeId);
// We can shortcut if our parent is also the primary parent
if (primaryChildAssocPair != null)
{
NodeRef primaryParentNodeRef = primaryChildAssocPair.getSecond().getParentRef();
if (primaryParentNodeRef.equals(parentRef))
{
// Shortcut - just delete the child node
deleteNode(childRef);
return;
}
}
// We have to iterate over the associations and remove all those between the parent and child
final List<Pair<Long, ChildAssociationRef>> assocsToDelete = new ArrayList<Pair<Long, ChildAssociationRef>>(5);
NodeDAO.ChildAssocRefQueryCallback callback = new NodeDAO.ChildAssocRefQueryCallback()
{
public boolean handle(
Pair<Long, ChildAssociationRef> childAssocPair,
Pair<Long, NodeRef> parentNodePair,
Pair<Long, NodeRef> childNodePair)
{
// Ignore if the child is not ours (redundant check)
if (!childNodePair.getFirst().equals(childNodeId))
{
return false;
}
// Add it
assocsToDelete.add(childAssocPair);
// More results
return true;
}
public boolean preLoadNodes()
{
return false;
}
public void done()
{
}
};
nodeDAO.getChildAssocs(parentNodeId, childNodeId, null, null, null, null, callback);
// Delete all the collected associations
for (Pair<Long, ChildAssociationRef> assocPair : assocsToDelete)
{
Long assocId = assocPair.getFirst();
ChildAssociationRef assocRef = assocPair.getSecond();
// delete the association instance - it is not primary
invokeBeforeDeleteChildAssociation(assocRef);
nodeDAO.deleteChildAssoc(assocId);
invokeOnDeleteChildAssociation(assocRef);
// Index
nodeIndexer.indexDeleteChildAssociation(assocRef);
}
// Done
}
public boolean removeChildAssociation(ChildAssociationRef childAssocRef)
{
Long parentNodeId = getNodePairNotNull(childAssocRef.getParentRef()).getFirst();
Long childNodeId = getNodePairNotNull(childAssocRef.getChildRef()).getFirst();
QName assocTypeQName = childAssocRef.getTypeQName();
QName assocQName = childAssocRef.getQName();
Pair<Long, ChildAssociationRef> assocPair = nodeDAO.getChildAssoc(
parentNodeId, childNodeId, assocTypeQName, assocQName);
if (assocPair == null)
{
// No association exists
return false;
}
Long assocId = assocPair.getFirst();
ChildAssociationRef assocRef = assocPair.getSecond();
if (assocRef.isPrimary())
{
NodeRef childNodeRef = assocRef.getChildRef();
// Delete the child node
this.deleteNode(childNodeRef);
// Done
return true;
}
else
{
// Delete the association
invokeBeforeDeleteChildAssociation(childAssocRef);
nodeDAO.deleteChildAssoc(assocId);
invokeOnDeleteChildAssociation(childAssocRef);
// Index
nodeIndexer.indexDeleteChildAssociation(childAssocRef);
// Done
return true;
}
}
public boolean removeSeconaryChildAssociation(ChildAssociationRef childAssocRef)
{
Long parentNodeId = getNodePairNotNull(childAssocRef.getParentRef()).getFirst();
Long childNodeId = getNodePairNotNull(childAssocRef.getChildRef()).getFirst();
QName assocTypeQName = childAssocRef.getTypeQName();
QName assocQName = childAssocRef.getQName();
Pair<Long, ChildAssociationRef> assocPair = nodeDAO.getChildAssoc(
parentNodeId, childNodeId, assocTypeQName, assocQName);
if (assocPair == null)
{
// No association exists
return false;
}
Long assocId = assocPair.getFirst();
ChildAssociationRef assocRef = assocPair.getSecond();
if (assocRef.isPrimary())
{
throw new IllegalArgumentException(
"removeSeconaryChildAssociation can not be applied to a primary association: \n" +
" Child Assoc: " + assocRef);
}
// Delete the secondary association
nodeDAO.deleteChildAssoc(assocId);
invokeOnDeleteChildAssociation(childAssocRef);
// Index
nodeIndexer.indexDeleteChildAssociation(childAssocRef);
// Done
return true;
}
public Serializable getProperty(NodeRef nodeRef, QName qname) throws InvalidNodeRefException
{
Long nodeId = getNodePairNotNull(nodeRef).getFirst();
// Spoof referencable properties
if (qname.equals(ContentModel.PROP_STORE_PROTOCOL))
{
return nodeRef.getStoreRef().getProtocol();
}
else if (qname.equals(ContentModel.PROP_STORE_IDENTIFIER))
{
return nodeRef.getStoreRef().getIdentifier();
}
else if (qname.equals(ContentModel.PROP_NODE_UUID))
{
return nodeRef.getId();
}
else if (qname.equals(ContentModel.PROP_NODE_DBID))
{
return nodeId;
}
Serializable property = nodeDAO.getNodeProperty(nodeId, qname);
// check if we need to provide a spoofed name
if (property == null && qname.equals(ContentModel.PROP_NAME))
{
return nodeRef.getId();
}
// done
return property;
}
public Map<QName, Serializable> getProperties(NodeRef nodeRef) throws InvalidNodeRefException
{
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
return getPropertiesImpl(nodePair);
}
/**
* Gets, converts and adds the intrinsic properties to the current node's properties
*/
private Map<QName, Serializable> getPropertiesImpl(Pair<Long, NodeRef> nodePair) throws InvalidNodeRefException
{
Long nodeId = nodePair.getFirst();
Map<QName, Serializable> nodeProperties = nodeDAO.getNodeProperties(nodeId);
// done
return nodeProperties;
}
public Long getNodeAclId(NodeRef nodeRef) throws InvalidNodeRefException
{
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
return getAclIDImpl(nodePair);
}
/**
* Gets, converts and adds the intrinsic properties to the current node's properties
*/
private Long getAclIDImpl(Pair<Long, NodeRef> nodePair) throws InvalidNodeRefException
{
Long nodeId = nodePair.getFirst();
Long aclID = nodeDAO.getNodeAclId(nodeId);
// done
return aclID;
}
/**
* Performs additional tasks associated with setting a property.
*
* @return Returns <tt>true</tt> if any work was done by this method
*/
private boolean setPropertiesCommonWork(Pair<Long, NodeRef> nodePair, Map<QName, Serializable> properties)
{
Long nodeId = nodePair.getFirst();
boolean changed = false;
// cm:name special handling
if (properties.containsKey(ContentModel.PROP_NAME))
{
String name = extractNameProperty(properties);
Pair<Long, ChildAssociationRef> primaryParentAssocPair = nodeDAO.getPrimaryParentAssoc(nodeId);
if (primaryParentAssocPair != null)
{
String oldName = extractNameProperty(nodeDAO.getNodeProperties(nodeId));
String newName = DefaultTypeConverter.INSTANCE.convert(String.class, name);
changed = setChildNameUnique(nodePair, newName, oldName);
}
}
// Done
return changed;
}
/**
* Gets the properties map, sets the value (null is allowed) and checks that the new set
* of properties is valid.
*
* @see DbNodeServiceImpl.NullPropertyValue
*/
public void setProperty(NodeRef nodeRef, QName qname, Serializable value) throws InvalidNodeRefException
{
ParameterCheck.mandatory("nodeRef", nodeRef);
ParameterCheck.mandatory("qname", qname);
// The UUID cannot be explicitly changed
if (qname.equals(ContentModel.PROP_NODE_UUID))
{
throw new IllegalArgumentException("The node UUID cannot be changed.");
}
// get the node
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
// Invoke policy behaviour
invokeBeforeUpdateNode(nodeRef);
// cm:name special handling
setPropertiesCommonWork(
nodePair,
Collections.singletonMap(qname, value));
// Add the property and all required defaults
boolean changed = addAspectsAndProperties(
nodePair, null,
null, null,
null, Collections.singletonMap(qname, value), false);
if (changed)
{
// Invoke policy behaviour
invokeOnUpdateNode(nodeRef);
// Index
nodeIndexer.indexUpdateNode(nodeRef);
}
}
/**
* Ensures that all required properties are present on the node and copies the
* property values to the <code>Node</code>.
* <p>
* To remove a property, <b>remove it from the map</b> before calling this method.
* Null-valued properties are allowed.
* <p>
* If any of the values are null, a marker object is put in to mimic nulls. They will be turned back into
* a real nulls when the properties are requested again.
*
* @see Node#getProperties()
*/
public void setProperties(NodeRef nodeRef, Map<QName, Serializable> properties) throws InvalidNodeRefException
{
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
// Invoke policy behaviours
invokeBeforeUpdateNode(nodeRef);
// SetProperties common tasks
setPropertiesCommonWork(nodePair, properties);
// Set properties and defaults, overwriting the existing properties
boolean changed = addAspectsAndProperties(nodePair, null, null, null, null, properties, true);
if (changed)
{
// Invoke policy behaviours
invokeOnUpdateNode(nodeRef);
// Index
nodeIndexer.indexUpdateNode(nodeRef);
}
}
public void addProperties(NodeRef nodeRef, Map<QName, Serializable> properties) throws InvalidNodeRefException
{
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
// Invoke policy behaviours
invokeBeforeUpdateNode(nodeRef);
// cm:name special handling
setPropertiesCommonWork(nodePair, properties);
// Add properties and defaults
boolean changed = addAspectsAndProperties(nodePair, null, null, null, null, properties, false);
if (changed)
{
// Invoke policy behaviours
invokeOnUpdateNode(nodeRef);
// Index
nodeIndexer.indexUpdateNode(nodeRef);
}
}
public void removeProperty(NodeRef nodeRef, QName qname) throws InvalidNodeRefException
{
// Get the node
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
Long nodeId = nodePair.getFirst();
// Invoke policy behaviours
invokeBeforeUpdateNode(nodeRef);
// Get the values before
Map<QName, Serializable> propertiesBefore = getPropertiesImpl(nodePair);
// cm:name special handling
if (qname.equals(ContentModel.PROP_NAME))
{
String oldName = extractNameProperty(nodeDAO.getNodeProperties(nodeId));
String newName = null;
setChildNameUnique(nodePair, newName, oldName);
}
// Remove
nodeDAO.removeNodeProperties(nodeId, Collections.singleton(qname));
// Invoke policy behaviours
Map<QName, Serializable> propertiesAfter = getPropertiesImpl(nodePair);
invokeOnUpdateNode(nodeRef);
invokeOnUpdateProperties(nodeRef, propertiesBefore, propertiesAfter);
// Index
nodeIndexer.indexUpdateNode(nodeRef);
}
public Collection<NodeRef> getParents(NodeRef nodeRef) throws InvalidNodeRefException
{
List<ChildAssociationRef> parentAssocs = getParentAssocs(
nodeRef,
RegexQNamePattern.MATCH_ALL,
RegexQNamePattern.MATCH_ALL);
// Copy into the set to avoid duplicates
Set<NodeRef> parentNodeRefs = new HashSet<NodeRef>(parentAssocs.size());
for (ChildAssociationRef parentAssoc : parentAssocs)
{
NodeRef parentNodeRef = parentAssoc.getParentRef();
parentNodeRefs.add(parentNodeRef);
}
// Done
return new ArrayList<NodeRef>(parentNodeRefs);
}
/**
* Filters out any associations if their qname is not a match to the given pattern.
*/
public List<ChildAssociationRef> getParentAssocs(
final NodeRef nodeRef,
final QNamePattern typeQNamePattern,
final QNamePattern qnamePattern)
{
// Get the node
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
Long nodeId = nodePair.getFirst();
final List<ChildAssociationRef> results = new ArrayList<ChildAssociationRef>(10);
// We have a callback handler to filter results
ChildAssocRefQueryCallback callback = new ChildAssocRefQueryCallback()
{
public boolean preLoadNodes()
{
return false;
}
public boolean handle(
Pair<Long, ChildAssociationRef> childAssocPair,
Pair<Long, NodeRef> parentNodePair,
Pair<Long, NodeRef> childNodePair)
{
if (!typeQNamePattern.isMatch(childAssocPair.getSecond().getTypeQName()))
{
return true;
}
if (!qnamePattern.isMatch(childAssocPair.getSecond().getQName()))
{
return true;
}
results.add(childAssocPair.getSecond());
return true;
}
public void done()
{
}
};
// Get the assocs pointing to it
QName typeQName = (typeQNamePattern instanceof QName) ? (QName) typeQNamePattern : null;
QName qname = (qnamePattern instanceof QName) ? (QName) qnamePattern : null;
nodeDAO.getParentAssocs(nodeId, typeQName, qname, null, callback);
// done
return results;
}
/**
* Filters out any associations if their qname is not a match to the given pattern.
*/
public List<ChildAssociationRef> getChildAssocs(NodeRef nodeRef, final QNamePattern typeQNamePattern, final QNamePattern qnamePattern)
{
return getChildAssocs(nodeRef, typeQNamePattern, qnamePattern, true) ;
}
/**
* Filters out any associations if their qname is not a match to the given pattern.
*/
public List<ChildAssociationRef> getChildAssocs(
NodeRef nodeRef,
final QNamePattern typeQNamePattern,
final QNamePattern qnamePattern,
final boolean preload)
{
// Get the node
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
Long nodeId = nodePair.getFirst();
final List<ChildAssociationRef> results = new ArrayList<ChildAssociationRef>(10);
// We have a callback handler to filter results
ChildAssocRefQueryCallback callback = new ChildAssocRefQueryCallback()
{
public boolean preLoadNodes()
{
return preload;
}
public boolean handle(
Pair<Long, ChildAssociationRef> childAssocPair,
Pair<Long, NodeRef> parentNodePair,
Pair<Long, NodeRef> childNodePair)
{
if (!typeQNamePattern.isMatch(childAssocPair.getSecond().getTypeQName()))
{
return true;
}
if (!qnamePattern.isMatch(childAssocPair.getSecond().getQName()))
{
return true;
}
results.add(childAssocPair.getSecond());
return true;
}
public void done()
{
}
};
// Get the assocs pointing to it
QName typeQName = (typeQNamePattern instanceof QName) ? (QName) typeQNamePattern : null;
QName qname = (qnamePattern instanceof QName) ? (QName) qnamePattern : null;
nodeDAO.getChildAssocs(nodeId, null, typeQName, qname, null, null, callback);
// sort the results
List<ChildAssociationRef> orderedList = reorderChildAssocs(results);
// Done
return orderedList;
}
public List<ChildAssociationRef> getChildAssocs(NodeRef nodeRef, Set<QName> childNodeTypeQNames)
{
// Get the node
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
Long nodeId = nodePair.getFirst();
final List<ChildAssociationRef> results = new ArrayList<ChildAssociationRef>(100);
NodeDAO.ChildAssocRefQueryCallback callback = new NodeDAO.ChildAssocRefQueryCallback()
{
public boolean handle(
Pair<Long, ChildAssociationRef> childAssocPair,
Pair<Long, NodeRef> parentNodePair,
Pair<Long, NodeRef> childNodePair)
{
results.add(childAssocPair.getSecond());
// More results
return true;
}
public boolean preLoadNodes()
{
return true;
}
public void done()
{
}
};
// Get all child associations with the specific qualified name
nodeDAO.getChildAssocsByChildTypes(nodeId, childNodeTypeQNames, callback);
// Sort the results
List<ChildAssociationRef> orderedList = reorderChildAssocs(results);
// Done
return orderedList;
}
private List<ChildAssociationRef> reorderChildAssocs(Collection<ChildAssociationRef> childAssocRefs)
{
// shortcut if there are no assocs
if (childAssocRefs.size() == 0)
{
return Collections.emptyList();
}
// sort results
ArrayList<ChildAssociationRef> orderedList = new ArrayList<ChildAssociationRef>(childAssocRefs);
Collections.sort(orderedList);
// list of results
int nthSibling = 0;
Iterator<ChildAssociationRef> iterator = orderedList.iterator();
while(iterator.hasNext())
{
ChildAssociationRef childAssocRef = iterator.next();
childAssocRef.setNthSibling(nthSibling);
nthSibling++;
}
// done
return orderedList;
}
public NodeRef getChildByName(NodeRef nodeRef, QName assocTypeQName, String childName)
{
// Get the node
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
Long nodeId = nodePair.getFirst();
Pair<Long, ChildAssociationRef> childAssocPair = nodeDAO.getChildAssoc(nodeId, assocTypeQName, childName);
if (childAssocPair != null)
{
return childAssocPair.getSecond().getChildRef();
}
else
{
return null;
}
}
public List<ChildAssociationRef> getChildrenByName(NodeRef nodeRef, QName assocTypeQName, Collection<String> childNames)
{
// Get the node
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
Long nodeId = nodePair.getFirst();
final List<ChildAssociationRef> results = new ArrayList<ChildAssociationRef>(100);
NodeDAO.ChildAssocRefQueryCallback callback = new NodeDAO.ChildAssocRefQueryCallback()
{
public boolean handle(
Pair<Long, ChildAssociationRef> childAssocPair,
Pair<Long, NodeRef> parentNodePair,
Pair<Long, NodeRef> childNodePair)
{
results.add(childAssocPair.getSecond());
// More results
return true;
}
public boolean preLoadNodes()
{
return true;
}
public void done()
{
}
};
// Get all child associations with the specific qualified name
nodeDAO.getChildAssocs(nodeId, assocTypeQName, childNames, callback);
// Sort the results
List<ChildAssociationRef> orderedList = reorderChildAssocs(results);
// Done
return orderedList;
}
public ChildAssociationRef getPrimaryParent(NodeRef nodeRef) throws InvalidNodeRefException
{
// Get the node
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
Long nodeId = nodePair.getFirst();
// get the primary parent assoc
Pair<Long, ChildAssociationRef> assocPair = nodeDAO.getPrimaryParentAssoc(nodeId);
// done - the assoc may be null for a root node
ChildAssociationRef assocRef = null;
if (assocPair == null)
{
assocRef = new ChildAssociationRef(null, null, null, nodeRef);
}
else
{
assocRef = assocPair.getSecond();
}
return assocRef;
}
public AssociationRef createAssociation(NodeRef sourceRef, NodeRef targetRef, QName assocTypeQName)
throws InvalidNodeRefException, AssociationExistsException
{
Pair<Long, NodeRef> sourceNodePair = getNodePairNotNull(sourceRef);
long sourceNodeId = sourceNodePair.getFirst();
Pair<Long, NodeRef> targetNodePair = getNodePairNotNull(targetRef);
long targetNodeId = targetNodePair.getFirst();
// we are sure that the association doesn't exist - make it
Long assocId = nodeDAO.newNodeAssoc(sourceNodeId, targetNodeId, assocTypeQName);
AssociationRef assocRef = new AssociationRef(assocId, sourceRef, assocTypeQName, targetRef);
// Invoke policy behaviours
invokeOnCreateAssociation(assocRef);
// Add missing aspects
addAspectsAndPropertiesAssoc(sourceNodePair, assocTypeQName, null, null, null, null, false);
return assocRef;
}
public Collection<ChildAssociationRef> getChildAssocsWithoutParentAssocsOfType(NodeRef parent, QName assocTypeQName)
{
// Get the parent node
Pair<Long, NodeRef> nodePair = getNodePairNotNull(parent);
Long parentNodeId = nodePair.getFirst();
final List<ChildAssociationRef> results = new ArrayList<ChildAssociationRef>(100);
NodeDAO.ChildAssocRefQueryCallback callback = new NodeDAO.ChildAssocRefQueryCallback()
{
public boolean handle(Pair<Long, ChildAssociationRef> childAssocPair, Pair<Long, NodeRef> parentNodePair,
Pair<Long, NodeRef> childNodePair)
{
results.add(childAssocPair.getSecond());
// More results
return true;
}
public boolean preLoadNodes()
{
return false;
}
public void done()
{
}
};
// Get the child associations that meet the criteria
nodeDAO.getChildAssocsWithoutParentAssocsOfType(parentNodeId, assocTypeQName, callback);
// done
return results;
}
/**
* Specific properties <b>not</b> supported by {@link #getChildAssocsByPropertyValue(NodeRef, QName, Serializable)}
*/
private static List<QName> getChildAssocsByPropertyValueBannedProps = new ArrayList<QName>();
static
{
getChildAssocsByPropertyValueBannedProps.add(ContentModel.PROP_NODE_DBID);
getChildAssocsByPropertyValueBannedProps.add(ContentModel.PROP_NODE_UUID);
getChildAssocsByPropertyValueBannedProps.add(ContentModel.PROP_NAME);
getChildAssocsByPropertyValueBannedProps.add(ContentModel.PROP_MODIFIED);
getChildAssocsByPropertyValueBannedProps.add(ContentModel.PROP_MODIFIER);
getChildAssocsByPropertyValueBannedProps.add(ContentModel.PROP_CREATED);
getChildAssocsByPropertyValueBannedProps.add(ContentModel.PROP_CREATOR);
}
@Override
public List<ChildAssociationRef> getChildAssocsByPropertyValue(
NodeRef nodeRef,
QName propertyQName,
Serializable value)
{
// Get the node
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
Long nodeId = nodePair.getFirst();
// Check the QName is not one of the "special" system maintained ones.
if (getChildAssocsByPropertyValueBannedProps.contains(propertyQName))
{
throw new IllegalArgumentException(
"getChildAssocsByPropertyValue does not allow search of system maintained properties: " + propertyQName);
}
final List<ChildAssociationRef> results = new ArrayList<ChildAssociationRef>(10);
// We have a callback handler to filter results
ChildAssocRefQueryCallback callback = new ChildAssocRefQueryCallback()
{
public boolean preLoadNodes()
{
return false;
}
public boolean handle(
Pair<Long, ChildAssociationRef> childAssocPair,
Pair<Long, NodeRef> parentNodePair,
Pair<Long, NodeRef> childNodePair)
{
results.add(childAssocPair.getSecond());
return true;
}
public void done()
{
}
};
// Get the assocs pointing to it
nodeDAO.getChildAssocsByPropertyValue(nodeId, propertyQName, value, callback);
// sort the results
List<ChildAssociationRef> orderedList = reorderChildAssocs(results);
// Done
return orderedList;
}
public void removeAssociation(NodeRef sourceRef, NodeRef targetRef, QName assocTypeQName)
throws InvalidNodeRefException
{
Pair<Long, NodeRef> sourceNodePair = getNodePairNotNull(sourceRef);
long sourceNodeId = sourceNodePair.getFirst();
Pair<Long, NodeRef> targetNodePair = getNodePairNotNull(targetRef);
long targetNodeId = targetNodePair.getFirst();
// delete it
int assocsDeleted = nodeDAO.removeNodeAssoc(sourceNodeId, targetNodeId, assocTypeQName);
if (assocsDeleted > 0)
{
AssociationRef assocRef = new AssociationRef(sourceRef, assocTypeQName, targetRef);
// Invoke policy behaviours
invokeOnDeleteAssociation(assocRef);
}
}
public AssociationRef getAssoc(Long id)
{
return nodeDAO.getNodeAssoc(id).getSecond();
}
public List<AssociationRef> getTargetAssocs(NodeRef sourceRef, QNamePattern qnamePattern)
{
Pair<Long, NodeRef> sourceNodePair = getNodePairNotNull(sourceRef);
long sourceNodeId = sourceNodePair.getFirst();
// get all assocs to target
Collection<Pair<Long, AssociationRef>> assocPairs = nodeDAO.getTargetNodeAssocs(sourceNodeId);
List<AssociationRef> nodeAssocRefs = new ArrayList<AssociationRef>(assocPairs.size());
for (Pair<Long, AssociationRef> assocPair : assocPairs)
{
AssociationRef assocRef = assocPair.getSecond();
// check qname pattern
if (!qnamePattern.isMatch(assocRef.getTypeQName()))
{
continue; // the assoc name doesn't match the pattern given
}
nodeAssocRefs.add(assocRef);
}
// done
return nodeAssocRefs;
}
public List<AssociationRef> getSourceAssocs(NodeRef targetRef, QNamePattern qnamePattern)
{
Pair<Long, NodeRef> targetNodePair = getNodePairNotNull(targetRef);
long targetNodeId = targetNodePair.getFirst();
// get all assocs to target
Collection<Pair<Long, AssociationRef>> assocPairs = nodeDAO.getSourceNodeAssocs(targetNodeId);
List<AssociationRef> nodeAssocRefs = new ArrayList<AssociationRef>(assocPairs.size());
for (Pair<Long, AssociationRef> assocPair : assocPairs)
{
AssociationRef assocRef = assocPair.getSecond();
// check qname pattern
if (!qnamePattern.isMatch(assocRef.getTypeQName()))
{
continue; // the assoc name doesn't match the pattern given
}
nodeAssocRefs.add(assocRef);
}
// done
return nodeAssocRefs;
}
/**
* @see #getPaths(NodeRef, boolean)
* @see #prependPaths(Node, Path, Collection, Stack, boolean)
*/
public Path getPath(NodeRef nodeRef) throws InvalidNodeRefException
{
List<Path> paths = getPaths(nodeRef, true); // checks primary path count
if (paths.size() == 1)
{
return paths.get(0); // we know there is only one
}
throw new RuntimeException("Primary path count not checked"); // checked by getPaths()
}
/**
* When searching for <code>primaryOnly == true</code>, checks that there is exactly
* one path.
* @see #prependPaths(Node, Path, Collection, Stack, boolean)
*/
public List<Path> getPaths(NodeRef nodeRef, boolean primaryOnly) throws InvalidNodeRefException
{
// get the starting node
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
return nodeDAO.getPaths(nodePair, primaryOnly);
}
/**
* Archives the node without the <b>cm:auditable</b> aspect behaviour
*/
private void archiveNode(NodeRef nodeRef, StoreRef archiveStoreRef)
{
boolean wasDisabled = policyBehaviourFilter.disableBehaviour(ContentModel.ASPECT_AUDITABLE);
try
{
archiveNodeImpl(nodeRef, archiveStoreRef);
}
finally
{
if (!wasDisabled)
{
policyBehaviourFilter.enableBehaviour(ContentModel.ASPECT_AUDITABLE);
}
}
}
private void archiveNodeImpl(NodeRef nodeRef, StoreRef archiveStoreRef)
{
Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
Long nodeId = nodePair.getFirst();
Pair<Long, ChildAssociationRef> primaryParentAssocPair = nodeDAO.getPrimaryParentAssoc(nodeId);
Set<QName> newAspects = new HashSet<QName>(5);
Map<QName, Serializable> existingProperties = nodeDAO.getNodeProperties(nodeId);
Map<QName, Serializable> newProperties = new HashMap<QName, Serializable>(11);
// add the aspect
newAspects.add(ContentModel.ASPECT_ARCHIVED);
newProperties.put(ContentModel.PROP_ARCHIVED_BY, AuthenticationUtil.getFullyAuthenticatedUser());
newProperties.put(ContentModel.PROP_ARCHIVED_DATE, new Date());
newProperties.put(ContentModel.PROP_ARCHIVED_ORIGINAL_PARENT_ASSOC, primaryParentAssocPair.getSecond());
Serializable originalOwner = existingProperties.get(ContentModel.PROP_OWNER);
Serializable originalCreator = existingProperties.get(ContentModel.PROP_CREATOR);
if (originalOwner != null || originalCreator != null)
{
newProperties.put(
ContentModel.PROP_ARCHIVED_ORIGINAL_OWNER,
originalOwner != null ? originalOwner : originalCreator);
}
// change the node ownership
newAspects.add(ContentModel.ASPECT_OWNABLE);
newProperties.put(ContentModel.PROP_OWNER, AuthenticationUtil.getFullyAuthenticatedUser());
// Set the aspects and properties
nodeDAO.addNodeProperties(nodeId, newProperties);
nodeDAO.addNodeAspects(nodeId, newAspects);
// move the node
Pair<Long, NodeRef> archiveStoreRootNodePair = nodeDAO.getRootNode(archiveStoreRef);
moveNode(
nodeRef,
archiveStoreRootNodePair.getSecond(),
ContentModel.ASSOC_CHILDREN,
NodeArchiveService.QNAME_ARCHIVED_ITEM);
}
/**
* {@inheritDoc}
*
* Archives the node without the <b>cm:auditable</b> aspect behaviour
*/
public NodeRef restoreNode(NodeRef archivedNodeRef, NodeRef destinationParentNodeRef, QName assocTypeQName, QName assocQName)
{
boolean wasDisabled = policyBehaviourFilter.disableBehaviour(ContentModel.ASPECT_AUDITABLE);
try
{
return restoreNodeImpl(archivedNodeRef, destinationParentNodeRef, assocTypeQName, assocQName);
}
finally
{
if (!wasDisabled)
{
policyBehaviourFilter.enableBehaviour(ContentModel.ASPECT_AUDITABLE);
}
}
}
private NodeRef restoreNodeImpl(NodeRef archivedNodeRef, NodeRef destinationParentNodeRef, QName assocTypeQName, QName assocQName)
{
Pair<Long, NodeRef> archivedNodePair = getNodePairNotNull(archivedNodeRef);
Long archivedNodeId = archivedNodePair.getFirst();
Set<QName> existingAspects = nodeDAO.getNodeAspects(archivedNodeId);
Set<QName> newAspects = new HashSet<QName>(5);
Map<QName, Serializable> existingProperties = nodeDAO.getNodeProperties(archivedNodeId);
Map<QName, Serializable> newProperties = new HashMap<QName, Serializable>(11);
// the node must be a top-level archive node
if (!existingAspects.contains(ContentModel.ASPECT_ARCHIVED))
{
throw new AlfrescoRuntimeException("The node to restore is not an archive node");
}
ChildAssociationRef originalPrimaryParentAssocRef = (ChildAssociationRef) existingProperties.get(
ContentModel.PROP_ARCHIVED_ORIGINAL_PARENT_ASSOC);
Serializable originalOwner = existingProperties.get(ContentModel.PROP_ARCHIVED_ORIGINAL_OWNER);
// remove the archived aspect
Set<QName> removePropertyQNames = new HashSet<QName>(11);
removePropertyQNames.add(ContentModel.PROP_ARCHIVED_ORIGINAL_PARENT_ASSOC);
removePropertyQNames.add(ContentModel.PROP_ARCHIVED_BY);
removePropertyQNames.add(ContentModel.PROP_ARCHIVED_DATE);
removePropertyQNames.add(ContentModel.PROP_ARCHIVED_ORIGINAL_OWNER);
nodeDAO.removeNodeProperties(archivedNodeId, removePropertyQNames);
nodeDAO.removeNodeAspects(archivedNodeId, Collections.singleton(ContentModel.ASPECT_ARCHIVED));
// restore the original ownership
if (originalOwner != null)
{
newAspects.add(ContentModel.ASPECT_OWNABLE);
newProperties.put(ContentModel.PROP_OWNER, originalOwner);
}
if (destinationParentNodeRef == null)
{
// we must restore to the original location
destinationParentNodeRef = originalPrimaryParentAssocRef.getParentRef();
}
// check the associations
if (assocTypeQName == null)
{
assocTypeQName = originalPrimaryParentAssocRef.getTypeQName();
}
if (assocQName == null)
{
assocQName = originalPrimaryParentAssocRef.getQName();
}
// move the node to the target parent, which may or may not be the original parent
ChildAssociationRef newChildAssocRef = moveNode(
archivedNodeRef,
destinationParentNodeRef,
assocTypeQName,
assocQName);
// the node reference has changed due to the store move
NodeRef restoredNodeRef = newChildAssocRef.getChildRef();
invokeOnRestoreNode(newChildAssocRef);
// done
if (logger.isDebugEnabled())
{
logger.debug("Restored node: \n" +
" original noderef: " + archivedNodeRef + "\n" +
" restored noderef: " + restoredNodeRef + "\n" +
" new parent: " + destinationParentNodeRef);
}
return restoredNodeRef;
}
/**
* Move Node
*
* Drops the old primary association and creates a new one
*/
public ChildAssociationRef moveNode(
NodeRef nodeToMoveRef,
NodeRef newParentRef,
QName assocTypeQName,
QName assocQName)
{
if (isDeletedNodeRef(newParentRef))
{
throw new InvalidNodeRefException("The parent node has been deleted", newParentRef);
}
Pair<Long, NodeRef> nodeToMovePair = getNodePairNotNull(nodeToMoveRef);
Pair<Long, NodeRef> parentNodePair = getNodePairNotNull(newParentRef);
Long nodeToMoveId = nodeToMovePair.getFirst();
QName nodeToMoveTypeQName = nodeDAO.getNodeType(nodeToMoveId);
NodeRef oldNodeToMoveRef = nodeToMovePair.getSecond();
Long parentNodeId = parentNodePair.getFirst();
NodeRef parentNodeRef = parentNodePair.getSecond();
StoreRef oldStoreRef = oldNodeToMoveRef.getStoreRef();
StoreRef newStoreRef = parentNodeRef.getStoreRef();
NodeRef newNodeToMoveRef = new NodeRef(newStoreRef, oldNodeToMoveRef.getId());
Pair<Long, NodeRef> newNodeToMovePair = new Pair<Long, NodeRef>(nodeToMoveId, newNodeToMoveRef);
// Get the primary parent association
Pair<Long, ChildAssociationRef> oldParentAssocPair = nodeDAO.getPrimaryParentAssoc(nodeToMoveId);
if (oldParentAssocPair == null)
{
// The node doesn't have parent. Moving it is not possible.
throw new IllegalArgumentException("Node " + nodeToMoveId + " doesn't have a parent. Use 'addChild' instead of move.");
}
ChildAssociationRef oldParentAssocRef = oldParentAssocPair.getSecond();
// Shortcut this whole process if nothing has changed
if (EqualsHelper.nullSafeEquals(oldParentAssocRef.getParentRef(), newParentRef) &&
EqualsHelper.nullSafeEquals(oldParentAssocRef.getTypeQName(), assocTypeQName) &&
EqualsHelper.nullSafeEquals(oldParentAssocRef.getQName(), assocQName))
{
// It's all just the same
return oldParentAssocRef;
}
boolean movingStore = !oldStoreRef.equals(newStoreRef);
// Invoke "Before"policy behaviour
if (movingStore)
{
// remove the deleted node from the list of new nodes
untrackNewNodeRef(nodeToMoveRef);
// track the deletion of this node - so we can prevent new associations to it.
trackDeletedNodeRef(nodeToMoveRef);
invokeBeforeDeleteNode(nodeToMoveRef);
invokeBeforeCreateNode(newParentRef, assocTypeQName, assocQName, nodeToMoveTypeQName);
}
else
{
invokeBeforeDeleteChildAssociation(oldParentAssocRef);
}
// Move node under the new parent
Pair<Long, ChildAssociationRef> newParentAssocPair = nodeDAO.moveNode(
nodeToMoveId,
parentNodeId,
assocTypeQName,
assocQName);
ChildAssociationRef newParentAssocRef = newParentAssocPair.getSecond();
// Handle indexing differently if it is a store move
if (movingStore)
{
// The association existed before and the node is moving to a new store
nodeIndexer.indexDeleteNode(oldParentAssocRef);
nodeIndexer.indexCreateNode(newParentAssocRef);
}
else
{
// The node is in the same store and is just having it's child association modified
nodeIndexer.indexUpdateChildAssociation(oldParentAssocRef, newParentAssocRef);
}
// Call behaviours
if (movingStore)
{
Set<QName> nodeToMoveAspectQNames = nodeDAO.getNodeAspects(nodeToMoveId);
// The Node changes NodeRefs, so this is really the deletion of the old node and creation
// of a node in a new store as far as the clients are concerned.
invokeOnDeleteNode(oldParentAssocRef, nodeToMoveTypeQName, nodeToMoveAspectQNames, true);
invokeOnCreateNode(newParentAssocRef);
// Pull children to the new store
pullNodeChildrenToSameStore(newNodeToMovePair);
}
else
{
invokeOnCreateChildAssociation(newParentAssocRef, false);
invokeOnDeleteChildAssociation(oldParentAssocRef);
invokeOnMoveNode(oldParentAssocRef, newParentAssocRef);
}
// Done
return newParentAssocRef;
}
/**
* This process is less invasive than the <b>move</b> method as the child associations
* do not need to be remade.
*/
private void pullNodeChildrenToSameStore(Pair<Long, NodeRef> nodePair)
{
Long nodeId = nodePair.getFirst();
// Get the node's children, but only one's that aren't in the same store
final List<Pair<Long, NodeRef>> childNodePairs = new ArrayList<Pair<Long, NodeRef>>(5);
NodeDAO.ChildAssocRefQueryCallback callback = new NodeDAO.ChildAssocRefQueryCallback()
{
public boolean handle(
Pair<Long, ChildAssociationRef> childAssocPair,
Pair<Long, NodeRef> parentNodePair,
Pair<Long, NodeRef> childNodePair
)
{
// Add it
childNodePairs.add(childNodePair);
// More results
return true;
}
public boolean preLoadNodes()
{
return true;
}
public void done()
{
}
};
// We only need to move child nodes that are not already in the same store
nodeDAO.getChildAssocs(nodeId, null, null, null, Boolean.TRUE, Boolean.FALSE, callback);
// Each child must be moved to the same store as the parent
for (Pair<Long, NodeRef> oldChildNodePair : childNodePairs)
{
Long childNodeId = oldChildNodePair.getFirst();
NodeRef childNodeRef = oldChildNodePair.getSecond();
NodeRef.Status childNodeStatus = nodeDAO.getNodeRefStatus(childNodeRef);
if (childNodeStatus == null || childNodeStatus.isDeleted())
{
// Node has already been deleted.
continue;
}
QName childNodeTypeQName = nodeDAO.getNodeType(childNodeId);
Set<QName> childNodeAspectQNames = nodeDAO.getNodeAspects(childNodeId);
Pair<Long, ChildAssociationRef> oldParentAssocPair = nodeDAO.getPrimaryParentAssoc(childNodeId);
Pair<Long, NodeRef> newChildNodePair = oldChildNodePair;
Pair<Long, ChildAssociationRef> newParentAssocPair = oldParentAssocPair;
ChildAssociationRef newParentAssocRef = newParentAssocPair.getSecond();
// remove the deleted node from the list of new nodes
untrackNewNodeRef(childNodeRef);
// track the deletion of this node - so we can prevent new associations to it.
trackDeletedNodeRef(childNodeRef);
// Fire node policies. This ensures that each node in the hierarchy gets a notification fired.
invokeBeforeDeleteNode(childNodeRef);
invokeBeforeCreateNode(
newParentAssocRef.getParentRef(),
newParentAssocRef.getTypeQName(),
newParentAssocRef.getQName(),
childNodeTypeQName);
// Move the node as this gives back the primary parent association
newParentAssocPair = nodeDAO.moveNode(childNodeId, nodeId, null,null);
// Index
nodeIndexer.indexCreateNode(newParentAssocPair.getSecond());
// Fire node policies. This ensures that each node in the hierarchy gets a notification fired.
invokeOnDeleteNode(oldParentAssocPair.getSecond(), childNodeTypeQName, childNodeAspectQNames, true);
invokeOnCreateNode(newParentAssocPair.getSecond());
// Cascade
pullNodeChildrenToSameStore(newChildNodePair);
}
}
public NodeRef getStoreArchiveNode(StoreRef storeRef)
{
StoreRef archiveStoreRef = storeArchiveMap.get(storeRef);
if (archiveStoreRef == null)
{
// no mapping for the given store
return null;
}
else
{
return getRootNode(archiveStoreRef);
}
}
private String extractNameProperty(Map<QName, Serializable> properties)
{
Serializable nameValue = properties.get(ContentModel.PROP_NAME);
String name = (String) DefaultTypeConverter.INSTANCE.convert(String.class, nameValue);
return name;
}
/**
* Ensures name uniqueness for the child and the child association. Note that nothing is done if the
* association type doesn't enforce name uniqueness.
*
* @return Returns <tt>true</tt> if the child association <b>cm:name</b> was written
*/
private boolean setChildNameUnique(Pair<Long, NodeRef> childNodePair, String newName, String oldName)
{
if (newName == null)
{
newName = childNodePair.getSecond().getId(); // Use the node's GUID
}
Long childNodeId = childNodePair.getFirst();
if (EqualsHelper.nullSafeEquals(newName, oldName))
{
// The name has not changed
return false;
}
else
{
nodeDAO.setChildAssocsUniqueName(childNodeId, newName);
return true;
}
}
}