Dave Ward e0b40d177f Merged V3.3-BUG-FIX to HEAD
23080: Fix for ALF-3815 - Error occur on creating user (Active Directory +LDAP authentication)
   23084: MERGED DEV to V3.3-BUG-FIX
      22839 :  ALF-4920 - IMAP server UID failure
   23102: Checked in file with my Hostname!
   23141: Merged PATCHES/V3.2.0 to V3.3-BUG-FIX
      22977: ALF-5057: Don't use lucene to locate tag nodes - unreliable in a cluster
         - CategoryService extended with root category retrieval method using node service
      23043: ALF-5057: Merged V3.2 to PATCHES/V3.2.0 (partial)
         18052: Merged DEV/REPO-DOCLIB to V3.2
            17653: Checkpoint Repo DocLib prototype work
   23142: Merged PATCHES/V3.2.0 to V3.3-BUG-FIX
      22981: ALF-5141: Need to limit webscript response times and reject traffic at high load
         - server.web.transaction.max-duration-ms property now specifies a maximum time for repository webscript transaction execution. Default is 10 seconds.
         - transaction retrying will not continue when the projected time is greater than this
         - Once a transaction hits this execution time the number of concurrently executing transactions at the time it was started becomes the ‘ceiling’ for the number of concurrent transactions
         - The ceiling will dynamically rise and fall, based on transaction execution times
         - When a transaction is started ‘above’ the current ceiling a TooBusyException is thrown, which is mapped to an immediate status 503 response
         - New unit test added for this
      23006: ALF-5141: Reverting IndexInfo changes
         - 'fairness' flag on ReentrantReadWriteLock appears to cause deadlock on JDK 1.5 in IndexInfoTest
         - lucene.indexer.maxMergeWait property and associated throttling 'back off' behaviour abandoned as it has the risk of leaving indexes in incomplete uncommited state
         - transaction limiter feature should be enough to avoid excessive wait times
      23011: ALF-5141: Reintroduce fair locking to IndexInfo and fix RetryingTransactionHelperTest
         - Bugs surrounding ReentrantReadWriteLock in old JVMs mean that it's not safe to make fair locking the default
         - However, it would be useful in new JVMs as it should guarantee that we don't lock out waiting writers indefinitely under high load
         - Now controlled by lucene.indexer.fairLocking property. Default value is false in V3.2.0 but true in V3.3.4 onwards.
         - RetryingTransactionHelperTest now uses latches to ensure test threads start up in strict sequential order
      23014: ALF-5141: Correct error that could allow transaction ceiling to be lowered to zero
   23146: (RECORD ONLY) ALF-5028: Merged HEAD to V3.3-BUG-FIX
      21471: SAIL-240 (SAIL-294) AuditDAO: AuditService enhancements
         - Added isAuditEnabled and enableAudit for global case (system-wide)
         - Some neatening up of Audit SQL (common WHERE and ORDER BY clauses)
         - AuditService enforces 'admin' role for all methods
      22109: ALF-4106: Added entry deletion count return value for clear()
      22726: Coding standards
      22857: Fix typo in javadoc
      22980: Added AuditService.clearAudit(List<Long>)
      22986: ALF-5028 - Tagging Service Update - Use the audit service as a persisted event log, so that tag scope updates can occur in batches and without contention issues. (Further tests and post-startup executor still needed)
         This commit enables the Audit Service by default, but turns off all the audit applications except tagging by default, so there shouldn't be any noticable changes
      22997: ALF-5028 - More tag scope updates and unit tests. Shortly after the system is started, check for un-applied tag scope updates, and apply them.
      23015: ALF-5028: Tagging test mods
         - Join onto first-level threads to be sure that first round of tagging has been done
         - Double-checks for transaction leaks (found 1)
         - Some formatting (new test only, but should be applied to file)
   23148: Merged PATCHES/V3.2.0 to V3.3-BUG-FIX
      23133: ALF-5221: Fixed file handle leaks in TaggingService
   23149: Merged V3.2 to V3.3-BUG-FIX
      23070: Part-fix ALF-5134: Performance of Alfresco cluster less than performance of single node
         - Prevent cache being updated even when there are no changes
         - Prevents some cache invalidation messages during read operations
      23071: ALF-5134: Performance of Alfresco cluster less than performance of single node
         - Removed null-equivalence check in TransactionalCache
         - Avoids cache update messages when running against empty caches
   23150: (RECORD ONLY) ALF-5235: Merged HEAD to V3.3-BUG-FIX
      22695: ALF-3800 "File is uploaded to the Document Library when its size more than user quota": make sure the exception is thrown back up to the transaction machinery to perform a rollback
   23156: Merged V3.3 to V3.3-BUG-FIX
      22913: Add jars back into Tomcat bundles
      23028: Merged DEV to V33:
         23022: ALF-4760 : XAM post-retention cleanup job: XAMArchiveJob
            1. Post-retention xam cleanup job was implemented according to requirements provided by Derek.
            2. Unit tests was added for new functionality.
      23125: Merged HEAD to V3.3
         20752: BatchProcessor is fed work by a BatchProcessWorkProvider
         22297: Fixed ALF-4676: WorkProviderIterator over BatchProcessWorkProvider does not fetch all results
      23126: (RECORD ONLY) Merged BRANCHES/DEV/V3.3-BUG-FIX to BRANCHES/V3.3:
         22883: ALF-4800 - AVM - intermittent test failure (layered file delete)


