james-server-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Virender Dogra" <viren...@ix.netcom.com>
Subject RE: would matcher AttachmentFilenameIsRegex be of use
Date Tue, 15 Jul 2003 22:53:25 GMT
The attachment got removed so here is my cut and paste

Hello Noel,

Please find the attached regular expression matcher for attachments. I
have named the file "AttachmentFileNameIsRegex.java" with "FileName"
having "N" as caps like in "AttachmentFileNameIs.java" 

Location: src\java\org\apache\james\transport\matchers

Please let me know if my submission procedure is too weird. Thanks.

I had promised test cases but have found it impossible for now to create
a testcase. I have run into issues like "how to set up a context" for
the getCondition() call, creating a session(?), etc. Any pointers where
I can find information on this issue?

Also would it be ok to create a package called "test.org.apache....."
for the testcases.

Thanks and sorry for so many queries ;-)

- Virender

>>>>>>>>>>   Cut here  for "AttachmentFileNameIsRegex.java"
>>>>>>>>>>>>>>>>>>>

package org.apache.james.transport.matchers;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Locale;
import java.util.StringTokenizer;

import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.MimeMessage;

import org.apache.mailet.GenericMatcher;
import org.apache.mailet.Mail;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;

/**
 * <P>Checks if at least one attachment has a file name which matches
any
 * element of a comma-separated list of regular expressions. </P>
 * <P>Multiple file name regular expressions can be specified, 
 * e.g.: (.*).(exe|bat|vbs), image(.+)2003.(jpg|gif|jpeg|jpe), web(.*),
insecure(.?).js </P>
 *
 * The method match(Mail) is a verbatim copy from AttachmentFileNameIs
 * Couldn't inherit from AttachmentFileNameIs as it kept running into
Nullpointer exceptions
 * 
 * @author Virender Dogra
 * @version 1 $Date: 2003/07/15
 * @since 2.2.0
 */

public class AttachmentFileNameIsRegex extends GenericMatcher
{

  /** contains compiled patterns, setup by init */
  private Perl5Matcher matcher;
  private Collection patterns;

  /** parses and compile the condition for the regular expressions */
  public void init() throws MessagingException
  {
    StringTokenizer st = new StringTokenizer(getCondition(), ", ",
false);
    try
    {

      patterns = compile(Collections.list(st));
    } catch (MalformedPatternException mp)
    {
      throw new MessagingException("Could not initialize regex
patterns", mp);
    }
  }

  /**
    * Checks if <I>fileName</I> matches with at least one of the
<CODE>patterns</CODE>.
    */
  private boolean matchFound(String fileName)
  {
    fileName = fileName.toLowerCase(Locale.US).trim();

    Iterator patternIter = patterns.iterator();
    while (patternIter.hasNext())
    {
      Pattern regex = (Pattern) patternIter.next();

      if (matcher.matches(fileName, regex))
      {
        return true; // matching file found
      }
    }
    return false;
  }

  /** Compiles a collection of regular expressions and reinsertes the
compiled pattern back into 
   * the collection replacing the initila expression 
   * */

  private Collection compile(Collection inPatterns) throws
MalformedPatternException
  {
    // compile a bunch of regular expressions
    Collection compiledPatterns = new ArrayList(10);
    matcher = new Perl5Matcher();
    Iterator pattIter = inPatterns.iterator();
    while (pattIter.hasNext())
    {
      String regex = (String) pattIter.next();
      compiledPatterns.add(new Perl5Compiler().compile(regex));
    }
    return compiledPatterns;
  }

// * The method match(Mail) is a verbatim copy from AttachmentFileNameIs
// * Couldn't inherit from AttachmentFileNameIs as then it kept running
into : 
//     exception! javax.mail.MessagingException: Malformed message;
//      nested exception is:
//       java.lang.NullPointerException
// * Please help if you can ;-)

  public Collection match(Mail mail) throws MessagingException
  {

    Exception anException = null;

    try
    {
      MimeMessage message = mail.getMessage();
      Object content;

      /**
       * if there is an attachment and no inline text,
       * the content type can be anything
       */
      if (message.getContentType() == null)
      {
        return null;
      }

      content = message.getContent();
      if (content instanceof Multipart)
      {
        Multipart multipart = (Multipart) content;
        for (int i = 0; i < multipart.getCount(); i++)
        {
          try
          {
            Part part = multipart.getBodyPart(i);
            String fileName = part.getFileName();
            if (fileName != null && matchFound(fileName))
            {
              return mail.getRecipients(); // matching file found
            }
          } catch (MessagingException e)
          {
            anException = e;
          } // ignore any messaging exception and process next bodypart
        }
      } else
      {
        String fileName = message.getFileName();
        if (fileName != null && matchFound(fileName))
        {
          return mail.getRecipients(); // matching file found
        }
      }
    } catch (Exception e)
    {
      anException = e;
    }

    // if no matching attachment was found and at least one exception
was catched rethrow it up
    if (anException != null)
    {
      throw new MessagingException("Error message", anException);
    }

    return null; // no matching attachment found
  }

  /*
  // Code to test a small piece of this class until i find a better way
to test the 
  // whole class using junit
  
    public void matchFoundForTesting(String fileNames, String condition)
      throws MalformedPatternException
    {
      StringTokenizer st = new StringTokenizer(condition, ", ", false);
      this.patterns = compile(Collections.list(st));
  
      StringTokenizer files = new StringTokenizer(fileNames, ", ",
false);
      Collection fileNameColl = Collections.list(files);
      Iterator fileIter = fileNameColl.iterator();
      while (fileIter.hasNext())
      {
        String filename = (String)fileIter.next();
        System.out.println(matchFound(filename) + " for file : " +
filename);
      }
    }
  */
}

<<<<<<<<<<<<<<<<<<<<<<<<<<<
  Cut here
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org


Mime
View raw message