1 /****************************************************************
2 * Licensed to the Apache Software Foundation (ASF) under one *
3 * or more contributor license agreements. See the NOTICE file *
4 * distributed with this work for additional information *
5 * regarding copyright ownership. The ASF licenses this file *
6 * to you under the Apache License, Version 2.0 (the *
7 * "License"); you may not use this file except in compliance *
8 * with the License. You may obtain a copy of the License at *
9 * *
10 * http://www.apache.org/licenses/LICENSE-2.0 *
11 * *
12 * Unless required by applicable law or agreed to in writing, *
13 * software distributed under the License is distributed on an *
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
15 * KIND, either express or implied. See the License for the *
16 * specific language governing permissions and limitations *
17 * under the License. *
18 ****************************************************************/
19
20 package org.apache.jsieve.mailet;
21
22 import javax.mail.MessagingException;
23
24 import org.apache.mailet.Mail;
25 import org.apache.mailet.MailAddress;
26
27 /**
28 * Utility methods helpful for actions.
29 */
30 public class ActionUtils
31 {
32
33 private final static String ATTRIBUTE_PREFIX = ActionUtils.class.getPackage().getName() + ".";
34
35 /**
36 * Answers the sole intended recipient for aMail.
37 *
38 * @param aMail
39 * @return String
40 * @throws MessagingException
41 */
42 public static MailAddress getSoleRecipient(Mail aMail) throws MessagingException
43 {
44 if (aMail.getRecipients() == null) {
45 throw new MessagingException("Invalid number of recipients - 0"
46 + ". Exactly 1 recipient is expected.");
47 } else if (1 != aMail.getRecipients().size())
48 throw new MessagingException("Invalid number of recipients - "
49 + new Integer(aMail.getRecipients().size()).toString()
50 + ". Exactly 1 recipient is expected.");
51 return (MailAddress) aMail.getRecipients().iterator().next();
52 }
53
54 /**
55 * Detect and handle locally looping mail. External loop detection is left
56 * to the MTA.
57 *
58 * @param aMail
59 * @param context not null
60 * @param anAttributeSuffix
61 * @throws MessagingException
62 */
63 public static void detectAndHandleLocalLooping(Mail aMail, ActionContext context, String anAttributeSuffix)
64 throws MessagingException
65 {
66 MailAddress thisRecipient = getSoleRecipient(aMail);
67 MailAddress lastRecipient = (MailAddress) aMail
68 .getAttribute(ATTRIBUTE_PREFIX + anAttributeSuffix);
69 if (null != lastRecipient && lastRecipient.equals(thisRecipient))
70 {
71 MessagingException ex = new MessagingException(
72 "This message is looping! Message ID: "
73 + aMail.getMessage().getMessageID());
74 context.getLog().warn(ex.getMessage(), ex);
75 throw ex;
76 }
77 aMail.setAttribute(ATTRIBUTE_PREFIX + anAttributeSuffix,
78 thisRecipient);
79 }
80 }