001 /*
002 * Copyright 2010 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016 package com.hs.mail.sieve;
017
018 import java.io.BufferedInputStream;
019 import java.io.File;
020 import java.io.FileInputStream;
021 import java.io.InputStream;
022
023 import org.apache.commons.io.IOUtils;
024 import org.apache.jsieve.ConfigurationManager;
025 import org.apache.jsieve.SieveConfigurationException;
026 import org.apache.jsieve.SieveFactory;
027 import org.apache.log4j.Logger;
028
029 import com.hs.mail.container.config.Config;
030 import com.hs.mail.mailet.MailetContext;
031 import com.hs.mail.smtp.message.Recipient;
032 import com.hs.mail.smtp.message.SmtpMessage;
033
034 public class Sieve {
035
036 static Logger logger = Logger.getLogger(Sieve.class);
037
038 public static final String DEFAULT_SIEVE = "default.sieve";
039
040 private static SieveFactory factory = null;
041 static {
042 try {
043 ConfigurationManager config = new ConfigurationManager();
044 factory = config.build();
045 } catch (SieveConfigurationException e) {
046 logger.error(e.getMessage(), e);
047 }
048 }
049
050 public static boolean runSieve(MailetContext context, Recipient recipient,
051 SmtpMessage msg) {
052 File script = getScript(context, recipient);
053 if (script != null) {
054 InputStream is = null;
055 try {
056 SieveMailAdapter adapter = new SieveMailAdapter(context,
057 recipient.getMailbox(), recipient.getID());
058 adapter.setMessage(msg);
059 is = new BufferedInputStream(new FileInputStream(script));
060 factory.interpret(adapter, is);
061 return true;
062 } catch (Exception e) {
063 logger.error(e.getMessage());
064 } finally {
065 IOUtils.closeQuietly(is);
066 }
067 }
068 return false;
069 }
070
071 private static File getScript(MailetContext context, Recipient recipient) {
072 File dir = context.getUserManager().getUserHome(recipient);
073 File script = new File(dir, DEFAULT_SIEVE);
074 if (script.exists()) {
075 return script;
076 }
077 // If user's sieve script does not exist, then check for domain's
078 // default sieve script.
079 String domain = (recipient.getHost() != null) ? recipient.getHost()
080 : Config.getDefaultDomain();
081 dir = new File(Config.getDataDirectory(), domain);
082 script = new File(dir, DEFAULT_SIEVE);
083 return (script.exists()) ? script : null;
084 }
085
086 }