alfresco-community-repo/source/java/org/alfresco/email/server/handler/AbstractEmailMessageHandler.java
Dave Ward cb4a571fa1 Merged V3.4-BUG-FIX to HEAD
29870: ALF-9952: Compatibility fix to allow mounting of Alfresco WebDAV as a network drive on Windows XP (without WebDrive)
   29872: Fixed ALF-7698 "Defects in tags picker in SHARE."
   - now checks added items to avoid duplicates
   29873: Made sure the onActionDetails doclib action generates SimpleDialog instance ids each time, to avoid multiple js class instances with the same id getting called for every dialog created.
   29878: ALF-9378: Use caching plus a read write lock, in a similar manner to ALF-7064, to avoid contention in SubsystemProxyFactory under load
   29881: Added helper text for the translators to the property file.
   29910: ALF-7433: a file deleted using the web UI still appears in a NFS mount but with NULL stats
   - timestamp propagation now enabled by default so NFS always works
   - timestamp propagation less agressive - only has to propagate on adds / deletes and renames
   29911: Values for recurrence strings updated now that I've read RFC-2445
   29944: ALF-9988: Merged PATCHES/V3.3.4 to V3.4-BUG-FIX
      28581: ALF-8944: Corrected sort parameter handling for datetime fields, based on analyzer and tokenization mode
   29955: Fixed ALF-9965: Property names matching fails if the property contains non Alphanumeric characters
   29956: Fixed ALF-9424: Webform(XSD): xf:switch switch group does not work based on "complexContent with Base" element.
   29964: Fixed ALF-9089: TinyMCE convert_fonts_to_spans parameter is not being picked up in Web Forms
   29977: L10N Updates from Gloria (based on rev29838).
   29980: Ignore virtual tomcat directory
   29981: Merged BRANCHES/DEV/BELARUS/V3.4-BUG-FIX-2011_08_19 to BRANCHES/DEV/V3.4-BUG-FIX 
       ALF-6808 : Incorrect Search Language Conversion for wild card characters (%, _) for MS SQL 
   29984: ALF-4753: Fix search query escaping in Alfresco Explorer
   - AWC-1743 / CHK-2171 fix restored
   29993: Merged DEV/TEMPORARY to V3.4-BUG-FIX
      29989: ALF-9976: WebDAV Class 2 compliance issue with OPTIONS response.
         Class 2 incompliance connected with absence of 'PROPPATCH' method in the 'Allow' response header has been fixed
   30009: ALF-7239 : Documents from Records Manager cannot be viewed in Outlook   
   30012: Merged BRANCHES/DEV/BELARUS/V3.4-BUG-FIX-2011_08_19 to BRANCHES/DEV/V3.4-BUG-FIX:
      29986: ALF-7105: pdfbox returns errors in the logs but one cannot understand what file is affected (PDFBox)
   30014: ALF-6284: Fix for Share Kerberos SSO Websphere compatibility (by Pavel)
   30016: Merged DEV to V3.4-BUG-FIX
      29424: ALF-8715: NFS: Admin sometimes cannot edit content uploaded via JSF
             Fix for "Can't open file for writing" during saving file in VI-like editors connected with FileExpiry daemon:
             - 'getNodeOrNull()' method extracted to get and check on existence of the cached file object
                and then update cache timeout or remove it from the cache;
             - 'getNodeForPath()' was appropriately updated in accordance with logic extracted to 'getNodeOrNull()';
             - 'fileExists()' method was corrected to take into account existence of the cached file object 
   30017: Reverses an accidental check in made with the last L10N bundle update (r29977)
   30045: ALF-8664 - Custom 'mandatory' RM metadata causes editing issues   
   30053: ALF-9681: webScriptsRegistryCache size in ehcache-default.xml   
      webScriptsRegistryCache maxElementsInMemory size was incremented up to 1000
   30079: ALF-10027: Fix template alfresco-global.properties for custom tomcat ports
   - Obselete web.application.context.url removed
   - alfresco.host, alfresco.port, share.host and share.port added
   30080: Fixed parse error mentioned in ALF-9511 "RSS Feeds with HTTP Auth doesn't work with Feed dashlet"
    - In java regexps the . (dot) does NOT include the \r or \n by default, to change that a (?s) instruction was added in the beginning of the regexp
   30083: Fixed ALF-10048 "Multiple thumbnails in RSS feeds causes problem for RSS Feed dashlet"
   30088: ALF-7433: Fix unit test fallout from new timestamp propagation behaviour
   30089: ALF-7433: Further unit test fallout from new timestamp propagation behaviour
   - testPermissionsAndPolicies needs to get folder modification date in a distinct transaction after populating it
   30091: ALF-10050: CIFS: Coordinator is unable to delete content after IMAP has been enabled
   - Transactional cache null entry issue
   30096: ALF-9793: Allow auto-created NFS authenticated users to work
   - Also removed admin from default mappings to avoid security hole
   30102: ALF-8723 CIFS on Windows fails to start under certain conditions
      - Found another place >= was required rather than just >
   30104: ALF-9890 SiteService is not producing audit data.
      - Internal siteService rather than public SiteService was being used, so there was no audit advice.
   30119: ALF-9793: Fallout from previous fix. Prevent initialization error when there are no user mappings and NFS is not enabled.
   30120: ALF-9526: Work around the fact that Websphere ignores the response encoding unless you call response.setCharacterEncoding()
   - GlobalLocalizationFilter inserts a response wrapper that parses the charset parameter from the content type header, if it is present
   30121: ALF-9535: Alfresco ignores Accept-Language sent from Share
   - Ticket and webscript authentication (i.e. Share requests) will use the language set in request headers as the session language
   30130: ALF-10049: Fix by Andrey to enable Flash upload on Weblogic!
   30141: ALF-8732 Now if the adhoc workflow throws exceptions while sending a notification email then those exceptions are ignored.
   30226: ALF-9415: JSF - Copy/Paste vs Cut/Paste add aspect rule.
   30242: Added NodeService.getNodeRef(Long nodeId)
    - First step to remove Lucene search from inbound email server
    - Done while investigating ALF-9660
   30243: Fixed ALF-9660: Inbound emails are always stored with encoding=UTF-8 regardless the encoding the email client uses.
    - If the encoding is provided, then it is not guessed
    - Includes tweak to remove Lucene search and rather use direct node ID-NodeRef translation provided by NodeService
   30263: Incremented version revision
   30264: ALF-10187: Merged V3.3 to V3.4-BUG-FIX
      30003: ALF-9898: More defensive exception handling to avoid packet pool leaks and extra logging on packet pool exhaustion
   30265: Merged V3.4 to V3.4-BUG-FIX
      30259: ALF-6527 LangPack FR - [Search results' page] Incorrect label when search matches results
        - Added "(s)" to "trouvé(s) dans l'entrepôt."   (for a repository search - found in retest)
        - The original change:
          Added "(s)" to "trouvé(s) dans tous les sites."   (for an All Sites search)
          
          However this leaves the current site search. As a result I also:
          Added "(s)" to "trouvé(s) dans le site {0}."  (for a current Site search)
          and checked with a French speaker that this would sound correct.
          
          Note: all three labels are prefixed by a separate text label: "N résultat(s) "
      30261: (RECORD ONLY) Merged V3.4-BUG-FIX to V3.4 (3.4.5)
      30262: ALF-10186: Merged PATCHES/V3.4.1 to V3.4
         30126: ALF-10075: Concurrency during CMIS document update causes content stream to close prematurely.
            - Created BufferedRequest request wrapper in RepositoryContainer
            - If the content stream is accessed directly it is streamed to a temporary file so that requests can be retried
         30137: ALF-10075: Fixed NPE


git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@30271 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
2011-09-06 16:14:53 +00:00

397 lines
14 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.email.server.handler;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.encoding.ContentCharsetFinder;
import org.alfresco.service.cmr.dictionary.DictionaryService;
import org.alfresco.service.cmr.email.EmailMessage;
import org.alfresco.service.cmr.email.EmailMessagePart;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sun.star.auth.InvalidArgumentException;
/**
* Abstract class implements common logic for processing email messages.
*
* @author maxim
* @since 2.2
*/
public abstract class AbstractEmailMessageHandler implements EmailMessageHandler
{
private static final Log log = LogFactory.getLog(EmailMessageHandler.class);
private DictionaryService dictionaryService;
private NodeService nodeService;
private ContentService contentService;
private MimetypeService mimetypeService;
/**
* @return Alfresco Content Service.
*/
protected ContentService getContentService()
{
return contentService;
}
/**
* @param contentService Alfresco Content Service.
*/
public void setContentService(ContentService contentService)
{
this.contentService = contentService;
}
/**
* @return the Alfresco dictionary service
*/
protected DictionaryService getDictionaryService()
{
return dictionaryService;
}
/**
* @param dictionaryService Alfresco dictionary service
*/
public void setDictionaryService(DictionaryService dictionaryService)
{
this.dictionaryService = dictionaryService;
}
/**
* @return Alfresco Node Service.
*/
protected NodeService getNodeService()
{
return nodeService;
}
/**
* @param nodeService Alfresco Node Service.
*/
public void setNodeService(NodeService nodeService)
{
this.nodeService = nodeService;
}
/**
* @return the service used to determine mimeypte and encoding
*/
protected MimetypeService getMimetypeService()
{
return mimetypeService;
}
/**
* @param mimetypeService the the service to determine mimetype and encoding
*/
public void setMimetypeService(MimetypeService mimetypeService)
{
this.mimetypeService = mimetypeService;
}
/**
* @param to Email address which user part specifies node-dbid
* @return Referance to requested node.
* @throws InvalidArgumentException The exception is thrown if input string has incorrect format or empty.
*/
protected NodeRef getTargetNode(String to) throws InvalidArgumentException
{
if (to == null || to.length() == 0)
{
throw new InvalidArgumentException("Input string has to contain email address.");
}
String[] parts = to.split("@");
if (parts.length != 2)
{
throw new InvalidArgumentException("Incorrect email address format.");
}
try
{
Long dbId = Long.parseLong(parts[0]);
return nodeService.getNodeRef(dbId);
}
catch (NumberFormatException e)
{
return null;
}
}
/**
* Write the content to the node
*
* @param nodeRef Target node
* @param content Content
*/
protected void writeContent(NodeRef nodeRef, String content)
{
writeContent(nodeRef, content, MimetypeMap.MIMETYPE_TEXT_PLAIN);
}
/**
* Write the string as content to the node.
*
* @param nodeRef Target node.
* @param content Text for writting.
* @param mimetype MIME content type. For exaple you can set this parameter to "text/html" or "text/xml", etc.
*/
protected void writeContent(NodeRef nodeRef, String content, String mimetype)
{
try
{
InputStream inputStream = new ByteArrayInputStream(content.getBytes("UTF-8"));
writeContent(nodeRef, inputStream, mimetype, "UTF-8");
}
catch (UnsupportedEncodingException e)
{
throw new AlfrescoRuntimeException("Failed to write content", e);
}
}
/**
* Write content to the node from InputStream.
*
* @param nodeRef Target node.
* @param content Content stream.
* @param mimetype MIME content type.
* @param encoding Encoding. Can be null for non text based content.
*/
protected void writeContent(NodeRef nodeRef, InputStream content, String mimetype, String encoding)
{
InputStream bis = new BufferedInputStream(content, 4092);
// Only guess the encoding if it has not been supplied
if (encoding == null)
{
if (mimetypeService.isText(mimetype))
{
ContentCharsetFinder charsetFinder = mimetypeService.getContentCharsetFinder();
encoding = charsetFinder.getCharset(bis, mimetype).name();
}
else
{
encoding = "UTF-8";
}
}
if (log.isDebugEnabled())
{
log.debug("Write content (MimeType=\"" + mimetype + "\", Encoding=\"" + encoding + "\"");
}
ContentService contentService = getContentService();
ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
writer.setMimetype(mimetype);
writer.setEncoding(encoding);
writer.putContent(bis);
}
/**
* Add emailed aspect to the specified node.
*
* @param nodeService Alfresco Node Service.
* @param nodeRef Target node.
* @param mailParser Mail message that will be used for extracting necessary information
*/
protected void addEmailedAspect(NodeRef nodeRef, EmailMessage message)
{
/*
* TODO - get rid of this and use the RFC822 metadata extractor instead.
*/
Map<QName, Serializable> emailProps = new HashMap<QName, Serializable>();
emailProps.put(ContentModel.PROP_SENTDATE, message.getSentDate());
emailProps.put(ContentModel.PROP_ORIGINATOR, message.getFrom());
emailProps.put(ContentModel.PROP_ADDRESSEE, message.getTo());
emailProps.put(ContentModel.PROP_ADDRESSEES, (Serializable)message.getCC());
emailProps.put(ContentModel.PROP_SUBJECT, message.getSubject());
nodeService.addAspect(nodeRef, ContentModel.ASPECT_EMAILED, emailProps);
/*
* MER
* Can't add IMAP_CONTENT here since that means the body of the message is a mime message.
*/
//Map<QName, Serializable> imapProps = new HashMap<QName, Serializable>();
//emailProps.put(ImapModel.PROP_MESSAGE_FROM, message.getFrom());
//emailProps.put(ImapModel.PROP_MESSAGE_TO, message.getTo());
//emailProps.put(ImapModel.PROP_MESSAGE_CC, (Serializable)message.getCC());
//emailProps.put(ImapModel.PROP_MESSAGE_SUBJECT, message.getSubject());
//nodeService.addAspect(nodeRef, ImapModel.ASPECT_IMAP_CONTENT, imapProps);
if (log.isDebugEnabled())
{
log.debug("Emailed aspect has been added.");
}
}
/**
* Add new node into Alfresco repository with specified parameters. Node content isn't added.
*
* @param nodeService Alfresco Node Service
* @param parent Parent node
* @param name Name of the new node
* @param assocType Association type that should be set between parent node and the new one.
* @return Reference to created node
*/
protected NodeRef addContentNode(NodeService nodeService, NodeRef parent, String name, QName assocType)
{
NodeRef childNodeRef = nodeService.getChildByName(parent, assocType, name);
if (childNodeRef != null)
{
// The node is present already. Make sure the name csae is correct
nodeService.setProperty(childNodeRef, ContentModel.PROP_NAME, name);
}
else
{
Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>();
contentProps.put(ContentModel.PROP_NAME, name);
ChildAssociationRef associationRef = nodeService.createNode(
parent,
assocType,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name),
ContentModel.TYPE_CONTENT,
contentProps);
childNodeRef = associationRef.getChildRef();
}
return childNodeRef;
}
/**
* Add new node into Alfresco repository with specified parameters.
* Node content isn't added. New node will be created with ContentModel.ASSOC_CONTAINS association with parent.
*
* @param nodeService Alfresco Node Service
* @param parent Parent node
* @param name Name of the new node
* @return Reference to created node
*/
protected NodeRef addContentNode(NodeService nodeService, NodeRef parent, String name)
{
return addContentNode(nodeService, parent, name, ContentModel.ASSOC_CONTAINS);
}
/**
* Adds new node into Alfresco repository and mark its as an attachment.
*
* @param nodeService Alfresco Node Service.
* @param folder Space/Folder to add.
* @param mainContentNode Main content node. Any mail is added into Alfresco as one main content node and several its attachments. Each attachment related with its main node.
* @param fileName File name for the attachment.
* @return Reference to created node.
*/
protected NodeRef addAttachment(NodeService nodeService, NodeRef folder, NodeRef mainContentNode, String fileName)
{
fileName = getAppropriateNodeName(folder, fileName, ContentModel.ASSOC_CONTAINS);
if (log.isDebugEnabled())
{
log.debug("Adding attachment node (name=" + fileName + ").");
}
NodeRef attachmentNode = addContentNode(nodeService, folder, fileName);
// Add attached aspect
nodeService.addAspect(mainContentNode, ContentModel.ASPECT_ATTACHABLE, null);
// Add the association
nodeService.createAssociation(mainContentNode, attachmentNode, ContentModel.ASSOC_ATTACHMENTS);
if (log.isDebugEnabled())
{
log.debug("Attachment has been added.");
}
return attachmentNode;
}
/**
* Return unique content name in passed folder based on provided name
*
* @param parent parent folder
* @param name name of node
* @param assocType assocType between parent and child
* @return Original name or name in format {name}({number})
*/
private String getAppropriateNodeName(NodeRef parent, String name, QName assocType)
{
if (nodeService.getChildByName(parent, assocType, name) != null)
{
name = name + "(1)";
while (nodeService.getChildByName(parent, assocType, name) != null)
{
int index = name.lastIndexOf("(");
if ((index > 0) && name.charAt(name.length() - 1) == ')')
{
String posibleNumber = name.substring(index + 1, name.length() - 1);
long num = Long.parseLong(posibleNumber) + 1;
name = name.substring(0, index) + "(" + num + ")";
}
}
}
return name;
}
/**
* Extracts the attachments from the given message and adds them to the space. All attachments
* are linked back to the original node that they are attached to.
*
* @param spaceNodeRef the space to add the documents into
* @param nodeRef the node to which the documents will be attached
* @param message the email message
*/
protected void addAttachments(NodeRef spaceNodeRef, NodeRef nodeRef, EmailMessage message)
{
// Add attachments
EmailMessagePart[] attachments = message.getAttachments();
for (EmailMessagePart attachment : attachments)
{
String fileName = attachment.getFileName();
InputStream contentIs = attachment.getContent();
MimetypeService mimetypeService = getMimetypeService();
String mimetype = mimetypeService.guessMimetype(fileName);
String encoding = attachment.getEncoding();
NodeRef attachmentNode = addAttachment(getNodeService(), spaceNodeRef, nodeRef, fileName);
writeContent(attachmentNode, contentIs, mimetype, encoding);
}
}
}