/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software License
 * version 1.1, a copy of which has been included with this distribution in
 * the LICENSE file.
 */
package org.apache.james.transport.matchers ;

import org.apache.mailet.GenericMatcher ;
import org.apache.mailet.Mail ;

import java.util.Collection ;
import java.util.StringTokenizer ;
import java.util.Vector ;

/**
 * Checkes the sender's displayed domain name against a supplied list.
 *
 * Sample configuration:
 *
 * <mailet match="SenderHostIs=domain.com" class="ToProcessor">
 *   <processor> spam </processor>
 * </mailet>
 *
 * @version 1.0.0, 2002-09-10
 * @author  Chris Means <cmeans@intfar.com>
 */
public class SenderHostIs
       extends GenericMatcher
{
  /**
   * The collection of host names to match against.
   */
  private Collection senderHosts ;

  /**
   * Initialize the mailet.
   */
  public void init ()
  {
    //Parse the condition...
    StringTokenizer st = new StringTokenizer (getCondition (),
                                              ", ",
                                              false) ;

    //..into a vector of domain names.
    senderHosts = new Vector () ;
    while (st.hasMoreTokens ())
      senderHosts.add (((String) st.nextToken ()).toLowerCase ()) ;
  }

  /**
   * Takes the message and checks the sender (if there is one) against
   * the vector of host names.
   *
   * Returns the collection of recipients if there's a match.
   *
   * @param mail the mail being processed
   */
  public Collection match (Mail mail)
  {
    try
    {
      if (mail.getSender () != null)
        if (senderHosts.contains (mail.getSender ().getHost ().toLowerCase ()))
          return mail.getRecipients () ;
    }
    catch (Exception e)
    {
      log (e.getMessage ()) ;
    }

    //No match.
    return null ;
  }
}

