alfresco-community-repo/source/java/org/alfresco/repo/node/MLPropertyInterceptor.java
Dave Ward e18ab791d7 Merged V3.4-BUG-FIX to HEAD
31072: Incremented version.revision for 3.4.7
   31082: Merged DEV to V3.4-BUG-FIX
      31077: ALF-9661: Adding or removing associations does not trigger 'update' rule.
             1. Unit test for replicating.
             2. SingleAssocRefPolicyRuleTrigger now handles trigger of the rules on the list of parents.
   31115: Merged DEV/TEMPORARY to V3.4-BUG-FIX
      30992: ALF-10029 : Webdav error when document type is missing
         Correcting directory listing. Display reader's mimetype if display label for mimetype couldn't be found.
   31116: Merged DEV/TEMPORARY to V3.4-BUG-FIX
      31114: ALF-10309 : CLONE -WebDAV - Canceling "save as" upload will create 0 byte content
         Logic was added to PutMethod that removes empty files if a save operation is cancelled or fails.
   31157: ALF-10757: Merged HEAD to V3.4-BUG-FIX
      31154: Synchronize file writes from CIFS. ALF-10721.
   31188: Merged DEV/TEMPORARY to V3.4-BUG-FIX
      31176: ALF-9979: Error thrown when adding user(s) to group in explorer if user already exists in group
         Implemented checking of the user presence in the particular group using getAuthService().getContainedAuthorities()
   31189: Merged DEV/TEMPORARY to V3.4-BUG-FIX
      31174: ALF-9684: CMIS AtomPub: The combination of includeRelationships=both and returnVersion=latestmajor returns an internal server error
         Try-catch block was added for nodeService.getSourceAssocs(node, RegexQNamePattern.MATCH_ALL) operation. This operation is not supported for a version store.
   31190: Merged DEV/TEMPORARY to V3.4-BUG-FIX
      20694: ALF-925: "title" property always gets populated with the name of a file when content without a file extension is added via Webdav.
         When user creates file through webdav, "title" property was populated with "name" property value.
         The code that was doing it has been removed. Now the title will be empty in such a case.
         This makes things consistent with CIFS and FTP, where you have to create a rule with action "Extract common metadata fields from content". 
   31217: ALF-10807: Share document download with SSL
   - Fix from Bitrock
   31226: ALF-10632: Added a sample configuration fragment for war-deployers-jboss-beans.xml because it's rather tricky to publish the correct configuration in the docs!
   31265: ALF-9999 Cannot search pdf files, which are written vertically.
      Sample configures PdfMiner as the pdf -> text and ??? -> pdf -> text transformer rather than PDFBox.
      PdfMiner is slower but does handle vertical text.
   31268: ALF-9093 Alfresco incapable of previewing text files including non Western European characters
      Sample file that configures OpenOffice as the default handler for text to PDF conversions
   31304: Merged BRANCHES/DEV/BELARUS/HEAD-2011_10_05 to BRANCHES/DEV/V3.4-BUG-FIX:
      31291: ALF-9460 : Archived discussion posts break display of the discussed node when users do not have access to the trash can
   31313: Fix for JBPM security issues with timers and async tasks.
   ALF-10776: Workflow timer fires a policy that causes a AuthenticationCredentialsNotFoundException
   ALF-6405: SecureContext issue if task node async property is set to "true"
   31314: Fixed ALF-10373 "There is no path to the folder for "Move" action inside the rule's description."
   31361: Fixed ALF-10930. Incorrect description of 'xam.archive.forceBackgroundStoreMove'
   31366: ALF-3756 - original fix didn't cope with existing MLText having one or more language variants. 
   ...upgrading to the fix would therefore not solve the problem properly. For example, if a property has en_GB text in it, then 'updating' that property with a locale of en_US will result in the addition of the en_US text rather than a true update (they're both English, and using two slightly differently configured browsers in this way leads to confusion).
   31387: ALF-10740: Flash upload - Working Copy label not removed on check in if non english locale is used in Share client   
   Two separate problems were fixed:   
   * Locale string as supplied by the flash uploader was being placed into the language portion of the Locale object in java, therefore no proper match was made when looking up the working copy label (e.g. "(Working Copy)") - fixed by using a proper locale string parser as supplied by Surf.   
   * Working copy label could still fail to be removed if document was checked out under one locale and checked in using another. Fix provided by recording the *original* working copy label against the cm:workingcopy aspect.   
   31395: ALF-3756: fixes broken FullNodeServiceTest
   31399: ALF-3756: fixing build failures from -c31366 (VersionServiceImplText.testRevert()) 
   A ConcurrentModificationException was being thrown, have changed the way that the hashmap is processed to avoid this.
   31401: Fix for ALF-2980
   31410: Fix for ALF-10961 - Share - Sites not displayed on dashboard
   31418: ALF-10768 Environment variables are being used to replace property placeholders in xml configuration files
      Modified ALL spring beans that are a PropertyPlaceholderConfigurer (including sub classes) and the 
      PropertyPlaceholderConfigurer created ChildApplicationContextFactory so that OS environment variables
      are not used in property place holder substitutions. Spring 3 started allowing OS environment variables
      to be used by default. This may explain why we have so many install problems.
   31420: ALF-3756 another compile error: This time StoreSelectorAspectContentStoreTest
   31425: ALF-10740: Fix from -c 31387 (compilation error)   
   This fix is in addition to -c31420. The compilation error was due to me not having the bug fix branch configured as an enterprise project.
   31458: Fix for ALF-10916
   31459: Fix for ALF-10915
   31482: ALF-10915
     - Fix build
   31491: Various oplock, access mode and CIFS protocol fixes ported from v4/HEAD. ALF-10331.
   31492: File open access mode checks ported from v4/HEAD. ALF-10331.
   31529: ALF-11144: NPE during incremental LDAP sync
   31530: Fixed ALF-11139: Audit concurrency exceptions do not trigger transaction retries
    - AuditMethodInterceptor allows audit exceptions to propagate out
   31606: ALF-10309 CLONE -WebDAV - Cancelling "save as" upload will create 0 byte content
       Changed name of aspect to be WebDAV specific (rather than using a CIFS value), so that it might be possible to tidy these up in future.
   31638: Fix for ALF-10597 - Share - Upload new version issue - OK button displayed during refresh
   31639: Fix for ALF-10297 JSF - Sort by First/Last Name in Groups Management not working
   31641: ALF-9776 - Fix for WCM - it allows users to submit contents to Staging with past Launch and Expiration Date
   31653: ALF-8906: Ensure entire IMAP service startup transaction runs as system, to allow for any auto-aspect adding / versioning during cache warming
   31654: Merged V3.4 to V3.4-BUG-FIX
      31327: ALF-10878 Merged HEAD to V3.4
           30225: ALF-10001 Update SiteService.listMembers to check group display names as well as group names, plus test
      31329: Merged V3.4-BUG-FIX (3.4.7) to V3.4 (3.4.6)
         30992: ALF-10029 : Webdav error when document type is missing
            Correcting directory listing. Display reader's mimetype if display label for mimetype couldn't be found.
      31462: ALF-10010 Document can not be found even after a full reindex.
         Sample configures xpdf as the pdf -> text and ??? -> pdf -> text transformer rather than PDFBox.
      31478: Merged BELARUS/V3.4-BUG-FIX-2011_10_13 to V3.4 (3.4.6)
         31460: ALF-10952: User is unable to edit own profile using Alfresco Share
            To compare two objects it needs to use equals() method instead of ==.
            Such a check was changed in UsageQuotaProtector.onUpdateProperties() method.
      31502: ALF-10324 Cannot disable Home Folder Creation
         2nd part to the problem. Folders were being created when "Show all" was pressed in the UI
      31504: Fix for ALF-9589 - Share - Advanced Search is not IE7 compatible for other themes
      31531: ALF-10324 Cannot disable Home Folder Creation
         There is a knock on effect to ContentUsageService when the user does not exist and we are not allowed to create missing users.
         Resulted in 2 DMDeploymentTargetTest failures
      31532: ALF-10955 No pooled task created for moderated site managers if any user requested to join
         Going with David Wards suggestion of still using getContainingAuthoritiesInZone with a null zone and a cut off at 100.
         The 100 might be too small, but probably is okay.
   31655: ALF-10187: Merged V3.3 to V3.4-BUG-FIX
      31180: ALF-9898: CIFS packet pool leaks
      - File state manager op lock break expiry thread was never getting started so some deferred packets were never getting released!
      - Synchronize around m_borrowed to prevent ConcurrentModificationExceptions in diagnostics
      - Synchronize around m_selector.keys() to prevent ConcurrentModificationExceptions during session reaping
      31244: Merged DEV/BELARUS/V3.4-BUG-FIX-2011_09_29_CIFS to V3.3
         ALF-10831: CIFS concurrency issues under load
            - Atomic synchronized write AND read operations in FileStateCache, TreeConnection, SrvSessionList, VirtualCircuit, VirtualCircuitList, ContentQuotaManager
      31245: Merged DEV/BELARUS/V3.4-BUG-FIX-2011_09_29_CIFS to V3.3
         ALF-9540: copy from drive to CIFS is slower than direct drive to drive copy by a factor of ~ 15
         - batchRemoveRequest added to ThreadRequestQueue, meaning that not all incoming packets are scatter-gunned across different worker threads and reducing context switching
         - Arseny's tests show that combined with 3.4.6 changes, the factor is now under 2!
      31246: ALF-9898: Merged HEAD to V3.3
         31154: Synchronize file writes from CIFS. ALF-10721.
         31233: Fixed a possible memory leak in the CIFS oplock timeout handler.
      31273: ALF-9540: Reversed batchRemoveRequest changes
      - Review by Gary. Thread pool may not be utilized properly when multiple virtual connections are being handled at once.
      31576: Changes to the CIFS idle session reaper so that it runs in the main socket event thread. ALF-9898.


git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@31657 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
2011-11-02 23:22:24 +00:00

674 lines
27 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;
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.Locale;
import java.util.Map;
import org.alfresco.model.ContentModel;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
import org.alfresco.service.cmr.dictionary.DictionaryService;
import org.alfresco.service.cmr.dictionary.PropertyDefinition;
import org.alfresco.service.cmr.ml.MultilingualContentService;
import org.alfresco.service.cmr.repository.ContentData;
import org.alfresco.service.cmr.repository.MLText;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.EqualsHelper;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.extensions.surf.util.I18NUtil;
/**
* Interceptor to filter out multilingual text properties from getter methods and
* transform to multilingual text for setter methods.
* <p>
* This interceptor ensures that all multilingual (ML) text is transformed to the
* locale chosen {@link org.alfresco.service.cmr.repository.MLText#getContextLocale() for the request}
* for getters and transformed to the default locale type for setters.
* <p>
* Where {@link org.alfresco.service.cmr.repository.MLText ML text} has been passed in, this
* will be allowed to pass.
*
* @see org.alfresco.service.cmr.repository.MLText#getContextLocale()
* @see org.alfresco.service.cmr.repository.NodeService#getProperty(NodeRef, QName)
* @see org.alfresco.service.cmr.repository.NodeService#getProperties(NodeRef)
* @see org.alfresco.service.cmr.repository.NodeService#setProperty(NodeRef, QName, Serializable)
* @see org.alfresco.service.cmr.repository.NodeService#setProperties(NodeRef, Map)
*
* @author Derek Hulley
* @author Philippe Dubois
*/
public class MLPropertyInterceptor implements MethodInterceptor
{
private static Log logger = LogFactory.getLog(MLPropertyInterceptor.class);
private static ThreadLocal<Boolean> mlAware = new ThreadLocal<Boolean>();
/** Direct access to the NodeService */
private NodeService nodeService;
/** Direct access to the MultilingualContentService */
private MultilingualContentService multilingualContentService;
/** Used to access property definitions */
private DictionaryService dictionaryService;
/**
* Change the filtering behaviour of this interceptor on the curren thread.
* Use this to switch off the filtering and just pass out properties as
* handed out of the node service.
*
* @param mlAwareVal <tt>true</tt> if the current thread is able to handle
* {@link MLText d:mltext} property types, otherwise <tt>false</tt>.
* @return
* <tt>true</tt> if the current transaction is ML aware
*/
static public boolean setMLAware(boolean mlAwareVal)
{
boolean wasMLAware = isMLAware();
mlAware.set(Boolean.valueOf(mlAwareVal));
return wasMLAware;
}
/**
* @return Returns <tt>true</tt> if the current thread has marked itself
* as being able to handle {@link MLText d:mltext} types properly.
*/
static public boolean isMLAware()
{
if (mlAware.get() == null)
{
return false;
}
else
{
return mlAware.get();
}
}
public void setNodeService(NodeService bean)
{
this.nodeService = bean;
}
public void setMultilingualContentService(MultilingualContentService multilingualContentService)
{
this.multilingualContentService = multilingualContentService;
}
public void setDictionaryService(DictionaryService dictionaryService)
{
this.dictionaryService = dictionaryService;
}
@SuppressWarnings("unchecked")
public Object invoke(final MethodInvocation invocation) throws Throwable
{
if (logger.isDebugEnabled())
{
logger.debug("Intercepting method " + invocation.getMethod().getName() + " using content filter " + I18NUtil.getContentLocale());
}
// If isMLAware then no treatment is done, just return
if (isMLAware())
{
// Don't interfere
return invocation.proceed();
}
Locale contentLangLocale = I18NUtil.getContentLocaleLang();
Object ret = null;
final String methodName = invocation.getMethod().getName();
final Object[] args = invocation.getArguments();
if (methodName.equals("getProperty"))
{
NodeRef nodeRef = (NodeRef) args[0];
QName propertyQName = (QName) args[1];
// Get the pivot translation, if appropriate
NodeRef pivotNodeRef = getPivotNodeRef(nodeRef);
// What locale must be used for filtering - ALF-3756 fix, ignore the country and variant
Serializable value = (Serializable) invocation.proceed();
ret = convertOutboundProperty(contentLangLocale, nodeRef, pivotNodeRef, propertyQName, value);
}
else if (methodName.equals("getProperties"))
{
NodeRef nodeRef = (NodeRef) args[0];
// Get the pivot translation, if appropriate
NodeRef pivotNodeRef = getPivotNodeRef(nodeRef);
Map<QName, Serializable> properties = (Map<QName, Serializable>) invocation.proceed();
Map<QName, Serializable> convertedProperties = new HashMap<QName, Serializable>(properties.size() * 2);
// Check each return value type
for (Map.Entry<QName, Serializable> entry : properties.entrySet())
{
QName propertyQName = entry.getKey();
Serializable value = entry.getValue();
Serializable convertedValue = convertOutboundProperty(contentLangLocale, nodeRef, pivotNodeRef, propertyQName, value);
// Add it to the return map
convertedProperties.put(propertyQName, convertedValue);
}
ret = convertedProperties;
// Done
if (logger.isDebugEnabled())
{
logger.debug(
"Converted getProperties return value: \n" +
" initial: " + properties + "\n" +
" converted: " + convertedProperties);
}
}
else if (methodName.equals("setProperties"))
{
NodeRef nodeRef = (NodeRef) args[0];
Map<QName, Serializable> newProperties =(Map<QName, Serializable>) args[1];
// Get the pivot translation, if appropriate
NodeRef pivotNodeRef = getPivotNodeRef(nodeRef);
// Get the current properties for the node
Map<QName, Serializable> currentProperties = nodeService.getProperties(nodeRef);
// Convert all properties
Map<QName, Serializable> convertedProperties = convertInboundProperties(
currentProperties,
newProperties,
contentLangLocale,
nodeRef,
pivotNodeRef);
// Now complete the call by passing the converted properties
nodeService.setProperties(nodeRef, convertedProperties);
// Done
}
else if (methodName.equals("addProperties"))
{
NodeRef nodeRef = (NodeRef) args[0];
Map<QName, Serializable> newProperties =(Map<QName, Serializable>) args[1];
// Get the pivot translation, if appropriate
NodeRef pivotNodeRef = getPivotNodeRef(nodeRef);
// Get the current properties for the node
Map<QName, Serializable> currentProperties = nodeService.getProperties(nodeRef);
// Convert all properties
Map<QName, Serializable> convertedProperties = convertInboundProperties(
currentProperties,
newProperties,
contentLangLocale,
nodeRef,
pivotNodeRef);
// Now complete the call by passing the converted properties
nodeService.addProperties(nodeRef, convertedProperties);
// Done
}
else if (methodName.equals("setProperty"))
{
NodeRef nodeRef = (NodeRef) args[0];
QName propertyQName = (QName) args[1];
Serializable inboundValue = (Serializable) args[2];
// Get the pivot translation, if appropriate
NodeRef pivotNodeRef = getPivotNodeRef(nodeRef);
// Convert the property
inboundValue = convertInboundProperty(contentLangLocale, nodeRef, pivotNodeRef, propertyQName, inboundValue, null);
// Pass this through to the node service
nodeService.setProperty(nodeRef, propertyQName, inboundValue);
// Done
}
else if (methodName.equals("createNode") && args.length > 4)
{
NodeRef parentNodeRef = (NodeRef) args[0];
QName assocTypeQName = (QName) args[1];
QName assocQName = (QName) args[2];
QName nodeTypeQName = (QName) args[3];
Map<QName, Serializable> newProperties =(Map<QName, Serializable>) args[4];
if (newProperties == null)
{
newProperties = Collections.emptyMap();
}
NodeRef nodeRef = null; // Not created yet
// No pivot
NodeRef pivotNodeRef = null;
// Convert all properties
Map<QName, Serializable> convertedProperties = convertInboundProperties(
null,
newProperties,
contentLangLocale,
nodeRef,
pivotNodeRef);
// Now complete the call by passing the converted properties
ret = nodeService.createNode(parentNodeRef, assocTypeQName, assocQName, nodeTypeQName, convertedProperties);
// Done
}
else if (methodName.equals("addAspect") && args[2] != null)
{
NodeRef nodeRef = (NodeRef) args[0];
QName aspectTypeQName = (QName) args[1];
// Get the pivot translation, if appropriate
NodeRef pivotNodeRef = getPivotNodeRef(nodeRef);
Map<QName, Serializable> newProperties =(Map<QName, Serializable>) args[2];
// Get the current properties for the node
Map<QName, Serializable> currentProperties = nodeService.getProperties(nodeRef);
// Convert all properties
Map<QName, Serializable> convertedProperties = convertInboundProperties(
currentProperties,
newProperties,
contentLangLocale,
nodeRef,
pivotNodeRef);
// Now complete the call by passing the converted properties
nodeService.addAspect(nodeRef, aspectTypeQName, convertedProperties);
// Done
}
else
{
ret = invocation.proceed();
}
// done
return ret;
}
/**
* @param nodeRef
* a potential empty translation
* @return
* the pivot translation node or <tt>null</tt>
*/
private NodeRef getPivotNodeRef(NodeRef nodeRef)
{
if (nodeRef == null)
{
throw new IllegalArgumentException("NodeRef may not be null for calls to NodeService. Check client code.");
}
if (!nodeRef.getStoreRef().getProtocol().equals(StoreRef.PROTOCOL_AVM) && nodeService.hasAspect(nodeRef, ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION))
{
return multilingualContentService.getPivotTranslation(nodeRef);
}
else
{
return null;
}
}
/**
* Ensure that content is spoofed for empty translations.
*/
private Serializable convertOutboundProperty(
Locale contentLocale,
NodeRef nodeRef,
NodeRef pivotNodeRef,
QName propertyQName,
Serializable outboundValue)
{
Serializable ret = null;
if (outboundValue == null)
{
ret = null;
}
if (outboundValue instanceof MLText)
{
// It is MLText
MLText mlText = (MLText) outboundValue;
ret = mlText.getClosestValue(contentLocale);
}
else if(isCollectionOfMLText(outboundValue))
{
Collection<?> col = (Collection<?>)outboundValue;
ArrayList<String> answer = new ArrayList<String>(col.size());
Locale closestLocale = getClosestLocale(col, contentLocale);
for(Object o : col)
{
MLText mlText = (MLText) o;
String value = mlText.get(closestLocale);
if(value != null)
{
answer.add(value);
}
}
ret = answer;
}
else if (pivotNodeRef != null) // It is an empty translation
{
if (propertyQName.equals(ContentModel.PROP_MODIFIED))
{
// An empty translation's modified date must be the later of its own
// modified date and the pivot translation's modified date
Date emptyLastModified = (Date) outboundValue;
Date pivotLastModified = (Date) nodeService.getProperty(pivotNodeRef, ContentModel.PROP_MODIFIED);
if (emptyLastModified.compareTo(pivotLastModified) < 0)
{
ret = pivotLastModified;
}
else
{
ret = emptyLastModified;
}
}
else if (propertyQName.equals(ContentModel.PROP_CONTENT))
{
// An empty translation's cm:content must track the cm:content of the
// pivot translation.
ret = nodeService.getProperty(pivotNodeRef, ContentModel.PROP_CONTENT);
}
else
{
ret = outboundValue;
}
}
else
{
ret = outboundValue;
}
// Done
if (logger.isDebugEnabled())
{
logger.debug(
"Converted outbound property: \n" +
" NodeRef: " + nodeRef + "\n" +
" Property: " + propertyQName + "\n" +
" Before: " + outboundValue + "\n" +
" After: " + ret);
}
return ret;
}
public Locale getClosestLocale(Collection<?> collection, Locale locale)
{
if (collection.size() == 0)
{
return null;
}
// Use the available keys as options
HashSet<Locale> locales = new HashSet<Locale>();
for(Object o : collection)
{
MLText mlText = (MLText)o;
locales.addAll(mlText.keySet());
}
// Get a match
Locale match = I18NUtil.getNearestLocale(locale, locales);
if (match == null)
{
// No close matches for the locale - go for the default locale
locale = I18NUtil.getLocale();
match = I18NUtil.getNearestLocale(locale, locales);
if (match == null)
{
// just get any locale
match = I18NUtil.getNearestLocale(null, locales);
}
}
return match;
}
/**
* @param outboundValue
* @return
*/
private boolean isCollectionOfMLText(Serializable outboundValue)
{
if(outboundValue instanceof Collection<?>)
{
for(Object o : (Collection<?>)outboundValue)
{
if(!(o instanceof MLText))
{
return false;
}
}
return true;
}
else
{
return false;
}
}
private Map<QName, Serializable> convertInboundProperties(
Map<QName, Serializable> currentProperties,
Map<QName, Serializable> newProperties,
Locale contentLocale,
NodeRef nodeRef,
NodeRef pivotNodeRef)
{
Map<QName, Serializable> convertedProperties = new HashMap<QName, Serializable>(newProperties.size() * 2);
for (Map.Entry<QName, Serializable> entry : newProperties.entrySet())
{
QName propertyQName = entry.getKey();
Serializable inboundValue = entry.getValue();
// Get the current property value
Serializable currentValue = currentProperties == null ? null : currentProperties.get(propertyQName);
// Convert the inbound property value
inboundValue = convertInboundProperty(contentLocale, nodeRef, pivotNodeRef, propertyQName, inboundValue, currentValue);
// Put the value into the map
convertedProperties.put(propertyQName, inboundValue);
}
return convertedProperties;
}
/**
*
* @param inboundValue The value that must be set
* @param currentValue The current value of the property or <tt>null</tt> if not known
* @return Returns a potentially converted property that conforms to the model
*/
private Serializable convertInboundProperty(
Locale contentLocale,
NodeRef nodeRef,
NodeRef pivotNodeRef,
QName propertyQName,
Serializable inboundValue,
Serializable currentValue)
{
Serializable ret = null;
PropertyDefinition propertyDef = this.dictionaryService.getProperty(propertyQName);
//if no type definition associated to the name then just proceed
if (propertyDef == null)
{
ret = inboundValue;
}
else if (propertyDef.getDataType().getName().equals(DataTypeDefinition.MLTEXT))
{
// Don't mess with multivalued properties or instances already of type MLText
if (inboundValue instanceof MLText)
{
ret = inboundValue;
}
else if(propertyDef.isMultiValued())
{
// leave collectios of ML text alone
if(isCollectionOfMLText(inboundValue))
{
ret = inboundValue;
}
else
{
// Anything else we assume is localised
if (currentValue == null && nodeRef != null)
{
currentValue = nodeService.getProperty(nodeRef, propertyQName);
}
ArrayList<MLText> returnMLList = new ArrayList<MLText>();
if (currentValue != null)
{
Collection<MLText> currentCollection = DefaultTypeConverter.INSTANCE.getCollection(MLText.class, currentValue);
returnMLList.addAll(currentCollection);
}
Collection<String> inboundCollection = DefaultTypeConverter.INSTANCE.getCollection(String.class, inboundValue);
int count = 0;
for(String current : inboundCollection)
{
MLText newMLValue;
if(count < returnMLList.size())
{
MLText currentMLValue = returnMLList.get(count);
newMLValue = new MLText();
if (currentMLValue != null)
{
newMLValue.putAll(currentMLValue);
}
}
else
{
newMLValue = new MLText();
}
replaceTextForLanguage(contentLocale, current, newMLValue);
if(count < returnMLList.size())
{
returnMLList.set(count, newMLValue);
}
else
{
returnMLList.add(newMLValue);
}
count++;
}
// remove locale settings for anything after
for(int i = count; i < returnMLList.size(); i++)
{
MLText currentMLValue = returnMLList.get(i);
MLText newMLValue = new MLText();
if (currentMLValue != null)
{
newMLValue.putAll(currentMLValue);
}
newMLValue.remove(contentLocale);
returnMLList.set(i, newMLValue);
}
// tidy up empty locales
ArrayList<MLText> tidy = new ArrayList<MLText>();
for(MLText mlText : returnMLList)
{
if(mlText.keySet().size() > 0)
{
tidy.add(mlText);
}
}
ret = tidy;
}
}
else
{
// This is a multilingual single-valued property
// Get the current value from the node service, if not provided
if (currentValue == null && nodeRef != null)
{
currentValue = nodeService.getProperty(nodeRef, propertyQName);
}
MLText returnMLValue = new MLText();
if (currentValue != null)
{
MLText currentMLValue = DefaultTypeConverter.INSTANCE.convert(MLText.class, currentValue);
returnMLValue.putAll(currentMLValue);
}
// Force the inbound value to be a String (it isn't MLText)
String inboundValueStr = DefaultTypeConverter.INSTANCE.convert(String.class, inboundValue);
// Update the text for the appropriate language.
replaceTextForLanguage(contentLocale, inboundValueStr, returnMLValue);
// Done
ret = returnMLValue;
}
}
else if (pivotNodeRef != null && propertyQName.equals(ContentModel.PROP_CONTENT))
{
// It is an empty translation. The content must not change if it matches
// the content of the pivot translation
ContentData pivotContentData = (ContentData) nodeService.getProperty(pivotNodeRef, ContentModel.PROP_CONTENT);
ContentData emptyContentData = (ContentData) inboundValue;
String pivotContentUrl = pivotContentData == null ? null : pivotContentData.getContentUrl();
String emptyContentUrl = emptyContentData == null ? null : emptyContentData.getContentUrl();
if (EqualsHelper.nullSafeEquals(pivotContentUrl, emptyContentUrl))
{
// They are a match. So the empty translation must be reset to it's original value
ret = (ContentData) nodeService.getProperty(nodeRef, ContentModel.PROP_CONTENT);
}
else
{
ret = inboundValue;
}
}
else
{
ret = inboundValue;
}
// Done
if (logger.isDebugEnabled() && ret != inboundValue)
{
logger.debug("Converted inbound property: \n" +
" NodeRef: " + nodeRef + "\n" +
" Property: " + propertyQName + "\n" +
" Before: " + inboundValue + "\n" +
" After: " + ret);
}
return ret;
}
/**
* Replace any text in mlText having the same language (but any variant) as contentLocale
* with updatedText keyed by the language of contentLocale. This ensures that the mlText
* will have no more than one entry for the particular language.
*
* @param contentLocale
* @param updatedText
* @param mlText
*/
private void replaceTextForLanguage(Locale contentLocale, String updatedText, MLText mlText)
{
String language = contentLocale.getLanguage();
// Remove all text entries having the same language as the chosen contentLocale
// (e.g. if contentLocale is en_GB, then remove text for en, en_GB, en_US etc.
Iterator<Locale> locales = mlText.getLocales().iterator();
while (locales.hasNext())
{
Locale locale = locales.next();
if (locale.getLanguage().equals(language))
{
locales.remove();
}
}
// Add the new value for the specific language
mlText.addValue(new Locale(language), updatedText);
}
}