git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@23161 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
2010-10-15 15:43:21 +00:00

291 lines
11 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.imap;
import static org.alfresco.repo.imap.AlfrescoImapConst.MIME_VERSION;
import static org.alfresco.repo.imap.AlfrescoImapConst.X_ALF_NODEREF_ID;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.extensions.surf.util.I18NUtil;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.imap.ImapService.EmailBodyType;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.template.TemplateNode;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QName;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author Arseny Kovalchuk
*/
public abstract class AbstractMimeMessage extends MimeMessage
{
/** Used if imapHelper.getDefaultFromAddress is not set */
protected static final String DEFAULT_EMAIL_FROM = "alfresco@alfresco.org";
protected static final String DEFAULT_EMAIL_TO = DEFAULT_EMAIL_FROM;
protected static int MAX_RETRIES = 1;
private Log logger = LogFactory.getLog(AbstractMimeMessage.class);
protected boolean generateBody = true;
protected ServiceRegistry serviceRegistry;
protected ImapService imapService;
protected FileInfo messageFileInfo;
protected MimeMessage wrappedMessage;
protected AbstractMimeMessage(Session session)
{
super(session);
}
protected AbstractMimeMessage(FileInfo fileInfo, ServiceRegistry serviceRegistry, boolean generateBody) throws MessagingException
{
super(Session.getDefaultInstance(new Properties()));
this.generateBody = generateBody;
buildMessage(fileInfo, serviceRegistry);
}
protected void buildMessage(FileInfo fileInfo, ServiceRegistry serviceRegistry) throws MessagingException
{
checkParameter(serviceRegistry, "ServiceRegistry");
this.content = null;
this.serviceRegistry = serviceRegistry;
this.imapService = serviceRegistry.getImapService();
this.messageFileInfo = fileInfo;
RetryingTransactionHelper txHelper = serviceRegistry.getTransactionService().getRetryingTransactionHelper();
txHelper.setMaxRetries(MAX_RETRIES);
txHelper.setReadOnly(false);
txHelper.doInTransaction(new RetryingTransactionCallback<Object>() {
public Object execute() throws Throwable
{
buildMessageInternal();
return null;
}
}, false);
}
/**
* Method must be implemented in subclasses. It usually should be used to generate message body.
*
* @throws MessagingException
*/
public abstract void buildMessageInternal() throws MessagingException;
/**
* Method that checks mandatory parameter.
* @param The parameter instance to check.
* @param The name of the parameter.
*/
protected void checkParameter(Object parameter, String name)
{
if (parameter == null)
{
throw new IllegalArgumentException(name + " parameter is null.");
}
}
protected void setMessageHeaders() throws MessagingException
{
setHeader(MIME_VERSION, "1.0");
// Optional headers for further implementation of multiple Alfresco server support.
setHeader(X_ALF_NODEREF_ID, messageFileInfo.getNodeRef().getId());
// setHeader(X_ALF_SERVER_UID, imapService.getAlfrescoServerUID());
}
/**
* Builds the InternetAddress from the Content Author name if provided. If name not specified, it takes Content Creator name. If content creator does not exists, the default
* from address will be returned.
*
* @param contentAuthor The content author full name.
* @return Generated InternetAddress[] array.
* @throws AddressException
*/
protected InternetAddress[] buildSenderFromAddress() throws AddressException
{
// Generate FROM address (Content author)
InternetAddress[] addressList = null;
Map<QName, Serializable> properties = messageFileInfo.getProperties();
String prop = (String) properties.get(ContentModel.PROP_AUTHOR);
String defaultFromAddress = imapService.getDefaultFromAddress();
defaultFromAddress = defaultFromAddress == null ? DEFAULT_EMAIL_FROM : defaultFromAddress;
try
{
if (prop != null)
{
StringBuilder contentAuthor = new StringBuilder();
contentAuthor.append("\"").append(prop).append("\" <").append(defaultFromAddress).append(">");
addressList = InternetAddress.parse(contentAuthor.toString());
}
else
{
prop = (String) properties.get(ContentModel.PROP_CREATOR);
if (prop != null)
{
StringBuilder creator = new StringBuilder();
creator.append("\"").append(prop).append("\" <").append(defaultFromAddress).append(">");
addressList = InternetAddress.parse(creator.toString());
}
else
{
throw new AddressException(I18NUtil.getMessage("imap.server.error.properties_dont_exist"));
}
}
}
catch (AddressException e)
{
addressList = InternetAddress.parse(DEFAULT_EMAIL_FROM);
}
return addressList;
}
/**
* Returns {@link FileInfo} object representing message in Alfresco.
*
* @return reference to the {@link FileInfo} object.
*/
public FileInfo getMessageInfo()
{
return messageFileInfo;
}
/**
* Returns message flags.
*
* @return {@link Flags}
*/
@Override
public Flags getFlags()
{
return imapService.getFlags(messageFileInfo);
}
/**
* Sets message flags.
*
* @param flags - {@link Flags} object.
* @param value - flags value.
*/
@Override
public void setFlags(Flags flags, boolean value) throws MessagingException
{
imapService.setFlags(messageFileInfo, flags, value);
}
/**
* Returns the text representing email body for ContentModel node.
*
* @param nodeRef NodeRef of the target content.
* @param type The type of the returned body. May be the one of {@link EmailBodyType}.
* @return Text representing email body for ContentModel node.
*/
public String getEmailBodyText(EmailBodyType type)
{
return serviceRegistry.getTemplateService().processTemplate(
imapService.getDefaultEmailBodyTemplate(type),
createEmailTemplateModel(messageFileInfo.getNodeRef()));
}
/**
* TODO USE CASE 2: "The To/addressee will be the first email alias found in the parent folders or a default one (TBD)".
* It seems to be more informative as alike {@code <user>@<current.domain>}...
*
* @return Generated TO address {@code <user>@<current.domain>}
* @throws AddressException
*/
protected InternetAddress[] buildRecipientToAddress() throws AddressException
{
InternetAddress[] result = null;
String defaultEmailTo = null;
final String escapedUserName = AuthenticationUtil.getFullyAuthenticatedUser().replaceAll("[/,\\,@]", ".");
final String userDomain = DEFAULT_EMAIL_TO.split("@")[1];
defaultEmailTo = escapedUserName + "@" + userDomain;
try
{
result = InternetAddress.parse(defaultEmailTo);
}
catch (AddressException e)
{
logger.error(String.format("Wrong email address '%s'.", defaultEmailTo), e);
result = InternetAddress.parse(DEFAULT_EMAIL_TO);
}
return result;
}
protected void addFromInternal(String addressesString) throws MessagingException
{
if (addressesString != null)
{
addFrom(InternetAddress.parse(addressesString));
}
else
{
addFrom(new Address[] { new InternetAddress(DEFAULT_EMAIL_FROM) });
}
}
/**
* Builds default email template model for TemplateProcessor
*
* @param ref NodeRef of the target content.
* @return Map that includes template model objects.
*/
private Map<String, Object> createEmailTemplateModel(NodeRef ref)
{
Map<String, Object> model = new HashMap<String, Object>(8, 1.0f);
TemplateNode tn = new TemplateNode(ref, serviceRegistry, null);
model.put("document", tn);
NodeRef parent = serviceRegistry.getNodeService().getPrimaryParent(ref).getParentRef();
model.put("space", new TemplateNode(parent, serviceRegistry, null));
model.put("date", new Date());
model.put("contextUrl", new String(imapService.getWebApplicationContextUrl()));
model.put("alfTicket", new String(serviceRegistry.getAuthenticationService().getCurrentTicket()));
return model;
}
protected void updateMessageID() throws MessagingException
{
setHeader("Message-ID", this.messageFileInfo.getNodeRef().getId());
}
}