huber       2003/01/06 13:51:21

  Added:       src/scratchpad/src/org/apache/cocoon/mail
                        ContentTypePreference.java IndexerCtPref.java
                        MailAction.java MailCommandBuilder.java
                        MailCommandManager.java MailCommandSelector.java
                        MailContentHandlerDelegate.java MailContext.java
                        MailContextHttpSession.java MailCtPref.java
                        MailGenerator.java MimeMessageUtil.java
               src/scratchpad/src/org/apache/cocoon/mail/command
                        AbstractMailCommand.java MailCommand.java
                        MailCommands.java
  Log:
  initial version of mail store access
  
  Revision  Changes    Path
  1.1                  
xml-cocoon2/src/scratchpad/src/org/apache/cocoon/mail/ContentTypePreference.java
  
  Index: ContentTypePreference.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.mail;
  
  import javax.mail.*;
  import javax.mail.internet.*;
  
  /**
   *  Description of the Interface
   *
   [EMAIL PROTECTED]     Bernhard Huber
   [EMAIL PROTECTED]    26. Oktober 2002
   */
  public interface ContentTypePreference {
      /**
       *  Description of the Method
       *
       [EMAIL PROTECTED]  mimepart  Description of the Parameter
       [EMAIL PROTECTED]           Description of the Return Value
       */
      public int preference(MimePart mimepart);
  }
  
  
  
  
  
  1.1                  
xml-cocoon2/src/scratchpad/src/org/apache/cocoon/mail/IndexerCtPref.java
  
  Index: IndexerCtPref.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.mail;
  
  import javax.mail.*;
  import javax.mail.internet.*;
  
  /**
   *  Description of the Class
   *
   [EMAIL PROTECTED]     Bernhard Huber
   [EMAIL PROTECTED]    26. Oktober 2002
   */
  public class IndexerCtPref implements ContentTypePreference {
      /**
       *  Description of the Method
       *
       [EMAIL PROTECTED]  part  Description of the Parameter
       [EMAIL PROTECTED]       Description of the Return Value
       */
      public int preference(MimePart part) {
          try {
              if (part.isMimeType("text/html")) {
                  return 5;
              }
              if (part.isMimeType("text/*")) {
                  return 10;
              }
              if (part.isMimeType("text")) {
                  return 9;
              }
              return 0;
          } catch (MessagingException messagingexception) {
              return 0;
          }
      }
  }
  
  
  
  
  
  1.1                  
xml-cocoon2/src/scratchpad/src/org/apache/cocoon/mail/MailAction.java
  
  Index: MailAction.java
  ===================================================================
  /*
   *  The Apache Software License, Version 1.1
   *
   *
   *  Copyright (c) 2001 The Apache Software Foundation.  All rights
   *  reserved.
   *
   *  Redistribution and use in source and binary forms, with or without
   *  modification, are permitted provided that the following conditions
   *  are met:
   *
   *  1. Redistributions of source code must retain the above copyright
   *  notice, this list of conditions and the following disclaimer.
   *
   *  2. Redistributions in binary form must reproduce the above copyright
   *  notice, this list of conditions and the following disclaimer in
   *  the documentation and/or other materials provided with the
   *  distribution.
   *
   *  3. The end-user documentation included with the redistribution,
   *  if any, must include the following acknowledgment:
   *  "This product includes software developed by the
   *  Apache Software Foundation (http://www.apache.org/)."
   *  Alternately, this acknowledgment may appear in the software itself,
   *  if and wherever such third-party acknowledgments normally appear.
   *
   *  4. The names "Apache Cocoon" and "Apache Software Foundation" must
   *  not be used to endorse or promote products derived from this
   *  software without prior written permission. For written
   *  permission, please contact [EMAIL PROTECTED]
   *
   *  5. Products derived from this software may not be called "Apache",
   *  nor may "Apache" appear in their name, without prior written
   *  permission of the Apache Software Foundation.
   *
   *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   *  DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   *  ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   *  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   *  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   *  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   *  SUCH DAMAGE.
   *  ====================================================================
   *
   *  This software consists of voluntary contributions made by many
   *  individuals on behalf of the Apache Software Foundation.  For more
   *  information on the Apache Software Foundation, please see
   *  <http://www.apache.org/>.
   */
  package org.apache.cocoon.mail;
  import java.io.IOException;
  
  import java.text.SimpleDateFormat;
  import java.util.HashMap;
  import java.util.Iterator;
  import java.util.List;
  import java.util.Map;
  import java.util.Map;
  import java.util.Properties;
  import java.util.Properties;
  import javax.mail.Folder;
  import javax.mail.Message;
  import javax.mail.MessagingException;
  import javax.mail.Provider;
  import javax.mail.Store;
  import javax.mail.URLName;
  import javax.servlet.http.HttpSessionBindingEvent;
  import javax.servlet.http.HttpSessionBindingListener;
  //import javax.mail.Session;
  import org.apache.avalon.framework.activity.Disposable;
  import org.apache.avalon.framework.activity.Initializable;
  import org.apache.avalon.framework.component.ComponentException;
  import org.apache.avalon.framework.component.ComponentManager;
  import org.apache.avalon.framework.context.Context;
  import org.apache.avalon.framework.context.ContextException;
  import org.apache.avalon.framework.context.Contextualizable;
  import org.apache.avalon.framework.context.DefaultContext;
  import org.apache.avalon.framework.logger.LogEnabled;
  import org.apache.avalon.framework.logger.LogEnabled;
  import org.apache.avalon.framework.logger.Logger;
  import org.apache.avalon.framework.logger.Logger;
  import org.apache.avalon.framework.parameters.Parameters;
  import org.apache.avalon.framework.parameters.Parameters;
  import org.apache.avalon.framework.thread.ThreadSafe;
  import org.apache.cocoon.Constants;
  import org.apache.cocoon.ProcessingException;
  import org.apache.cocoon.acting.ComposerAction;
  import org.apache.cocoon.environment.ObjectModelHelper;
  import org.apache.cocoon.environment.ObjectModelHelper;
  import org.apache.cocoon.environment.Redirector;
  import org.apache.cocoon.environment.Request;
  import org.apache.cocoon.environment.Request;
  import org.apache.cocoon.environment.Session;
  import org.apache.cocoon.environment.Session;
  import org.apache.cocoon.environment.SourceResolver;
  import org.apache.cocoon.environment.SourceResolver;
  import org.apache.cocoon.generation.ComposerGenerator;
  import org.apache.cocoon.mail.command.AbstractMailCommand;
  import org.apache.cocoon.util.NetUtils;
  import org.apache.excalibur.source.Source;
  import org.xml.sax.SAXException;
  
  /**
   * This action ...
   *
   [EMAIL PROTECTED]     Bernhard Huber
   [EMAIL PROTECTED]    16. Dezember 2002
   [EMAIL PROTECTED]    CVS $Id: MailAction.java,v 1.1 2003/01/06 21:51:20 
huber Exp $
   [EMAIL PROTECTED]      2.1
   */
  public class MailAction extends ComposerAction implements ThreadSafe {
  
      /**
       *  Request attribute name of a XMLizable folder
       */
      public final static String REQUEST_ATTRIBUTE_FOLDER = "folder";
      /**
       *  Request attribute name of a XMLizable folders object
       */
      public final static String REQUEST_ATTRIBUTE_FOLDERS = "folders";
      /**
       *  Request attribute name of a XMLizable message object
       */
      public final static String REQUEST_ATTRIBUTE_MESSAGE = "message";
      /**
       *  Request attribute name of a XMLizable messages object
       */
      public final static String REQUEST_ATTRIBUTE_MESSAGES = "messages";
  
  
      /**
       * Execute mail commands.
       *
       [EMAIL PROTECTED]  redirector     Cocoon's redirector
       [EMAIL PROTECTED]  resolver       Cocoon's source resolver, used for 
testing if a source is resolvable
       [EMAIL PROTECTED]  source         the source, e.g.: index.html
       [EMAIL PROTECTED]  objectModel    Description of the Parameter
       [EMAIL PROTECTED]  par            Description of the Parameter
       [EMAIL PROTECTED]
       [EMAIL PROTECTED]  Exception  Description of the Exception
       */
      public Map act(Redirector redirector, SourceResolver resolver, Map 
objectModel, String source, Parameters par) throws Exception {
          Map actionMap = new HashMap();
  
          Request request = ObjectModelHelper.getRequest(objectModel);
  
          String command = request.getParameter("cmd");
          String folderName = request.getParameter("folder");
          String userid = request.getParameter("mail-userid");
          String password = request.getParameter("mail-password");
          
          // assert mailContext is available
          Session session = request.getSession(true);
          MailContext mailContext = (MailContext) 
session.getAttribute(MailContext.SESSION_MAIL_CONTEXT);
          if (mailContext == null) {
              // no mailContext is yet available
              // create it and put it into http-session
              mailContext = new MailContextHttpSession(null);
              mailContext.enableLogging(getLogger());
              session.setAttribute(MailContext.SESSION_MAIL_CONTEXT, 
mailContext);
          }
  
          // assert mailSession is available
          javax.mail.Session mailSession = null;
          Store mailStore = null;
          try {
              try {
                  mailSession = (javax.mail.Session) 
mailContext.get(MailContext.MAIL_SESSION_ENTRY);
              } catch (ContextException ce) {
                  // build session properties
                  Properties sessionProperties = new Properties();
                  String[] allParameterNames = par.getNames();
                  for (int i = 0; i < allParameterNames.length; i++) {
                      String parameterName = allParameterNames[i];
                      final String PARAMETER_NAME_PREFIX = 
"javax.mail.Session.props:";
                      if (parameterName.startsWith(PARAMETER_NAME_PREFIX)) {
                          String sessionPropName = 
parameterName.substring(PARAMETER_NAME_PREFIX.length());
                          String sessionPropValue = 
par.getParameter(parameterName, null);
                          if (sessionPropValue != null) {
                              getLogger().debug("Add session property " +
                                      String.valueOf(sessionPropName) + ": " +
                                      String.valueOf(sessionPropValue));
                              sessionProperties.put(sessionPropName, 
sessionPropValue);
                          }
                      }
                  }
                  mailSession = 
javax.mail.Session.getDefaultInstance(sessionProperties, null);
                  checkProviders(mailSession);
                  mailContext.put(MailContext.MAIL_SESSION_ENTRY, mailSession);
              }
          } catch (Exception e) {
              String message = "Cannot create mail session";
              getLogger().error(message, e);
              throw new ProcessingException(message, e);
          }
  
          // assert mailStore is available
          String storeURLNameExpanded = null;
          String storeURLNameTemplate = par.getParameter("store-urlname", null);
          try {
              try {
                  mailStore = (Store) 
mailContext.get(MailContext.MAIL_STORE_ENTRY);
              } catch (ContextException ce) {
  
                  // imap://{userid}:[EMAIL PROTECTED]:port/
                  storeURLNameExpanded = 
getURLNameExpanded(storeURLNameTemplate, userid, password);
  
                  URLName urlNameExpanded = new URLName(storeURLNameExpanded);
                  getLogger().info("get store using URLName " + 
String.valueOf(urlNameExpanded));
                  mailStore = mailSession.getStore(urlNameExpanded);
                  mailStore.connect();
                  mailContext.put(MailContext.MAIL_STORE_ENTRY, mailStore);
              }
          } catch (Exception e) {
              String message = "Cannot get store, and connect " + 
String.valueOf(storeURLNameExpanded);
              getLogger().error(message, e);
              throw new ProcessingException(message, e);
          }
  
          if (folderName != null) {
              // make folderName the current working folder (a la cwd)
              // check foldername a bit
              mailContext.put(MailContext.MAIL_CURRENT_WORKING_FOLDER_ENTRY, 
folderName);
          } else {
              // no folderName in request parameter, retrieve current working 
folder
              folderName = (String) 
mailContext.get(MailContext.MAIL_CURRENT_WORKING_FOLDER_ENTRY);
          }
          actionMap.put(MailContext.MAIL_CURRENT_WORKING_FOLDER_ENTRY, 
folderName);
  
          if (command != null) {
              mailContext.put(MailContext.MAIL_CURRENT_WORKING_COMMAND_ENTRY, 
command);
          } else {
              command = (String) 
mailContext.get(MailContext.MAIL_CURRENT_WORKING_COMMAND_ENTRY);
          }
          actionMap.put(MailContext.MAIL_CURRENT_WORKING_COMMAND_ENTRY, 
command);
  
          // mailSession and mailStore are available
  
          // excecute mail command, and populate request attribute
          mailContext.setRequest(request);
          populateRequestAttribute(request, mailContext);
          // it's better to release ref to request, as it is not needed, and 
helps
          // recycling of the request
          mailContext.setRequest(null);
  
          return actionMap;
      }
  
  
      /**
       *  Gets the uRLNameExpanded attribute of the MailGenerator object
       *
       [EMAIL PROTECTED]  storeURLNameTemplate  Description of the Parameter
       [EMAIL PROTECTED]  userid                Description of the Parameter
       [EMAIL PROTECTED]  password              Description of the Parameter
       [EMAIL PROTECTED]                       The uRLNameExpanded value
       */
      protected String getURLNameExpanded(String storeURLNameTemplate, String 
userid, String password) {
          StringBuffer sb = new StringBuffer(storeURLNameTemplate);
  
          // perhaps find some better way than ''xxx'' placeholder encoding
          int indexOf;
          String template;
          template = "''mail-userid''";
          indexOf = sb.indexOf(template);
          if (indexOf != -1) {
              sb.replace(indexOf, indexOf + template.length(), userid);
          }
          template = "''mail-passwd''";
          indexOf = sb.indexOf(template);
          if (indexOf != -1) {
              sb.replace(indexOf, indexOf + template.length(), password);
          }
          String storeURLNameExpanded = sb.toString();
          return storeURLNameExpanded;
      }
  
  
      /**
       *  Check that the provider need is available
       *
       [EMAIL PROTECTED]  session  The javamail Session used for checking its 
providers.
       */
      protected void checkProviders(javax.mail.Session session) {
          Provider[] providers = session.getProviders();
          // just log the available providers
          for (int i = 0; i < providers.length; i++) {
              getLogger().info("mail provider " + providers[i]);
          }
      }
  
  
      /**
       *  Populate request attribute map.
       *  <p>
       *    Execute mail command, and populate request attribute map with
       *    XMLizable javamail objects, created by the mail command
       *  </p>
       *
       [EMAIL PROTECTED]  request        triggering the creation of javamail 
objects
       [EMAIL PROTECTED]  mailContext    javamail context, store, session, 
folders
       [EMAIL PROTECTED]  Exception  Description of the Exception
       */
      protected void populateRequestAttribute(Request request, MailContext 
mailContext) throws Exception {
          String folderName = (String) 
mailContext.get(MailContext.MAIL_CURRENT_WORKING_FOLDER_ENTRY);
          request.setAttribute(MailContext.MAIL_CURRENT_WORKING_FOLDER_ENTRY, 
folderName);
          String command = (String) 
mailContext.get(MailContext.MAIL_CURRENT_WORKING_COMMAND_ENTRY);
          request.setAttribute(MailContext.MAIL_CURRENT_WORKING_COMMAND_ENTRY, 
command);
  
          // build javamail objects
          List javaMailResult = retrieveJavaMailObjects(mailContext);
          Iterator javaMailResultIterator;
  
          // put javamail objects into request attribute map
          javaMailResultIterator = javaMailResult.iterator();
          //Request request = ObjectModelHelper.getRequest(objectModel);
          putXMLizerToRequestAttribute(request, javaMailResultIterator);
      }
  
  
      /**
       *  Put XMLizable javamail objects into request attribute map
       *
       [EMAIL PROTECTED]  request         holding the destination attribute map
       [EMAIL PROTECTED]  resultIterator  Iterator of
       */
      protected void putXMLizerToRequestAttribute(Request request, Iterator 
resultIterator) {
          if (resultIterator != null) {
              // marshal java mail objects
              Logger logger = getLogger();
  
              String datePattern = "dd.MM.yyyy HH:mm";
              SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
  
              while (resultIterator.hasNext()) {
                  Object objRef = resultIterator.next();
  
                  getLogger().debug("Creating XMLizer for " + 
String.valueOf(objRef));
  
                  if (objRef instanceof Folder) {
                      MailContentHandlerDelegate.FolderXMLizer fx = new 
MailContentHandlerDelegate.FolderXMLizer((Folder) objRef);
                      fx.enableLogging(logger);
                      request.setAttribute(REQUEST_ATTRIBUTE_FOLDER, fx);
                  } else if (objRef instanceof Folder[]) {
                      Folder[] folders = (Folder[]) objRef;
                      MailContentHandlerDelegate.FolderXMLizer[] fxs = new 
MailContentHandlerDelegate.FolderXMLizer[folders.length];
                      for (int i = 0; i < folders.length; i++) {
                          fxs[i] = new 
MailContentHandlerDelegate.FolderXMLizer(folders[i]);
                          fxs[i].enableLogging(logger);
                      }
                      // trust that array of XMLizable is handled
                      request.setAttribute(REQUEST_ATTRIBUTE_FOLDERS, fxs);
                  } else if (objRef instanceof Message) {
                      MailContentHandlerDelegate.MessageXMLizer mx = new 
MailContentHandlerDelegate.MessageXMLizer((Message) objRef);
                      mx.enableLogging(logger);
                      mx.setSimpleDateFormat(sdf);
                      request.setAttribute(REQUEST_ATTRIBUTE_MESSAGE, mx);
                  } else if (objRef instanceof Message[]) {
                      MailContentHandlerDelegate.MessageEnvelopeXMLizer mex = 
new MailContentHandlerDelegate.MessageEnvelopeXMLizer((Message[]) objRef);
                      mex.enableLogging(logger);
                      mex.setSimpleDateFormat(sdf);
                      request.setAttribute(REQUEST_ATTRIBUTE_MESSAGES, mex);
                  }
              }
          }
      }
  
  
      /**
       *   Retrieve javamail objects
       *
       [EMAIL PROTECTED]  mailContext              Description of the Parameter
       [EMAIL PROTECTED]                          List of retrieved javamail 
objects
       [EMAIL PROTECTED]  ProcessingException  thrown iff retrieval fails
       */
      protected List retrieveJavaMailObjects(MailContext mailContext) throws 
ProcessingException {
  
          List result = null;
          try {
              // do we have a MailCommandManager ?
              MailCommandManager mam = new MailCommandManager();
              mam.enableLogging(getLogger());
  
              // build the MailCommand(s)
              MailCommandBuilder mab = new MailCommandBuilder();
              mab.enableLogging(getLogger());
              AbstractMailCommand ama = 
mab.buildAbstractMailCommand(mailContext);
  
              getLogger().debug("Executing " + String.valueOf(ama));
  
              // execute the command(s)
              result = mam.execute(ama);
  
              // return the javamail objects
              return result;
          } catch (Exception e) {
              String message = "Cannot retrieve javamail objects";
              getLogger().error(message, e);
              throw new ProcessingException(message, e);
          }
      }
  }
  
  
  
  
  1.1                  
xml-cocoon2/src/scratchpad/src/org/apache/cocoon/mail/MailCommandBuilder.java
  
  Index: MailCommandBuilder.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.mail;
  
  import java.util.HashMap;
  import java.util.Map;
  import org.apache.avalon.framework.context.Context;
  import org.apache.avalon.framework.context.ContextException;
  import org.apache.avalon.framework.context.Contextualizable;
  import org.apache.avalon.framework.logger.AbstractLogEnabled;
  import org.apache.avalon.framework.logger.LogEnabled;
  import org.apache.cocoon.mail.command.AbstractMailCommand;
  
  /**
   * Build an AbstractMailCommand from MailContext.
   * <p>
   *   As a user requests a command, the command is mapped to an MailCommand 
instance.
   *   The registration of MailCommand, and the resolution of a command string 
to
   *   a command instance are the tasks of this class.
   * </p>
   *
   [EMAIL PROTECTED]     Bernhard Huber
   [EMAIL PROTECTED]    28. Dezember 2002
   [EMAIL PROTECTED]    CVS Version: $Id: MailCommandBuilder.java,v 1.1 
2003/01/06 21:51:20 huber Exp $
   */
  public class MailCommandBuilder extends AbstractLogEnabled {
  
      // global factory settings
      private Map cmdMap;
  
      /**
       *Constructor for the MailCommandBuilder object
       */
      public MailCommandBuilder() {
          configure();
      }
  
  
      /**
       *  Build a mail command.
       *
       [EMAIL PROTECTED]  mailContext  Description of the Parameter
       [EMAIL PROTECTED]              Description of the Return Value
       */
      public AbstractMailCommand buildAbstractMailCommand(MailContext 
mailContext) {
          AbstractMailCommand ama = null;
  
          try {
              // request parameter say "what"
              String cmd = mailContext.getParameter("cmd");
              if (cmd == null) {
                  cmd = (String)mailContext.get( 
MailContext.MAIL_CURRENT_WORKING_COMMAND_ENTRY );
              }
              Class clazz = (Class) getClassForCommand(cmd);
              if (clazz != null) {
                  ama = (AbstractMailCommand) clazz.newInstance();
                  // enable logging of the mail command
                  if (ama instanceof LogEnabled) {
                      ((LogEnabled) ama).enableLogging(getLogger());
                  }
                  // contextualize the mail command
                  if (ama instanceof Contextualizable) {
                      ((Contextualizable) ama).contextualize(mailContext);
                  }
                  return ama;
              } else {
                  getLogger().error("Cmd " + String.valueOf(cmd) + " is 
invalid");
              }
          } catch (Exception e) {
              String message = "Cannto build AbstractMailCommand";
              getLogger().error(message, e);
          }
          return ama;
      }
  
  
      /**
       * get Class for a command
       *
       * @param cmd the command
       * @return Class associated with cmd, or null iff cmd is not mapped to 
any class
       */
      protected Class getClassForCommand( String cmd ) {
          Class clazz = (Class)cmdMap.get( cmd );
          return clazz;
      }
      
      /**
       * test if command is mapped to a Command class
       *
       * @param cmd the command
       * @return true iff command is mapped to a Class, otherwise return false
       */
      public boolean isCommandMapped( String cmd ) {
          return cmdMap.containsKey( cmd );
      }
      
      /**
       *  configure the cmd to mail command class mapping.
       *  <p>
       *    New commands are registered here. A command name is associated with 
       *    each command class.
       *  </p>
       */
      public void configure() {
          cmdMap = new HashMap();
          cmdMap.put("cat-folder", 
MailCommandManager.MailFolderCatCommand.class);
          cmdMap.put("refresh-folder", 
MailCommandManager.MailRefreshFolderCommand.class);
          cmdMap.put("list-folder", 
MailCommandManager.MailListFolderCommand.class);
          cmdMap.put("list-folder-messages", 
MailCommandManager.MailListMessagesCommand.class);
          cmdMap.put("search-folder-messages", 
MailCommandManager.MailSearchMessagesCommand.class);
          cmdMap.put("cat-message-by-uid", 
MailCommandManager.MailCatMessageByUIDCommand.class);
          cmdMap.put("cat-message-by-id", 
MailCommandManager.MailCatMessageByIdCommand.class);
          cmdMap.put("cat-attachment-of-message-by-id", 
MailCommandManager.MailCatAttachmentMessageByIdCommand.class);
      }
  
  }
  
  
  
  
  1.1                  
xml-cocoon2/src/scratchpad/src/org/apache/cocoon/mail/MailCommandManager.java
  
  Index: MailCommandManager.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.mail;
  
  import java.util.List;
  import java.io.IOException;
  import javax.mail.FetchProfile;
  import javax.mail.Folder;
  import javax.mail.Message;
  import javax.mail.MessagingException;
  import javax.mail.Multipart;
  import javax.mail.Part;
  import javax.mail.Store;
  import javax.mail.UIDFolder;
  import javax.mail.search.FromStringTerm;
  import javax.mail.search.OrTerm;
  import javax.mail.search.SearchTerm;
  import javax.mail.search.SubjectTerm;
  import org.apache.avalon.framework.context.Context;
  import org.apache.avalon.framework.context.ContextException;
  import org.apache.avalon.framework.context.Contextualizable;
  import org.apache.avalon.framework.logger.AbstractLogEnabled;
  import org.apache.cocoon.mail.command.AbstractMailCommand;
  import org.apache.cocoon.mail.command.MailCommands;
  
  /**
   * Manage invocation of mail commands.
   *
   [EMAIL PROTECTED]     Bernhard Huber
   [EMAIL PROTECTED]    23. Oktober 2002
   [EMAIL PROTECTED]    CVS Version: $Id: MailCommandManager.java,v 1.1 
2003/01/06 21:51:20 huber Exp $
   */
  public class MailCommandManager extends AbstractLogEnabled {
  
      /**
       *  Description of the Field
       */
      public final static String DEFAULT_FOLDER_NAME = "INBOX";
  
      /**
       *  Description of the Field
       */
      public final static String DEFAULT_FOLDER_PATTERN = "%";
  
      /**
       *  Context key specifying the foldername.
       */
      public final static String CONTEXT_FOLDER_ENTRY = "folder";
      /**
       *  Description of the Field
       */
      public final static String CONTEXT_UID_ENTRY = "uid";
      /**
       *  Description of the Field
       */
      public final static String CONTEXT_ID_ENTRY = "id";
      /**
       *  Description of the Field
       */
      public final static String CONTEXT_PARTID_ENTRY = "part-id";
      /**
       *  Description of the Field
       */
      public final static String CONTEXT_FOLDER_PATTERN_ENTRY = 
"folder-pattern";
      /**
       *  Description of the Field
       */
      public final static String CONTEXT_MAX_FOLDER_LEVEL_ENTRY = 
"max-folder-level";
  
  
      /**
       *  Creates a new instance of MailHeaderList
       */
      public MailCommandManager() { }
  
  
      /**
       *  Open a javamail folder
       *
       [EMAIL PROTECTED]  f                       Description of the Parameter
       [EMAIL PROTECTED]  mode                    folder opening mode, use 
Folder.READ_WRITE, or Folder.READ_ONLY
       [EMAIL PROTECTED]  MessagingException  Description of the Exception
       */
      public static void openFolder(Folder f, int mode) throws 
MessagingException {
          if (!f.isOpen()) {
              f.open(mode);
          }
      }
  
  
      /**
       *  Close a javamail folder
       *
       [EMAIL PROTECTED]  f                       Description of the Parameter
       [EMAIL PROTECTED]  MessagingException  Description of the Exception
       */
      public static void closeFolder(Folder f) throws MessagingException {
          if (f != null && f.isOpen()) {
              // fix me : do we need expungeOnExit = true?
              f.close(false);
          }
      }
  
  
      /**
       *  Open a javamail store
       *
       [EMAIL PROTECTED]  s                       Description of the Parameter
       [EMAIL PROTECTED]  MessagingException  Description of the Exception
       */
      public static void openStore(Store s) throws MessagingException {
          if (!s.isConnected()) {
              s.connect();
          }
      }
  
  
      /**
       *  Close a javamail store
       *
       [EMAIL PROTECTED]  s                       Description of the Parameter
       [EMAIL PROTECTED]  MessagingException  Description of the Exception
       */
      public static void closeStore(Store s) throws MessagingException {
          if (s != null && s.isConnected()) {
              s.close();
          }
      }
  
  
      /**
       *  Description of the Method
       *
       [EMAIL PROTECTED]  aList  Description of the Parameter
       [EMAIL PROTECTED]        Description of the Return Value
       */
      public List execute(List aList) {
          MailCommands folderCommands = new MailCommands(aList);
          try {
              folderCommands.execute();
          } catch (MessagingException me) {
              // log exception
              getLogger().error("Cannot execute", me);
          }
          return folderCommands.getResults();
      }
  
  
      /**
       *  Description of the Method
       *
       [EMAIL PROTECTED]  amfa  Description of the Parameter
       [EMAIL PROTECTED]       Description of the Return Value
       */
      public List execute(AbstractMailCommand amfa) {
          try {
              amfa.execute();
          } catch (MessagingException me) {
              // log exception
              getLogger().error("Cannot execute", me);
          }
          return amfa.getResults();
      }
  
  
      /**
       *  Retrieve folder, and put it as command result.
       *
       [EMAIL PROTECTED]     Bernhard Huber
       [EMAIL PROTECTED]    23. Oktober 2002
       [EMAIL PROTECTED]    CVS Version: $Id: MailCommandManager.java,v 1.1 
2003/01/06 21:51:20 huber Exp $
       */
      public static class MailFolderCatCommand extends AbstractMailCommand 
implements Contextualizable {
  
          private Folder aFolder;
  
  
          /**
           *Constructor for the MailFolderCommand object
           */
          public MailFolderCatCommand() { }
  
  
          /**
           *  Description of the Method
           *
           [EMAIL PROTECTED]  ctx                   Description of the Parameter
           [EMAIL PROTECTED]  ContextException  Description of the Exception
           */
          public void contextualize(Context ctx) throws ContextException {
              MailContext mctx = (MailContext) ctx;
              this.aFolder = mctx.getTheFolder(CONTEXT_FOLDER_ENTRY);
          }
  
  
          /**
           *  Description of the Method
           *
           [EMAIL PROTECTED]  MessagingException  Description of the Exception
           */
          public void execute() throws MessagingException {
              MailCommandManager.openFolder(aFolder, Folder.READ_ONLY);
              addResult(aFolder);
          }
      }
  
  
  ////
      /**
       *  Retrieve folder, and put it as command result.
       *
       [EMAIL PROTECTED]     Bernhard Huber
       [EMAIL PROTECTED]    23. Oktober 2002
       [EMAIL PROTECTED]    CVS Version: $Id: MailCommandManager.java,v 1.1 
2003/01/06 21:51:20 huber Exp $
       */
      public static class MailRefreshFolderCommand extends AbstractMailCommand 
implements Contextualizable {
  
          private Folder aFolder;
  
  
          /**
           *Constructor for the MailFolderCommand object
           */
          public MailRefreshFolderCommand() { }
  
  
          /**
           *  Description of the Method
           *
           [EMAIL PROTECTED]  ctx                   Description of the Parameter
           [EMAIL PROTECTED]  ContextException  Description of the Exception
           */
          public void contextualize(Context ctx) throws ContextException {
              MailContext mctx = (MailContext) ctx;
              this.aFolder = mctx.getTheFolder(CONTEXT_FOLDER_ENTRY);
          }
  
  
          /**
           *  Description of the Method
           *
           [EMAIL PROTECTED]  MessagingException  Description of the Exception
           */
          public void execute() throws MessagingException {
              MailCommandManager.closeFolder(aFolder);
              MailCommandManager.openFolder(aFolder, Folder.READ_ONLY);
              addResult(aFolder);
          }
      }
  
  
      /**
       *  Retrieved headers of all messages of a folder, put
       *   retrieved messages as command result.
       *
       [EMAIL PROTECTED]     Bernhard Huber
       [EMAIL PROTECTED]    23. Oktober 2002
       [EMAIL PROTECTED]    CVS Version: $Id: MailCommandManager.java,v 1.1 
2003/01/06 21:51:20 huber Exp $
       */
      public static class MailListMessagesCommand extends AbstractMailCommand 
implements Contextualizable {
  
          private Folder aFolder;
  
  
          /**
           *Constructor for the MailAllHeadersCommand object
           */
          public MailListMessagesCommand() { }
  
  
          /**
           *  Description of the Method
           *
           [EMAIL PROTECTED]  ctx                   Description of the Parameter
           [EMAIL PROTECTED]  ContextException  Description of the Exception
           */
          public void contextualize(Context ctx) throws ContextException {
              // try to get the folder object
              MailContext mctx = (MailContext) ctx;
              this.aFolder = mctx.getTheFolder(CONTEXT_FOLDER_ENTRY);
          }
  
  
          /**
           *  Description of the Method
           *
           [EMAIL PROTECTED]  MessagingException  Description of the Exception
           */
          public void execute() throws MessagingException {
              MailCommandManager.openFolder(aFolder, Folder.READ_ONLY);
  
              // add folder, too
              addResult(aFolder);
  
              Message[] messages = aFolder.getMessages();
  
              // Use a suitable FetchProfile
              FetchProfile fp = new FetchProfile();
              fp.add(FetchProfile.Item.ENVELOPE);
              fp.add(FetchProfile.Item.FLAGS);
              fp.add("X-Mailer");
              aFolder.fetch(messages, fp);
  
              // add all messages to the result
              addResult(messages);
  
          }
      }
  
  
      /**
       *  List all subfolders of a folder, put
       *  all retrieved folders as command result.
       *
       [EMAIL PROTECTED]     Bernhard Huber
       [EMAIL PROTECTED]    23. Oktober 2002
       [EMAIL PROTECTED]    CVS Version: $Id: MailCommandManager.java,v 1.1 
2003/01/06 21:51:20 huber Exp $
       */
      public static class MailListFolderCommand extends AbstractMailCommand 
implements Contextualizable {
  
          private Folder aFolder;
          private String folderPattern = 
MailCommandManager.DEFAULT_FOLDER_PATTERN;
  
  
          /**
           *Constructor for the MailFoldersCommand object
           */
          public MailListFolderCommand() { }
  
  
          /**
           *   Gets the folderPattern attribute of the ListFolderCommand object
           *
           [EMAIL PROTECTED]    The folderPattern value
           */
          public String getFolderPattern() {
              return this.folderPattern;
          }
  
  
          /**
           *  Description of the Method
           *
           [EMAIL PROTECTED]  ctx                   Description of the Parameter
           [EMAIL PROTECTED]  ContextException  Description of the Exception
           */
          public void contextualize(Context ctx) throws ContextException {
              MailContext mctx = (MailContext) ctx;
              this.aFolder = mctx.getTheFolder(CONTEXT_FOLDER_ENTRY);
  
              try {
              String fp = (String) ctx.get("param:" + 
CONTEXT_FOLDER_PATTERN_ENTRY);
              } catch (ContextException ce) {
                  // use default folder pattern
                  this.folderPattern = 
MailCommandManager.DEFAULT_FOLDER_PATTERN;
              }
          }
  
  
          /**
           *  Description of the Method
           *
           [EMAIL PROTECTED]  MessagingException  Description of the Exception
           */
          public void execute() throws MessagingException {
              // spec say: folder list can be invoked on closed folder 
MailCommandManager.openFolder(aFolder,Folder.READ_ONLY);
              //addResult(aFolder);
              Folder[] subFolders = aFolder.list(this.folderPattern);
              getLogger().debug("Adding " + String.valueOf(subFolders.length) + 
" subFolders ");
              for (int i = 0; i < subFolders.length; i++) {
                  getLogger().debug("subFolder " + String.valueOf(i) + " name " 
+ subFolders[i].getFullName());
              }
              addResult(subFolders);
          }
      }
  
  
      /**
       *  Retrieved a message (envelope plus content) of a folder by its uid, 
put
       *   retrieved message as command result.
       *
       [EMAIL PROTECTED]     Bernhard Huber
       [EMAIL PROTECTED]    23. Oktober 2002
       [EMAIL PROTECTED]    CVS Version: $Id: MailCommandManager.java,v 1.1 
2003/01/06 21:51:20 huber Exp $
       */
      public static class MailCatMessageByUIDCommand extends 
AbstractMailCommand implements Contextualizable {
  
          private int msgUID = 1;
          private Folder aFolder;
  
  
          /**
           *Constructor for the MailMessageByUIDCommand object
           */
          public MailCatMessageByUIDCommand() { }
  
  
          /**
           *  Description of the Method
           *
           [EMAIL PROTECTED]  ctx                   Description of the Parameter
           [EMAIL PROTECTED]  ContextException  Description of the Exception
           */
          public void contextualize(Context ctx) throws ContextException {
              MailContext mctx = (MailContext) ctx;
              this.aFolder = mctx.getTheFolder(CONTEXT_FOLDER_ENTRY);
  
              Integer i = (Integer) ctx.get("param-integer:" + 
CONTEXT_UID_ENTRY);
              if (i == null) {
                  String message = "Missing mandatory context entry " + 
String.valueOf(CONTEXT_UID_ENTRY);
                  throw new ContextException(message);
              }
              this.msgUID = i.intValue();
          }
  
  
          /**
           *  Description of the Method
           *
           [EMAIL PROTECTED]  MessagingException  Description of the Exception
           */
          public void execute() throws MessagingException {
              UIDFolder uidFolder = (UIDFolder) aFolder;
              MailCommandManager.openFolder(aFolder, Folder.READ_ONLY);
              
              // add folder, too
              addResult(aFolder);
              
              Message msg = uidFolder.getMessageByUID(msgUID);
              addResult(msg);
          }
      }
  
  
      /**
       *  Retrieved a message (envelope plus content) of a folder by its id, put
       *   retrieved message as command result.
       *
       [EMAIL PROTECTED]     Bernhard Huber
       [EMAIL PROTECTED]    23. Oktober 2002
       [EMAIL PROTECTED]    CVS Version: $Id: MailCommandManager.java,v 1.1 
2003/01/06 21:51:20 huber Exp $
       */
      public static class MailCatMessageByIdCommand extends AbstractMailCommand 
implements Contextualizable {
  
          private int msgId = 1;
          private Folder aFolder;
  
  
          /**
           *Constructor for the MailMessageByIdCommand object
           */
          public MailCatMessageByIdCommand() { }
  
  
          /**
           *  Description of the Method
           *
           [EMAIL PROTECTED]  ctx                   Description of the Parameter
           [EMAIL PROTECTED]  ContextException  Description of the Exception
           */
          public void contextualize(Context ctx) throws ContextException {
              MailContext mctx = (MailContext) ctx;
              this.aFolder = mctx.getTheFolder(CONTEXT_FOLDER_ENTRY);
  
              try {
                Integer i = (Integer) ctx.get("param-integer:" + 
CONTEXT_ID_ENTRY);
                this.msgId = i.intValue();
              } catch (ContextException ce) {
                  String message = "Missing mandatory context entry " + 
String.valueOf(CONTEXT_ID_ENTRY);
                  throw new ContextException(message);
              }
          }
  
  
          /**
           *  Description of the Method
           *
           [EMAIL PROTECTED]  MessagingException  Description of the Exception
           */
          public void execute() throws MessagingException {
              MailCommandManager.openFolder(aFolder, Folder.READ_ONLY);
  
              // add folder, too
              addResult(aFolder);
  
              Message msg = aFolder.getMessage(msgId);
              addResult(msg);
          }
      }
  
  
      /**
       *  Retrieved a message part by its part id, specifying the message by 
id, put
       *   retrieved part as command result.
       *
       [EMAIL PROTECTED]     Bernhard Huber
       [EMAIL PROTECTED]    23. Oktober 2002
       [EMAIL PROTECTED]    CVS Version: $Id: MailCommandManager.java,v 1.1 
2003/01/06 21:51:20 huber Exp $
       */
      public static class MailCatAttachmentMessageByIdCommand extends 
AbstractMailCommand implements Contextualizable {
  
          private int msgId = -1;
          private int partId = -1;
          private Folder aFolder;
  
  
          /**
           *Constructor for the MailCatAttachmentMessageByIdCommand object
           */
          public MailCatAttachmentMessageByIdCommand() { }
  
  
          /**
           *  Description of the Method
           *
           [EMAIL PROTECTED]  ctx                   Description of the Parameter
           [EMAIL PROTECTED]  ContextException  Description of the Exception
           */
          public void contextualize(Context ctx) throws ContextException {
              MailContext mctx = (MailContext) ctx;
              this.aFolder = mctx.getTheFolder(CONTEXT_FOLDER_ENTRY);
  
              Integer i = (Integer) ctx.get("param-integer:" + 
CONTEXT_ID_ENTRY);
              if (i == null) {
                  String message = "Missing mandatory context entry " + 
String.valueOf(CONTEXT_ID_ENTRY);
                  throw new ContextException(message);
              }
              this.msgId = i.intValue();
  
              i = (Integer) ctx.get("param-integer:" + CONTEXT_PARTID_ENTRY);
              if (i == null) {
                  String message = "Missing mandatory context entry " + 
String.valueOf(CONTEXT_PARTID_ENTRY);
              }
              this.partId = i.intValue();
          }
  
  
          /**
           *  Description of the Method
           *
           [EMAIL PROTECTED]  MessagingException  Description of the Exception
           */
          public void execute() throws MessagingException {
              MailCommandManager.openFolder(aFolder, Folder.READ_ONLY);
              
              // add folder, too
              addResult(aFolder);
              
              // get the message 
              Message msg = aFolder.getMessage(msgId);
              
              if (msg == null) {
                  String message = "Cannot get message for id " + 
String.valueOf(msgId);
                  getLogger().warn(message);
                  return;
              }
              try {
                  Part part = null;
                  Object objRef = msg.getContent();
                  if (!(objRef instanceof Multipart)) {
                      String message = "Message of id " + String.valueOf(msgId) 
+ " is not a multipart message!";
                      getLogger().warn(message);
                      return;
                  }
                  Multipart multipart = (Multipart) objRef;
                  int numParts = multipart.getCount();
  
                  if (partId < numParts) {
                      part = multipart.getBodyPart(partId);
                  } else {
                      String message = "Invalid part id " + 
String.valueOf(this.partId) + " of message id " + String.valueOf(this.msgId);
                      getLogger().warn(message);
                  }
                  addResult(part);
              } catch (IOException ioe) {
                  String message = "Cannot get content of " +
                          "message for id " + String.valueOf(msgId);
                  throw new MessagingException(message, ioe);
              }
          }
      }
  
  
      /**
       *  Description of the Class
       *
       [EMAIL PROTECTED]     Administrator
       [EMAIL PROTECTED]    02. J�nner 2003
       [EMAIL PROTECTED]    CVS Version: $Id: MailCommandManager.java,v 1.1 
2003/01/06 21:51:20 huber Exp $
       */
      public static class MailSearchMessagesCommand extends AbstractMailCommand 
implements Contextualizable {
          private Folder aFolder;
          private SearchTerm searchTerm;
  
  
          /**
           *  Description of the Method
           *
           [EMAIL PROTECTED]  ctx                   Description of the Parameter
           [EMAIL PROTECTED]  ContextException  Description of the Exception
           */
          public void contextualize(Context ctx) throws ContextException {
              MailContext mctx = (MailContext) ctx;
              this.aFolder = mctx.getTheFolder(CONTEXT_FOLDER_ENTRY);
  
              String searchString = (String) ctx.get("param:" + "search");
              if (searchString == null) {
                  searchString = "";
              }
              searchTerm = new OrTerm(
                      new SubjectTerm(searchString),
                      new FromStringTerm(searchString));
  
              // build searchTerm from searchTermString
  
              /* proposed searchTermString syntax
                {header}:comp-op:{value} & {header}:comp-op:{value} | .....
  
                eg. subject:eq:cocoon & date::MM/DD/2002
  
                header:com-op:
                  subject:[cont|ncont]:
                  sender:[cont|ncont]:
                  body:[cont|ncont]:
                  date:[is|nis|before|after]
                  status:[is|nis]:[Read|New|Replied|Forwarded]
                  to:[cont|ncont]:
                  cc:
                  age-in-days:[is|nis|gt|lt]:
                  reply-to:[cont|ncont]:
  
              */
          }
  
  
          /**
           *  Description of the Method
           *
           [EMAIL PROTECTED]  MessagingException  Description of the Exception
           */
          public void execute() throws MessagingException {
              MailCommandManager.openFolder(aFolder, Folder.READ_ONLY);
  
              // add folder, too
              addResult(aFolder);
              
              Message[] msgs = aFolder.search(searchTerm);
              addResult(msgs);
          }
      }
  }
  
  
  
  
  1.1                  
xml-cocoon2/src/scratchpad/src/org/apache/cocoon/mail/MailCommandSelector.java
  
  Index: MailCommandSelector.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.mail;
  
  import java.util.Map;
  import org.apache.cocoon.selection.AbstractSwitchSelector;
  import org.apache.avalon.framework.parameters.Parameters;
  import org.apache.cocoon.environment.Request;
  import org.apache.cocoon.environment.ObjectModelHelper;
  import org.apache.cocoon.environment.Session;
  import org.apache.avalon.framework.context.ContextException;
  /*
  usage:
    <map:select type="mail-selector">
      <!-- optional -->
      <map:parameter name="command" value="{request-attribute:cmd}"/>
      
      <!-- get value from request.getAttribute( "cmd" ) -->
      <map:parameter name="command" value="cmd"/>
      
      <map:when test="cat-folder">
      </map:when>
      
      <map:otherwise>
      </map:otherwise>
    
      
      <map:when test="command-defined">
      <map:when test="command-undefined">
      
      <map:when test="
      
  */
  public class MailCommandSelector extends AbstractSwitchSelector {
    
    public Object getSelectorContext(Map objectModel, Parameters parameters) {
        Request request = ObjectModelHelper.getRequest(objectModel);
        // try to get the command from the request-attribute
        String cmdName = MailContext.MAIL_CURRENT_WORKING_COMMAND_ENTRY;
        String cmd = (String)request.getAttribute( cmdName );
        
        // try to get command from the request parameter
        if (cmd == null) {
            cmdName = "cmd";
            cmd = request.getParameter( cmdName );
        }
        
        // try to get command from the session attribute
        if (cmd == null) {
            Session session = request.getSession( false );
            if (session != null) {
                MailContext mailContext = (MailContext)session.getAttribute( 
MailContext.SESSION_MAIL_CONTEXT );
                if (mailContext != null) {
                    try {
                        cmd = 
(String)mailContext.get(MailContext.MAIL_CURRENT_WORKING_COMMAND_ENTRY);
                    } catch (ContextException ce) {
                        String message = "Cannot get command entry " + 
                          
String.valueOf(MailContext.MAIL_CURRENT_WORKING_COMMAND_ENTRY) + " " + 
                          "from mailContext from session";
                        getLogger().warn( message, ce );
                    }
                }
            }
        }
        MailCommandBuilder mcb = new MailCommandBuilder();
        boolean isMapped = mcb.isCommandMapped( cmd );
        if (isMapped) {
            return cmd;
        } else {
            // uup the command is invalid, we will surly be not able to map it 
to a valid
            // AbstractMailAction
            return null;
        }
    }
  
    public boolean select(String expression, Object selectorContext) {
        if (selectorContext == null) {
            return false;
        } else {
            String cmd = (String)selectorContext;
            return cmd.equals( expression );
        }
    }
  
  }
  
  
  
  
  1.1                  
xml-cocoon2/src/scratchpad/src/org/apache/cocoon/mail/MailContentHandlerDelegate.java
  
  Index: MailContentHandlerDelegate.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.mail;
  
  import java.io.IOException;
  import java.io.InputStream;
  import java.text.SimpleDateFormat;
  import java.util.Date;
  import java.util.Enumeration;
  import java.util.Locale;
  import javax.mail.Address;
  import javax.mail.Flags;
  import javax.mail.Folder;
  import javax.mail.Header;
  import javax.mail.Message;
  import javax.mail.MessagingException;
  import javax.mail.Multipart;
  import javax.mail.Part;
  import javax.mail.internet.ContentType;
  import javax.mail.internet.InternetAddress;
  import javax.mail.internet.MimeMultipart;
  import javax.mail.internet.MimePart;
  import javax.mail.internet.ParameterList;
  import javax.mail.internet.ParseException;
  import org.apache.avalon.excalibur.xml.XMLizable;
  import org.apache.avalon.framework.logger.AbstractLogEnabled;
  import org.apache.avalon.framework.logger.Logger;
  import org.xml.sax.Attributes;
  import org.xml.sax.ContentHandler;
  import org.xml.sax.SAXException;
  import org.xml.sax.helpers.AttributesImpl;
  
  /**
   * Marshal javamail objects
   * <p>
   *   Having one or more javamail objects, like Message, Folder, et al. emit 
SAX events
   * </p>
   *
   [EMAIL PROTECTED]     Bernhard Huber
   [EMAIL PROTECTED]    24. Oktober 2002
   [EMAIL PROTECTED]    CVS Version: $Id: MailContentHandlerDelegate.java,v 1.1 
2003/01/06 21:51:20 huber Exp $
   */
  
  /*
   *  Generated SAX events conforming to following folder sample xml:
   *
   *  <mail:mail xmlns:mail="http://apache.org/cocoon/mail/1.0";>
   *
   *  <mail:folder name="INBOX" full-name="INBOX" url-name="imap://[EMAIL 
PROTECTED]/INBOX"
   *  is-subscribed="yes"
   *  is-direcory="no"
   *  has-new-messages="no"
   *  total-messages="3"
   *  new-messages="0"
   *  deleted-messages="-1"
   *  unread-messages="0"
   *  >
   *  </mail:mail>
   *
   *  Generated SAX events conforming to following message sample xml:
   *
   *  <mail:mail xmlns:mail="http://apache.org/cocoon/mail/1.0";>
   *
   *  <mail:message-envelope>
   *  <mail:from email-address="[EMAIL PROTECTED]">[EMAIL PROTECTED]</mail:from>
   *  <mail:to email-address="[EMAIL PROTECTED]">[EMAIL PROTECTED]</mail:to>
   *  <mail:reply-to email-address="[EMAIL PROTECTED]">[EMAIL 
PROTECTED]</mail:reply-to>
   *  <mail:subject>TEST</mail:subject>
   *  <mail:sent-date>Thu Oct 10 14:40:43 CEST 2002</mail:sent-date>
   *  <mail:received-date>Thu Oct 10 14:43:29 CEST 2002</mail:received-date>
   *  <mail:size>4440</mail:size>
   *  <mail:message-number>1</mail:message-number> <mail:flags seen="yes"/>
   *  <mail:header name="Return-path" value="<[EMAIL PROTECTED]>"/>
   *  <mail:header name="Received" value="from x1"/>
   *  <mail:header name="Received" value="from x2"/>
   *  <mail:header name="Date" value="Thu, 10 Oct 2002 14:40:43 +0200 (CEST)"/>
   *  <mail:header name="From" value="[EMAIL PROTECTED]"/>
   *  <mail:header name="Subject" value="TEST"/>
   *  <mail:header name="To" value="[EMAIL PROTECTED]"/>
   *  <mail:header name="Message-id" value="<[EMAIL PROTECTED]>"/>
   *  <mail:header name="MIME-version" value="1.0"/>
   *  <mail:header name="Content-type" value="multipart/mixed;&#10; 
boundary="[EMAIL PROTECTED]""/>
   *  </mail:message-envelope>
   *
   *  <mail:part content-type="multipart/MIXED; &#10; boundary="[EMAIL 
PROTECTED]"">
   *  <mail:content>
   *  <mail:part content-type="TEXT/PLAIN; charset=us-ascii">
   *  <mail:content>TEST CONTENT MESSSAGE TEST.</mail:content>
   *  </mail:part>
   *  <mail:part content-type="MESSAGE/RFC822">
   *  <mail:content>
   *  <mail:part content-type="multipart/MIXED; boundary=--1f735d241edf3a1">
   *  <mail:content>
   *  <mail:part content-type="TEXT/PLAIN; charset=us-ascii">
   *  <mail:content>Test &#13;</mail:content>
   *  </mail:part>
   *  <mail:part content-type="TEXT/X-VCARD; name=xxx.vcf; 
charset=windows-1252" description="Card for <[EMAIL PROTECTED]>" 
disposition="ATTACHMENT" file-name="xxx.vcf">
   *  <mail:content>begin:vcard&#13; n:Name;Name&#13; title:Dr&#13; 
email;internet:[EMAIL PROTECTED]&#13; url:www.xxx.net&#13; fn:xXxXx&#13; 
end:vcard&#13; &#13; </mail:content>
   *  </mail:part>
   *  </mail:content>
   *  </mail:part>
   *  </mail:content>
   *  </mail:part>
   *  </mail:content>
   *  </mail:part>
   *
   *  </mail:mail>
   *
   */
  public class MailContentHandlerDelegate extends AbstractLogEnabled {
  
      /**
       *  URI of the generated XML elements
       */
      public final static String URI = "http://apache.org/cocoon/mail/1.0";;
  
      /**
       *  PREFIX of the generated XML elements
       */
      public final static String PREFIX = "mail";
  
      /**
       * Destination content handler receiving SAX events generated by
       * this class
       */
      private ContentHandler contentHandler;
  
      /**
       *  use this attributes for startElement attributes invocation, reusing
       *  attributes object for all elements
       */
      private AttributesImpl attributes = null;
  
      private SimpleDateFormat sdf;
  
      private ContentTypePreference alternativeMailCtPref = new MailCtPref();
  
  
      /**
       *  Constructor for the MailContentHandler object
       *
       [EMAIL PROTECTED]  contentHandler  Description of Parameter
       */
      public MailContentHandlerDelegate(ContentHandler contentHandler) {
          this.contentHandler = contentHandler;
      }
  
  
      /**
       *  Sets the simpleDateFormatter attribute of the 
MailContentHandlerDelegate object
       *
       [EMAIL PROTECTED]  sdf  The new simpleDateFormat value
       */
      public void setSimpleDateFormat(SimpleDateFormat sdf) {
          this.sdf = sdf;
      }
  
  
      /**
       *  Gets the simpleDateFormat attribute of the MailContentHandlerDelegate 
object
       *
       [EMAIL PROTECTED]    The simpleDateFormat value
       */
      public SimpleDateFormat getSimpleDateFormat() {
          return sdf;
      }
  
  
      /**
       *  Emit starting SAX events sequence, including SAX startDocument event
       *
       [EMAIL PROTECTED]  SAXException  thrown iff generating SAX events fails
       */
      public void startDocument() throws SAXException {
          startDocumentInternal(true);
      }
  
  
      /**
       *  Emit starting SAX events sequence, excluding SAX startDocument event
       *
       [EMAIL PROTECTED]  SAXException  thrown iff generating SAX events fails
       */
      public void startDocumentXMLizer() throws SAXException {
          startDocumentInternal(false);
      }
  
  
      /**
       *  Emit starting SAX events sequence, including SAX endDocument event
       *
       [EMAIL PROTECTED]  SAXException  thrown iff generating SAX events fails
       */
      public void endDocument() throws SAXException {
          endDocumentInternal(true);
      }
  
  
      /**
       *  Emit starting SAX events sequence, excluding SAX endDocument event
       *
       [EMAIL PROTECTED]  SAXException  thrown iff generating SAX events fails
       */
      public void endDocumentXMLizer() throws SAXException {
          endDocumentInternal(false);
      }
  
  
      /**
       *  Emit a folder  as a sequence of SAX events
       *
       [EMAIL PROTECTED]  folder  emit this folder
       */
      public void marshalFolderToSAX(Folder folder) {
          try {
              folderToSAX(this.contentHandler, folder);
          } catch (Exception e) {
              getLogger().error("Cannot generate SAX events from folder", e);
          }
      }
  
  
      /**
       *  Emit folders as a sequence of SAX events
       *
       [EMAIL PROTECTED]  folders  emit these folders
       */
      public void marshalFolderToSAX(Folder[] folders) {
          try {
              for (int i = 0; i < folders.length; i++) {
                  folderToSAX(this.contentHandler, folders[i]);
              }
          } catch (Exception e) {
              getLogger().error("Cannot generate SAX events from folders", e);
          }
      }
  
  
      /**
       *  Emit a message envelope as a sequence of SAX events
       *
       [EMAIL PROTECTED]  message  emit envelope of this message
       */
      public void marshalMessageEnvelopeToSAX(Message message) {
          try {
              messageEnvelopeToSAX(this.contentHandler, message);
          } catch (Exception e) {
              getLogger().error("Cannot generate SAX events from message 
envelope ", e);
          }
      }
  
  
      /**
       *  Emit a message envelope, and message content as a sequence of SAX 
events
       *
       [EMAIL PROTECTED]  message  emit envelope, and content of this message
       */
      public void marshalMessageToSAX(Message message) {
          try {
              messageEnvelopeToSAX(this.contentHandler, message);
              partToSAX(this.contentHandler, message, 0);
          } catch (Exception e) {
              getLogger().error("Cannot generate SAX events from message ", e);
          }
      }
  
  
      /**
       *  Emit a message content as a sequence of SAX events
       *
       [EMAIL PROTECTED]  part  Description of the Parameter
       */
      public void marshalPartToSAX(Part part) {
          try {
              partToSAX(this.contentHandler, part, 0);
          } catch (Exception e) {
              getLogger().error("Cannot generate SAX events part", e);
          }
      }
  
  
      /**
       *  Emit start document sequence
       *
       [EMAIL PROTECTED]  emitStartDocument  flag controlling invocation of SAX 
startDocument
       [EMAIL PROTECTED]  SAXException   thrown iff generating SAX events fails
       */
      protected void startDocumentInternal(boolean emitStartDocument) throws 
SAXException {
          if (emitStartDocument) {
              this.contentHandler.startDocument();
          }
          this.contentHandler.startPrefixMapping(PREFIX, URI);
  
          attributes = new AttributesImpl();
          attributes.clear();
          attributes.addAttribute("", PREFIX, "xmlns:" + PREFIX, "CDATA", URI);
          startElement("mail", attributes);
      }
  
  
      /**
       *  Emit end document sequence
       *
       [EMAIL PROTECTED]  emitEndDocument   flag controlling invocation of SAX 
endDocument
       [EMAIL PROTECTED]  SAXException  thrown iff generating SAX events fails
       */
      protected void endDocumentInternal(boolean emitEndDocument) throws 
SAXException {
          endElement("mail");
  
          this.contentHandler.endPrefixMapping(PREFIX);
          if (emitEndDocument) {
              this.contentHandler.endDocument();
          }
      }
  
  
      /**
       *  Emit folder as sequence of SAX events
       *
       [EMAIL PROTECTED]  folder                  emit this folder
       [EMAIL PROTECTED]  contentHandler          specifies sink of SAX events
       [EMAIL PROTECTED]  MessagingException  thrown iff accessing javamail 
data fails
       [EMAIL PROTECTED]  SAXException        thrown iff generating SAX events 
fails
       */
      protected void folderToSAX(ContentHandler contentHandler, Folder folder) 
throws MessagingException, SAXException {
          attributes.clear();
          addAttribute("name", folder.getName());
          addAttribute("full-name", folder.getFullName());
          addAttribute("url-name", folder.getURLName().toString());
          addAttribute("is-subscribed", folder.isSubscribed() ? "yes" : "no");
          addAttribute("is-directory", (folder.getType() & 
Folder.HOLDS_FOLDERS) != 0 ? "yes" : "no");
  
          if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {
              addAttribute("holds-messages", "yes" );
              addAttribute("has-new-messages", folder.hasNewMessages() ? "yes" 
: "no");
              addAttribute("total-messages", 
String.valueOf(folder.getMessageCount()));
              addAttribute("new-messages", 
String.valueOf(folder.getNewMessageCount()));
              addAttribute("deleted-messages", 
String.valueOf(folder.getDeletedMessageCount()));
              addAttribute("unread-messages", 
String.valueOf(folder.getUnreadMessageCount()));
          }
  
          startElement("folder", attributes);
          endElement("folder");
      }
  
  
      /**
       *  Emit message envelope as sequence of SAX events
       *
       [EMAIL PROTECTED]  message                 emit envelope of this message
       [EMAIL PROTECTED]  contentHandler          specifies sink of SAX events
       [EMAIL PROTECTED]  MessagingException  thrown iff accessing javamail 
data fails
       [EMAIL PROTECTED]  SAXException        thrown iff generating SAX events 
fails
       */
      protected void messageEnvelopeToSAX(ContentHandler contentHandler, 
Message message) throws MessagingException, SAXException {
          attributes.clear();
          startElement("message-envelope", attributes);
  
          Address[] a;
          // FROM
          if ((a = message.getFrom()) != null) {
              for (int j = 0; j < a.length; j++) {
                  emitAddress("from", a[j]);
              }
          }
  
          // TO
          if ((a = message.getRecipients(Message.RecipientType.TO)) != null) {
              for (int j = 0; j < a.length; j++) {
                  emitAddress("to", a[j]);
              }
          }
  
          // CC
          if ((a = message.getRecipients(Message.RecipientType.CC)) != null) {
              for (int j = 0; j < a.length; j++) {
                  emitAddress("cc", a[j]);
              }
          }
          // BCC
          if ((a = message.getRecipients(Message.RecipientType.BCC)) != null) {
              for (int j = 0; j < a.length; j++) {
                  emitAddress("bcc", a[j]);
              }
          }
  
          // REPLY-TO
          if ((a = message.getReplyTo()) != null) {
              for (int j = 0; j < a.length; j++) {
                  emitAddress("reply-to", a[j]);
              }
          }
  
          // SUBJECT
          attributes.clear();
          startElement("subject", attributes);
          characters(message.getSubject());
          endElement("subject");
  
          // SENT-DATE
          Date d;
          d = message.getSentDate();
          emitDate("sent-date", d);
  
          // RECEIVED-DATE
          d = message.getReceivedDate();
          emitDate("received-date", d);
  
          // SIZE
          attributes.clear();
          startElement("size", attributes);
          characters(String.valueOf(message.getSize()));
          endElement("size");
  
          // MESSAGE NUMBER
          attributes.clear();
          startElement("message-number", attributes);
          characters(String.valueOf(message.getMessageNumber()));
          endElement("message-number");
  
          // FLAGS:
          Flags flags = message.getFlags();
          Flags.Flag[] sf = flags.getSystemFlags();
          // get the system flags
  
          attributes.clear();
          for (int i = 0; i < sf.length; i++) {
              Flags.Flag flag = sf[i];
              if (flag == Flags.Flag.ANSWERED) {
                  addAttribute("answered", "yes");
              } else if (flag == Flags.Flag.DELETED) {
                  addAttribute("deleted", "yes");
              } else if (flag == Flags.Flag.DRAFT) {
                  addAttribute("draft", "yes");
              } else if (flag == Flags.Flag.FLAGGED) {
                  addAttribute("flagged", "yes");
              } else if (flag == Flags.Flag.RECENT) {
                  addAttribute("recent", "yes");
              } else if (flag == Flags.Flag.SEEN) {
                  addAttribute("seen", "yes");
              }
          }
          startElement("flags", attributes);
          endElement("flags");
  
          String[] uf = flags.getUserFlags();
          // get the user flag strings
          for (int i = 0; i < uf.length; i++) {
              attributes.clear();
              startElement("user-flags", attributes);
              characters(uf[i]);
              endElement("user-flags");
          }
  
          // X-MAILER
          //String[] hdrs = message.getHeader("X-Mailer");
          //logger.info("X-Mailer " + (hdrs != null ? hdrs[0] : "NOT 
available"));
  
          Enumeration allHeaders = message.getAllHeaders();
          if (allHeaders != null) {
              while (allHeaders.hasMoreElements()) {
                  Header header = (Header) allHeaders.nextElement();
                  attributes.clear();
                  addAttribute("name", header.getName());
                  addAttribute("value", header.getValue());
                  startElement("header", attributes);
  
                  endElement("header");
              }
          }
  
          endElement("message-envelope");
      }
  
  
      /**
       *  Emit part as sequence of SAX events
       *
       [EMAIL PROTECTED]  part                    Description of the Parameter
       [EMAIL PROTECTED]  contentHandler          specifies sink of SAX events
       [EMAIL PROTECTED]  i                       Description of the Parameter
       [EMAIL PROTECTED]  MessagingException  thrown iff accessing javamail 
data fails
       [EMAIL PROTECTED]  IOException         thrown iff accessing content fails
       [EMAIL PROTECTED]  SAXException        thrown iff generating SAX events 
fails
       */
      protected void partToSAX(ContentHandler contentHandler, Part part, int i) 
throws MessagingException, IOException, SAXException {
          attributes.clear();
          String v;
          if ((v = part.getContentType()) != null) {
              // content type as-is
              addAttribute("content-type", v);
              try {
                  ContentType ct = new ContentType(v);
                  String s;
  
                  // primary part only
                  s = ct.getPrimaryType();
                  if (s != null) {
                      addAttribute("primary-type", s.toLowerCase());
                  }
                  
                  // secondary part only
                  s = ct.getSubType();
                  if (s != null) {
                      addAttribute("secondary-type", s.toLowerCase());
                  }
  
                  // primary part '/' secondary part
                  s = ct.getBaseType();
                  if (s != null) {
                      addAttribute("base-type", s.toLowerCase());
                  }
  
                  // list of parameters : parameter-name parameter-value
                  ParameterList pl = ct.getParameterList();
                  Enumeration names = pl.getNames();
                  while (names.hasMoreElements()) {
                      String key = (String) names.nextElement();
                      String value = pl.get(key);
                      addAttribute(key, value);
                  }
              } catch (ParseException pe) {
                  String message = "Cannot parse content-type " + 
String.valueOf(v);
                  getLogger().error(message, pe);
              }
          }
  
          if (i > 0) {
              addAttribute("part-num", String.valueOf(i));
  
              if (part.getDescription() != null) {
                  addAttribute("description", part.getDescription());
              }
              if (part.getDisposition() != null) {
                  addAttribute("disposition", part.getDisposition());
                  addAttribute("disposition-inline", 
String.valueOf(part.getDisposition().equals(Part.INLINE)));
              }
              if (part.getFileName() != null) {
                  addAttribute("file-name", part.getFileName());
              }
          } else {
              boolean hasAttachments = false;
              if (part.isMimeType("multipart/*")) {
                  Multipart mp = (Multipart) part.getContent();
                  if (mp.getCount() > 1) {
                      hasAttachments = true;
                      addAttribute("num-parts", String.valueOf(mp.getCount()));
                  }
              }
              addAttribute("has-attachments", String.valueOf(hasAttachments));
          }
  
          startElement("part", attributes);
          contentToSAX(contentHandler, part);
          endElement("part");
      }
  
  
      /**
       *  Emit content of message part as sequence of SAX events
       *
       [EMAIL PROTECTED]  contentHandler          specifies sink of SAX events
       [EMAIL PROTECTED]  part                    emit this part as sequence of 
SAX events
       [EMAIL PROTECTED]  SAXException        thrown iff generating SAX events 
fails
       [EMAIL PROTECTED]  MessagingException  thrown iff accessing javamail 
data fails
       [EMAIL PROTECTED]  IOException         thrown iff accessing content fails
       */
      protected void contentToSAX(ContentHandler contentHandler, Part part) 
throws MessagingException, IOException, SAXException {
          attributes.clear();
          startElement("content", attributes);
  
          /*
           *  Using isMimeType to determine the content type avoids
           *  fetching the actual content data until we need it.
           *
           *  todo: recheck this code for all circumstances.........
           */
          if (part.getContent() instanceof String && 
(part.isMimeType("text/plain"))) {
              characters((String) part.getContent());
          } else if (part.isMimeType("multipart/alternative")) {
              MimeMultipart mp = (MimeMultipart) part.getContent();
              MimePart bestPart = null;
              int ctMax = 0;
              for (int i = 0; i < mp.getCount(); i++) {
                  MimePart p = (MimePart) mp.getBodyPart(i);
                  int ctPrefN = alternativeMailCtPref.preference(p);
                  if (ctPrefN > ctMax) {
                      ctMax = ctPrefN;
                      bestPart = p;
                  }
              }
              if (bestPart != null) {
                  partToSAX(contentHandler, bestPart, 0);
              }
          } else if (part.isMimeType("multipart/*")) {
              Multipart mp = (Multipart) part.getContent();
  
              int count = mp.getCount();
              for (int i = 0; i < count; i++) {
                  partToSAX(contentHandler, mp.getBodyPart(i), i);
              }
          } else if (part.isMimeType("message/rfc822")) {
              partToSAX(contentHandler, (Part) part.getContent(), 0);
          } else {
              /*
               *  If we actually want to see the data, and it's not a
               *  MIME type we know, fetch it and check its Java type.
              Object o = part.getContent();
              if (o instanceof String) {
                  characters((String) o);
              } else if (o instanceof InputStream) {
                  encodeInputStreamForXML((InputStream) o);
              } else {
                  // unkown type
                  InputStream is = part.getInputStream();
                  encodeInputStreamForXML(is);
              }
              */
          }
          endElement("content");
      }
  
  
      /**
       *  Helper method emitting SAX events representing an internet address
       *
       [EMAIL PROTECTED]  nodeName          emitted element node name
       [EMAIL PROTECTED]  address           emitted address data
       [EMAIL PROTECTED]  SAXException  thrown iff generating SAX events fails
       */
      protected void emitAddress(String nodeName, Address address) throws 
SAXException {
  
          attributes.clear();
  
          if (address instanceof InternetAddress) {
              InternetAddress internetAddress = (InternetAddress) address;
              String personal = internetAddress.getPersonal();
              if (personal != null) {
                  addAttribute("personal", personal);
              }
              String emailAddress = internetAddress.getAddress();
              if (emailAddress != null) {
                  addAttribute("email-address", emailAddress);
              }
          }
  
          startElement(nodeName, attributes);
          String addressAsString = address.toString();
          characters(addressAsString);
          endElement(nodeName);
      }
  
  
      /**
       *  Helper method emitting SAX events representing a date
       *
       [EMAIL PROTECTED]  nodeName          emitted element node name
       [EMAIL PROTECTED]  d                 Description of the Parameter
       [EMAIL PROTECTED]  SAXException  thrown iff generating SAX events fails
       */
      protected void emitDate(String nodeName, Date d) throws SAXException {
          attributes.clear();
          startElement(nodeName, attributes);
          if (d != null) {
              if (sdf != null) {
                  String formattedDate = sdf.format(d);
                  characters(formattedDate);
              } else {
                  characters(d.toString());
              }
          }
          endElement(nodeName);
      }
  
  
      /**
       *  Helper method emitting SAX startElement event
       *
       [EMAIL PROTECTED]  nodeName          Description of the Parameter
       [EMAIL PROTECTED]  attributes        Description of the Parameter
       [EMAIL PROTECTED]  SAXException  thrown iff generating SAX events fails
       */
      private void startElement(String nodeName, Attributes attributes) throws 
SAXException {
          this.contentHandler.startElement(URI, nodeName, PREFIX + ":" + 
nodeName, attributes);
      }
  
  
      /**
       *  Helper method emitting SAX characters event
       *
       [EMAIL PROTECTED]  s                 Description of the Parameter
       [EMAIL PROTECTED]  SAXException  thrown iff generating SAX events fails
       */
      private void characters(String s) throws SAXException {
          if (s != null) {
              // replace 0d0a by 0a
              // any better idea ?
              StringBuffer sb = new StringBuffer();
              char[] stringCharacters = s.toCharArray();
              for (int i = 0; i < stringCharacters.length; i++) {
                  if (stringCharacters[i] != 0x0d) {
                      sb.append(stringCharacters[i]);
                  }
              }
              stringCharacters = sb.toString().toCharArray();
  
              this.contentHandler.characters(stringCharacters, 0, 
stringCharacters.length);
          }
      }
  
  
      /**
       *  Helper method emitting SAX endElement event
       *
       [EMAIL PROTECTED]  nodeName          Description of the Parameter
       [EMAIL PROTECTED]  SAXException  thrown iff generating SAX events fails
       */
      private void endElement(String nodeName) throws SAXException {
          this.contentHandler.endElement(URI, nodeName, PREFIX + ":" + 
nodeName);
      }
  
  
      /**
       *  Helper method adding an attribute name-value pair
       *
       [EMAIL PROTECTED]  nodeName   The feature to be added to the Attribute 
attribute
       [EMAIL PROTECTED]  nodeValue  The feature to be added to the Attribute 
attribute
       */
      private void addAttribute(String nodeName, String nodeValue) {
          attributes.addAttribute("", nodeName, nodeName, "CDATA", nodeValue);
      }
  
  
      /**
       *  Description of the Method
       *
       [EMAIL PROTECTED]  is                Description of Parameter
       [EMAIL PROTECTED]  IOException   Description of Exception
       [EMAIL PROTECTED]  SAXException  thrown iff generating SAX events fails
       */
      private void encodeInputStreamForXML(InputStream is) throws IOException, 
SAXException {
          int contentLength = is.available();
          if (contentLength < 16) {
              contentLength = 2048;
          }
          attributes.clear();
          addAttribute("type", "hex");
          startElement("encoding", attributes);
          byte content[] = new byte[contentLength];
          int readLength;
          while ((readLength = is.read(content, 0, content.length)) != -1) {
              String strContent = encodeBytes(content, 0, readLength);
              characters(strContent);
          }
          endElement("encoding");
      }
  
  
      /**
       *  A simple byte as hex encodeing
       *
       [EMAIL PROTECTED]  bytes   Description of Parameter
       [EMAIL PROTECTED]  offset  Description of Parameter
       [EMAIL PROTECTED]  length  Description of Parameter
       [EMAIL PROTECTED]         Description of the Returned Value
       */
      private String encodeBytes(final byte[] bytes, final int offset, final 
int length) {
          StringBuffer sb = new StringBuffer();
          final String ENCODE_TABLE[] = {
                  "0", "1", "2", "3", "4", "5", "6", "7", "8",
                  "9", "a", "b", "c", "d", "e", "f"};
          final int l = offset + length;
          for (int i = offset; i < l; i++) {
              byte b = bytes[i];
              int upperNibble = ((b >> 4) & 0x0f);
              int lowerNibble = (b & 0x0f);
  
              sb.append(ENCODE_TABLE[upperNibble]);
              sb.append(ENCODE_TABLE[lowerNibble]);
              sb.append(" ");
          }
          return sb.toString();
      }
  
  
      /**
       *  XMLizable Wrapper for one or more folders, saxing folders.
       *
       [EMAIL PROTECTED]     Bernhard Huber
       [EMAIL PROTECTED]    30. Dezember 2002
       [EMAIL PROTECTED]    CVS Version: $Id: MailContentHandlerDelegate.java,v 
1.1 2003/01/06 21:51:20 huber Exp $
       */
      static class FolderXMLizer extends AbstractLogEnabled
               implements XMLizable, org.apache.cocoon.xml.XMLizable {
          //private Folder folder;
          private Folder[] folders;
  
  
          /**
           *Constructor for the FolderSAX object
           *
           [EMAIL PROTECTED]  folder  Description of the Parameter
           */
          FolderXMLizer(Folder folder) {
              this.folders = new Folder[]{folder};
          }
  
  
          /**
           *Constructor for the FolderXMLizer object
           *
           [EMAIL PROTECTED]  folders  Description of the Parameter
           */
          FolderXMLizer(Folder[] folders) {
              this.folders = folders;
          }
  
  
          /**
           *  Generate SAX events from one or more folders
           *
           [EMAIL PROTECTED]  handler           Description of the Parameter
           [EMAIL PROTECTED]  SAXException  thrown iff generating SAX events 
fails
           */
          public void toSAX(ContentHandler handler) throws SAXException {
              MailContentHandlerDelegate mailContentHandlerDelegate = new 
MailContentHandlerDelegate(handler);
              mailContentHandlerDelegate.enableLogging(getLogger());
              mailContentHandlerDelegate.startDocumentXMLizer();
              for (int i = 0; i < folders.length; i++) {
                  mailContentHandlerDelegate.marshalFolderToSAX(folders[i]);
              }
              mailContentHandlerDelegate.endDocumentXMLizer();
          }
      }
  
  
      /**
       *  XMLizable Wrapper for one or more messages, saxing envelope only of 
messages.
       *
       [EMAIL PROTECTED]     Bernhard Huber
       [EMAIL PROTECTED]    30. Dezember 2002
       [EMAIL PROTECTED]    CVS Version: $Id: MailContentHandlerDelegate.java,v 
1.1 2003/01/06 21:51:20 huber Exp $
       */
      static class MessageEnvelopeXMLizer extends AbstractLogEnabled
               implements XMLizable, org.apache.cocoon.xml.XMLizable {
          private Message[] messages;
  
          private SimpleDateFormat sdf;
  
  
          /**
           *Constructor for the MessageEnvelopeXMLizer object
           *
           [EMAIL PROTECTED]  message  Description of the Parameter
           */
          public MessageEnvelopeXMLizer(Message message) {
              this.messages = new Message[1];
              this.messages[0] = message;
          }
  
  
          /**
           *Constructor for the MessageEnvelopeXMLize object
           *
           [EMAIL PROTECTED]  messages  Description of the Parameter
           */
          public MessageEnvelopeXMLizer(Message[] messages) {
              this.messages = messages;
          }
  
  
          /**
           *  Sets the simpleDateFormat attribute of the MessageEnvelopeXMLizer 
object
           *
           [EMAIL PROTECTED]  sdf  The new simpleDateFormat value
           */
          public void setSimpleDateFormat(SimpleDateFormat sdf) {
              this.sdf = sdf;
          }
  
  
          /**
           *  Sets the simpleDateFormat attribute of the MessageEnvelopeXMLizer 
object
           *
           [EMAIL PROTECTED]  pattern  The new simpleDateFormat value
           [EMAIL PROTECTED]  country  The new simpleDateFormat value
           */
          public void setSimpleDateFormat(String pattern, String country) {
              try {
                  if (pattern != null && country != null) {
                      Locale locale = new Locale(country);
                      sdf = new SimpleDateFormat(pattern, locale);
                  } else if (pattern != null) {
                      sdf = new SimpleDateFormat(pattern);
                  } else {
                      sdf = null;
                  }
              } catch (Exception e) {
                  String message = "Cannot create SimpleDateFormatter for " +
                          "pattern " + String.valueOf(pattern) + ", and " +
                          "country " + String.valueOf(country);
                  getLogger().warn(message, e);
              }
          }
  
  
          /**
           *  Gets the simpleDateFormat attribute of the MessageEnvelopeXMLizer 
object
           *
           [EMAIL PROTECTED]  sdf  Description of the Parameter
           */
          public void getSimpleDateFormat(SimpleDateFormat sdf) {
              this.sdf = sdf;
          }
  
  
          /**
           *  Generate SAX events from one or more messages
           *
           [EMAIL PROTECTED]  handler           Description of the Parameter
           [EMAIL PROTECTED]  SAXException  thrown iff generating SAX events 
fails
           */
          public void toSAX(ContentHandler handler) throws SAXException {
              MailContentHandlerDelegate mailContentHandlerDelegate = new 
MailContentHandlerDelegate(handler);
              mailContentHandlerDelegate.enableLogging(getLogger());
              mailContentHandlerDelegate.setSimpleDateFormat(sdf);
              mailContentHandlerDelegate.startDocumentXMLizer();
  
              for (int i = 0; i < messages.length; i++) {
                  
mailContentHandlerDelegate.marshalMessageEnvelopeToSAX(messages[i]);
              }
  
              mailContentHandlerDelegate.endDocumentXMLizer();
          }
      }
  
  
      /**
       *  XMLizable Wrapper for a message, saxing a message envelope, plus 
content.
       *
       [EMAIL PROTECTED]     Bernhard Huber
       [EMAIL PROTECTED]    30. Dezember 2002
       [EMAIL PROTECTED]    CVS Version: $Id: MailContentHandlerDelegate.java,v 
1.1 2003/01/06 21:51:20 huber Exp $
       */
      static class MessageXMLizer extends AbstractLogEnabled
               implements XMLizable, org.apache.cocoon.xml.XMLizable {
          private Message message;
  
          private SimpleDateFormat sdf;
  
  
          /**
           *Constructor for the MessageXMLizer object
           *
           [EMAIL PROTECTED]  message  Description of the Parameter
           */
          public MessageXMLizer(Message message) {
              this.message = message;
          }
  
  
          /**
           *  Sets the simpleDateFormat attribute of the MessageXMLizer object
           *
           [EMAIL PROTECTED]  sdf  The new simpleDateFormat value
           */
          public void setSimpleDateFormat(SimpleDateFormat sdf) {
              this.sdf = sdf;
          }
  
  
          /**
           *  Sets the simpleDateFormat attribute of the MessageXMLizer object
           *
           [EMAIL PROTECTED]  pattern  The new simpleDateFormat value
           [EMAIL PROTECTED]  country  The new simpleDateFormat value
           */
          public void setSimpleDateFormat(String pattern, String country) {
              try {
                  if (pattern != null && country != null) {
                      Locale locale = new Locale(country);
                      sdf = new SimpleDateFormat(pattern, locale);
                  } else if (pattern != null) {
                      sdf = new SimpleDateFormat(pattern);
                  } else {
                      sdf = null;
                  }
              } catch (Exception e) {
                  String message = "Cannot create SimpleDateFormatter for " +
                          "pattern " + String.valueOf(pattern) + ", and " +
                          "country " + String.valueOf(country);
                  getLogger().warn(message, e);
              }
          }
  
  
          /**
           *  Gets the simpleDateFormat attribute of the MessageXMLizer object
           *
           [EMAIL PROTECTED]  sdf  Description of the Parameter
           */
          public void getSimpleDateFormat(SimpleDateFormat sdf) {
              this.sdf = sdf;
          }
  
  
          /**
           *  Generate SAX events from a message
           *
           [EMAIL PROTECTED]  handler           Description of the Parameter
           [EMAIL PROTECTED]  SAXException  thrown iff generating SAX events 
fails
           */
          public void toSAX(ContentHandler handler) throws SAXException {
              MailContentHandlerDelegate mailContentHandlerDelegate = new 
MailContentHandlerDelegate(handler);
              mailContentHandlerDelegate.enableLogging(getLogger());
              mailContentHandlerDelegate.setSimpleDateFormat(sdf);
              mailContentHandlerDelegate.startDocumentXMLizer();
              mailContentHandlerDelegate.marshalMessageToSAX(message);
              mailContentHandlerDelegate.endDocumentXMLizer();
          }
      }
  }
  
  
  
  
  1.1                  
xml-cocoon2/src/scratchpad/src/org/apache/cocoon/mail/MailContext.java
  
  Index: MailContext.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.mail;
  
  import java.io.IOException;
  import java.util.Iterator;
  import java.util.List;
  import java.util.Map;
  import java.util.Properties;
  import java.util.Set;
  import javax.mail.Folder;
  import javax.mail.Message;
  import javax.mail.MessagingException;
  import javax.mail.Provider;
  import javax.mail.Store;
  import javax.mail.URLName;
  //import javax.mail.Session;
  import org.apache.avalon.framework.activity.Disposable;
  import org.apache.avalon.framework.activity.Initializable;
  import org.apache.avalon.framework.component.ComponentException;
  import org.apache.avalon.framework.component.ComponentManager;
  import org.apache.avalon.framework.context.Context;
  import org.apache.avalon.framework.context.ContextException;
  import org.apache.avalon.framework.context.Contextualizable;
  import org.apache.avalon.framework.context.DefaultContext;
  import org.apache.avalon.framework.logger.LogEnabled;
  import org.apache.avalon.framework.logger.Logger;
  import org.apache.avalon.framework.parameters.Parameters;
  import org.apache.cocoon.ProcessingException;
  import org.apache.cocoon.environment.ObjectModelHelper;
  import org.apache.cocoon.environment.Request;
  import org.apache.cocoon.environment.Session;
  import org.apache.cocoon.environment.SourceResolver;
  import org.apache.cocoon.generation.ComposerGenerator;
  import org.apache.cocoon.mail.command.AbstractMailCommand;
  import org.xml.sax.SAXException;
  
  /**
   *  Encapsulation of context info of this webmail application
   *
   [EMAIL PROTECTED]     Bernhard Huber
   [EMAIL PROTECTED]    29. Dezember 2002
   [EMAIL PROTECTED]    CVS Version: $Id: MailContext.java,v 1.1 2003/01/06 
21:51:20 huber Exp $
   */
  public class MailContext extends DefaultContext implements LogEnabled {
      /**
       * attribute name of MailContext object in an application session, eg 
http-session
       */
      public final static String SESSION_MAIL_CONTEXT = "mail-context";
  
      /**
       *  Description of the Field
       */
      public final static String MAIL_SESSION_ENTRY = "mail-session";
      /**
       *  Description of the Field
       */
      public final static String MAIL_STORE_ENTRY = "mail-store";
  
      /**
       *  Description of the Field
       */
      public final static String MAIL_CURRENT_WORKING_FOLDER_ENTRY = 
"mail-current-working-folder";
      /**
       *  Description of the Field
       */
      public final static String MAIL_CURRENT_WORKING_COMMAND_ENTRY = 
"mail-current-working-command";
  
      private Request request;
      private Logger logger;
  
  
      /**
       *Constructor for the MailContext object
       *
       [EMAIL PROTECTED]  parent  Description of the Parameter
       */
      MailContext(Context parent) {
          super(parent);
      }
  
  
      /**
       *  Sets the request attribute of the MailContext object
       *
       [EMAIL PROTECTED]  request  The new request value
       */
      public void setRequest(Request request) {
          this.request = request;
      }
  
  
      /**
       *  A specialization of the plain Context get method.
       *  <p>
       *    Implementing special key prefixes
       *  </p>
       *  <ul>
       *    <li>"param:key" get key from request parameters
       *    </li>
       *    <li>"param-integer:key" get key from request parameters, casting to 
Integer
       *    </li>
       *    <li>"param-folder:key" get key from request parameters, ie 
foldername, lookup
       *      foldername using key "folder:foldername"
       *    </li>
       *    <li>key get key via plain context get method
       *    </li>
       *  </ul>
       *
       [EMAIL PROTECTED]  key                   Description of the Parameter
       [EMAIL PROTECTED]                       Description of the Return Value
       [EMAIL PROTECTED]  ContextException  Description of the Exception
       */
      public Object get(Object key) throws ContextException {
          String keyString = (String) key;
  
          final String PARAM_PREFIX_ENTRY = "param:";
          final String PARAM_INTEGER_PREFIX_ENTRY = "param-integer:";
          final String PARAM_FOLDER_PREFIX_ENTRY = "param-folder:";
  
          if (keyString.startsWith(PARAM_PREFIX_ENTRY)) {
              String paramName = 
keyString.substring(PARAM_PREFIX_ENTRY.length());
              String paramValue = getParameter(paramName);
              if (paramValue == null) {
                  String message = "No parameter " + String.valueOf(keyString) 
+ " available.";
                  throw new ContextException(message);
              }
              return paramValue;
          } else if (keyString.startsWith(PARAM_INTEGER_PREFIX_ENTRY)) {
              String paramName = 
keyString.substring(PARAM_INTEGER_PREFIX_ENTRY.length());
              try {
                  Integer paramValue = getParameterAsInteger(paramName);
                  return paramValue;
              } catch (NumberFormatException nfe) {
                  String message = "Cannot create Integer for parameter " + 
String.valueOf(keyString);
                  throw new ContextException(message, nfe);
              }
          } else if (keyString.startsWith(PARAM_FOLDER_PREFIX_ENTRY)) {
              String paramName = 
keyString.substring(PARAM_FOLDER_PREFIX_ENTRY.length());
              String folderName = getParameter(paramName);
              if (folderName == null) {
                  // no folderName is available in the parameters bag
                  // try to get the current working folder
                  try {
                      folderName = (String) 
super.get(MAIL_CURRENT_WORKING_FOLDER_ENTRY);
                  } catch (ContextException ce) {
                      // no current working folder entry available
                      String message = "No " + 
MAIL_CURRENT_WORKING_FOLDER_ENTRY + " entry available ";
                      getLogger().error(message);
                      throw new ContextException(message, ce);
                  }
              }
  
              // get folder object, folderName is okay
              Folder folder = null;
              try {
                  folder = (Folder) getFolder(folderName);
              } catch (ContextException ce) {
                  // folder is not stored yet
  
                  Store store = (Store) get(MAIL_STORE_ENTRY);
                  // get folder, eventually connect the store
                  try {
                      if (!store.isConnected()) {
                          store.connect();
                      }
                      final String DEFAULT_FOLDER_NAME = "~";
                      
                      // empty folder name is specified by empty string, or "~"
                      if (folderName.equals( DEFAULT_FOLDER_NAME) || 
folderName.length() == 0) {
                          folder = store.getDefaultFolder();
                      } else {
                        folder = store.getFolder(folderName);
                      }
  
                      // save the Folder, for later access
                      putFolder(folder);
                  } catch (MessagingException me) {
                      String message = "Cannot get folder " + 
String.valueOf(folderName);
                      throw new ContextException(message, ce);
                  }
              }
              return folder;
          } else {
              return super.get(key);
          }
      }
  
  
      /**
       *  Gets the theFolder attribute of the MailContext object
       *
       [EMAIL PROTECTED]  entry                 Description of the Parameter
       [EMAIL PROTECTED]                       The theFolder value
       [EMAIL PROTECTED]  ContextException  Description of the Exception
       */
      public Folder getTheFolder(String entry) throws ContextException {
          Folder f;
          try {
              f = (Folder) get("param-folder:" + entry);
          } catch (Exception e) {
              String message = "Cannot get Folder object for " + 
String.valueOf(entry);
              throw new ContextException(message, e);
          }
          return f;
      }
  
  
      /**
       *  Gets the folder attribute of the MailContext object
       *
       [EMAIL PROTECTED]  folderName            Description of the Parameter
       [EMAIL PROTECTED]                       The folder value
       [EMAIL PROTECTED]  ContextException  Description of the Exception
       */
      public Object getFolder(String folderName) throws ContextException {
          // canonicalize folder name
          folderName = canoncializeFoldername(folderName);
  
          final String key = "folder:" + folderName;
          getLogger().debug("Getting folder " + String.valueOf(key));
  
          Object o = super.get(key);
          getLogger().debug("Successfully getting folder " + 
String.valueOf(key) + ": " + String.valueOf(o));
          return o;
      }
  
  
      /**
       *  Remove and close Store of this MailContext, implicitly remove all 
folders, too.
       */
      public void removeStore() {
          try {
              getLogger().info("Remove store " + String.valueOf(this));
              removeAllFolders();
  
              Map map = getContextData();
              Store store = (Store) map.remove(MAIL_STORE_ENTRY);
              if (store != null) {
                  MailCommandManager.closeStore(store);
              }
          } catch (Exception e) {
              String message = "Cannot remove store";
              getLogger().error(message, e);
          }
      }
  
  
      /**
       * remove all folders in this MailContext object
       */
      public void removeAllFolders() {
          try {
              getLogger().info("Remove folders " + String.valueOf(this));
  
              Map map = getContextData();
              Set entrySet = map.entrySet();
              Iterator i = entrySet.iterator();
              while (i.hasNext()) {
                  Map.Entry me = (Map.Entry) i.next();
                  String key = (String) me.getKey();
                  if (key.startsWith("folder:")) {
                      Folder f = (Folder) me.getValue();
                      MailCommandManager.closeFolder(f);
                      i.remove();
                  }
              }
          } catch (Exception e) {
              String message = "Cannot remove all folders";
              getLogger().error(message, e);
          }
      }
  
  
      /**
       *  put a folder in this MailContext object map
       *
       [EMAIL PROTECTED]  folder                Description of the Parameter
       [EMAIL PROTECTED]  ContextException  Description of the Exception
       */
      public void putFolder(Folder folder) throws ContextException {
          String folderName = folder.getFullName();
          // canonicalize folder name
          folderName = canoncializeFoldername(folderName);
  
          final String key = "folder:" + folderName;
  
          getLogger().debug("Putting folder key: " + String.valueOf(key) +
                  " folder " + String.valueOf(folder));
  
          // close folder if folder is overwritten
          try {
              Object objRef = super.get(key);
              if (objRef != null) {
                  // close this folder as it is goint to get overwritten
                  try {
                      Folder f = (Folder) objRef;
                      MailCommandManager.closeFolder(f);
                  } catch (MessagingException me) {
                      String message = "Cannot close folder";
                      getLogger().warn(message, me);
                  }
              }
          } catch (ContextException e) {
              // ignore as we set it
          }
  
          // Shall we garbage collect folders?
  
          super.put(key, folder);
      }
  
  
      /**
       *  Description of the Method
       *
       [EMAIL PROTECTED]  folders               Description of the Parameter
       [EMAIL PROTECTED]  ContextException  Description of the Exception
       */
      public void putFolder(Folder[] folders) throws ContextException {
          for (int i = 0; i < folders.length; i++) {
              putFolder(folders[i]);
          }
      }
  
  
      /**
       *  Description of the Method
       *
       [EMAIL PROTECTED]  logger  Description of the Parameter
       */
      public void enableLogging(Logger logger) {
          this.logger = logger;
      }
  
  
  
      /**
       *  Gets the parameter attribute of the MailContext object
       *
       [EMAIL PROTECTED]  key  Description of the Parameter
       [EMAIL PROTECTED]      The parameter value
       */
      protected String getParameter(String key) {
          String value = request.getParameter(key);
          return value;
      }
  
  
      /**
       *  Gets the parameterAsInteger attribute of the MailContext object
       *
       [EMAIL PROTECTED]  key  Description of the Parameter
       [EMAIL PROTECTED]      The parameterAsInteger value
       */
      protected Integer getParameterAsInteger(String key) {
          String value = request.getParameter(key);
          Integer i = new Integer(value);
          return i;
      }
  
  
      /**
       *  Gets the logger attribute of the MailContext object
       *
       [EMAIL PROTECTED]    The logger value
       */
      protected Logger getLogger() {
          return this.logger;
      }
  
  
      /**
       *  Description of the Method
       *
       [EMAIL PROTECTED]  fn  Description of the Parameter
       [EMAIL PROTECTED]     Description of the Return Value
       */
      protected String canoncializeFoldername(String fn) {
          //
          return fn;
      }
  
  }
  
  
  
  
  1.1                  
xml-cocoon2/src/scratchpad/src/org/apache/cocoon/mail/MailContextHttpSession.java
  
  Index: MailContextHttpSession.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.mail;
  
  import javax.servlet.http.HttpSessionBindingEvent;
  import javax.servlet.http.HttpSessionBindingListener;
  import org.apache.avalon.framework.context.Context;
  
  /**
   *  An extension of MailContext.
   *  <p>
   *    It implments HttpSessionBindingListener for manging MailContext 
   *    resources in case of valueUnbound - ie. session removal.
   *  </p> 
   *
   [EMAIL PROTECTED]     Bernhard Huber
   [EMAIL PROTECTED]    02. J�nner 2003
   [EMAIL PROTECTED]    CVS Version: $Id: MailContextHttpSession.java,v 1.1 
2003/01/06 21:51:20 huber Exp $
   */
  public class MailContextHttpSession extends MailContext implements 
HttpSessionBindingListener {
  
      /**
       *Constructor for the MailContextHttpSession object
       *
       [EMAIL PROTECTED]  parent  Description of the Parameter
       */
      public MailContextHttpSession(Context parent) {
          super(parent);
      }
  
  
      /**
       * Notifies the object that it is being bound to a session and identifies 
the session.
       *
       [EMAIL PROTECTED]  event  Description of the Parameter
       */
      public void valueBound(HttpSessionBindingEvent event) {
          getLogger().info("value bound " + String.valueOf(event));
      }
  
  
      /**
       * Notifies the object that it is being unbound from a session and 
identifies the session.
       *
       [EMAIL PROTECTED]  event  Description of the Parameter
       */
      public void valueUnbound(HttpSessionBindingEvent event) {
          getLogger().info("value unbound " + String.valueOf(event));
          
          // This should not happen, removeStore of this
          this.removeStore();
      }
  }
  
  
  
  
  1.1                  
xml-cocoon2/src/scratchpad/src/org/apache/cocoon/mail/MailCtPref.java
  
  Index: MailCtPref.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.mail;
  
  import javax.mail.MessagingException;
  import javax.mail.internet.MimePart;
  
  /**
   *  A simple MimePart preference selecting algorithm
   *
   [EMAIL PROTECTED]     Bernhard Huber
   [EMAIL PROTECTED]    26. Oktober 2002
   */
  public class MailCtPref implements ContentTypePreference {
  
      /**
       *  Yield preference
       *
       [EMAIL PROTECTED]  part  Examine the content of this part
       [EMAIL PROTECTED]       preference, a higher preference value signals 
higher preference,
       *  eg. a part evaluating preference 10, signals preference over
       *    a part evaluating preference of 5
       */
      public int preference(MimePart part) {
          try {
              if (part.isMimeType("text/html")) {
                  return 5;
              }
              if (part.isMimeType("text/*")) {
                  return 10;
              }
              if (part.isMimeType("text")) {
                  return 9;
              }
              return 0;
          } catch (MessagingException messagingexception) {
              return 0;
          }
      }
  }
  
  
  
  
  1.1                  
xml-cocoon2/src/scratchpad/src/org/apache/cocoon/mail/MailGenerator.java
  
  Index: MailGenerator.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.mail;
  
  import java.io.IOException;
  import java.util.Iterator;
  import java.util.List;
  import java.util.Map;
  import java.util.Properties;
  import javax.mail.Folder;
  import javax.mail.Message;
  import javax.mail.MessagingException;
  import javax.mail.Provider;
  import javax.mail.Store;
  import javax.mail.URLName;
  import javax.servlet.http.HttpSessionBindingEvent;
  import javax.servlet.http.HttpSessionBindingListener;
  //import javax.mail.Session;
  import org.apache.avalon.framework.activity.Disposable;
  import org.apache.avalon.framework.activity.Initializable;
  import org.apache.avalon.framework.component.ComponentException;
  import org.apache.avalon.framework.component.ComponentManager;
  import org.apache.avalon.framework.context.Context;
  import org.apache.avalon.framework.context.ContextException;
  import org.apache.avalon.framework.context.Contextualizable;
  import org.apache.avalon.framework.context.DefaultContext;
  import org.apache.avalon.framework.logger.LogEnabled;
  import org.apache.avalon.framework.logger.Logger;
  import org.apache.avalon.framework.parameters.Parameters;
  import org.apache.cocoon.ProcessingException;
  import org.apache.cocoon.environment.ObjectModelHelper;
  import org.apache.cocoon.environment.Request;
  import org.apache.cocoon.environment.Session;
  import org.apache.cocoon.environment.SourceResolver;
  import org.apache.cocoon.generation.ComposerGenerator;
  import org.apache.cocoon.mail.command.AbstractMailCommand;
  import org.xml.sax.SAXException;
  
  /**
   * Generates an XML representation of a java mail objects
   *
   [EMAIL PROTECTED]     <a href="mailto:Bernhard Huber">Bernhard Huber</a>
   [EMAIL PROTECTED]    27. Dezember 2002
   [EMAIL PROTECTED]    CVS $Id: MailGenerator.java,v 1.1 2003/01/06 21:51:20 
huber Exp $
   [EMAIL PROTECTED] Use MailAction instead, MailGenerator is not maintained.
   */
  public class MailGenerator extends ComposerGenerator {
  
      //private MailContext mailContext;
  
  
      /**
       * Setup generator for generation SAX events from javamail objects
       * <p>
       *   Do the following tasks
       * </p>
       * <ul>
       *   <li>Put objectModel parameters having prefix 
<code>javax.mail.Session.props:</code>
       *     into javax.mail.Session properties, stripping the prefix of its 
name.
       *   </li>
       *   <li>Get optional request parameter <code>mail-userid</code>, and
       *     <code>mail-password</code>.
       *   </li>
       *   <li>Get the template URLName from objectModel parameter 
<code>store-urlname</code>.
       *     Expand this template replacing ''mail-userid'', and 
''mail-passwd''.
       *   </li>
       *   <li>Check, and create an http-session, putting session attribute
       *     named <code>mail-context</code>, storing javamail session, 
javamail store,
       *     and javamail folders.
       *   </li>
       * </ul>
       *
       [EMAIL PROTECTED]  resolver                 Description of the Parameter
       [EMAIL PROTECTED]  objectModel              Description of the Parameter
       [EMAIL PROTECTED]  src                      Description of the Parameter
       [EMAIL PROTECTED]  par                      Description of the Parameter
       [EMAIL PROTECTED]  ProcessingException  Description of the Exception
       [EMAIL PROTECTED]  SAXException         Description of the Exception
       [EMAIL PROTECTED]  IOException          Description of the Exception
       */
      public void setup(SourceResolver resolver, Map objectModel, String src, 
Parameters par)
               throws ProcessingException, SAXException, IOException {
          super.setup(resolver, objectModel, src, par);
  
          Properties sessionProperties = new Properties();
  
          // build session properties
          String[] allParameterNames = par.getNames();
          for (int i = 0; i < allParameterNames.length; i++) {
              String parameterName = allParameterNames[i];
              final String PARAMETER_NAME_PREFIX = "javax.mail.Session.props:";
              if (parameterName.startsWith(PARAMETER_NAME_PREFIX)) {
                  String sessionPropName = 
parameterName.substring(PARAMETER_NAME_PREFIX.length());
                  String sessionPropValue = par.getParameter(parameterName, 
null);
                  if (sessionPropValue != null) {
                      getLogger().debug("Add session property " +
                              String.valueOf(sessionPropName) + ": " +
                              String.valueOf(sessionPropValue));
                      sessionProperties.put(sessionPropName, sessionPropValue);
                  }
              }
          }
  
          Request request = ObjectModelHelper.getRequest(objectModel);
  
          String folderName = request.getParameter( "folder" );
          String userid = request.getParameter("mail-userid");
          String password = request.getParameter("mail-password");
          Session session = request.getSession(true);
  
          // session attribute handling
          MailContext mailContext = (MailContext) 
session.getAttribute("mail-context");
          if (mailContext == null) {
              // no context is yet available
              mailContext = new MailContext(null);
              mailContext.enableLogging(getLogger());
              session.setAttribute("mail-context", mailContext);
          }
  
          // sitemap parameter handling
          // imap://{userid}:[EMAIL PROTECTED]:port/
          String storeURLNameTemplate = par.getParameter("store-urlname", null);
          String storeURLNameExpanded = null;
          if (storeURLNameTemplate != null) {
              storeURLNameExpanded = getURLNameExpanded(storeURLNameTemplate, 
userid, password);
              getLogger().warn("Use store URLName " + 
String.valueOf(storeURLNameExpanded));
          }
  
          javax.mail.Session mailSession = null;
          Store mailStore = null;
          // assert mailSession is available
          try {
              try {
                  mailSession = (javax.mail.Session) 
mailContext.get(MailContext.MAIL_SESSION_ENTRY);
              } catch (ContextException ce) {
  
                  mailSession = 
javax.mail.Session.getDefaultInstance(sessionProperties, null);
                  checkProviders(mailSession);
  
                  mailContext.put(MailContext.MAIL_SESSION_ENTRY, mailSession);
              }
          } catch (Exception e) {
              String message = "Cannot create mail session";
              getLogger().error(message, e);
              throw new ProcessingException(message, e);
          }
  
          // assert mailStore is available
          try {
              try {
                  mailStore = (Store) 
mailContext.get(MailContext.MAIL_STORE_ENTRY);
              } catch (ContextException ce) {
                  URLName urlNameExpanded = new URLName(storeURLNameExpanded);
                  getLogger().info("get store using URLName " + 
String.valueOf(urlNameExpanded));
                  mailStore = mailSession.getStore(urlNameExpanded);
                  mailStore.connect();
                  mailContext.put(MailContext.MAIL_STORE_ENTRY, mailStore);
              }
          } catch (Exception e) {
              String message = "Cannot get store, and connect " + 
String.valueOf(storeURLNameExpanded);
              getLogger().error(message, e);
              throw new ProcessingException(message, e);
          }
  
          if (folderName != null) {
              // make folderName the current working folder (a la cwd)
              mailContext.put(MailContext.MAIL_CURRENT_WORKING_FOLDER_ENTRY, 
folderName );
          }
          
          // mailSession and mailStore are available
          mailContext.setRequest(request);
      }
  
      /**
       *   Generate SAX events from javamail objects
       *
       [EMAIL PROTECTED]  IOException          Description of Exception
       [EMAIL PROTECTED]  SAXException         Description of Exception
       [EMAIL PROTECTED]  ProcessingException  Description of Exception
       */
      public void generate() throws IOException, SAXException, 
ProcessingException {
          //
          Request request = ObjectModelHelper.getRequest(objectModel);
          Session session = request.getSession(false);
          if (session == null) {
              String message = "Missing http-session"; 
              throw new ProcessingException( message );
          }
  
          MailContext mailContext = (MailContext) 
session.getAttribute("mail-context");
          
  
          // build javamail objects
          List javaMailResult = retrieveJavaMailObjects(mailContext);
          Iterator javaMailResultIterator;
  
          // iterate over javamail objects
          // generating SAX events from java mail objects
          javaMailResultIterator = javaMailResult.iterator();
          generateSAXFromJavaMailObject(javaMailResultIterator);
  
          // put javamail objects into request attribute map
          javaMailResultIterator = javaMailResult.iterator();
          //Request request = ObjectModelHelper.getRequest(objectModel);
          putXMLizerToRequestAttribute(request, javaMailResultIterator);
      }
  
  
      /**
       * Recycle the generator
       */
      public void recycle() {
          super.recycle();
  
          /*
          try {
              if (mailContext != null) {
                  Store mailStore = (Store) 
mailContext.get(MailContext.MAIL_STORE_ENTRY);
                  if (mailStore != null) {
                      mailStore.close();
                  }
              }
          } catch (Exception e) {
              String message = "Cannot close mail store";
              getLogger().error(message, e);
          }
          // close all folders, too?
  
          mailContext = null;
          */
      }
  
      /**
       *  Gets the uRLNameExpanded attribute of the MailGenerator object
       *
       [EMAIL PROTECTED]  storeURLNameTemplate  Description of the Parameter
       [EMAIL PROTECTED]  userid                Description of the Parameter
       [EMAIL PROTECTED]  password              Description of the Parameter
       [EMAIL PROTECTED]                       The uRLNameExpanded value
       */
      protected String getURLNameExpanded(String storeURLNameTemplate, String 
userid, String password) {
          StringBuffer sb = new StringBuffer(storeURLNameTemplate);
  
          int indexOf;
          String template;
          template = "''mail-userid''";
          indexOf = sb.indexOf(template);
          if (indexOf != -1) {
              sb.replace(indexOf, indexOf + template.length(), userid);
          }
          template = "''mail-passwd''";
          indexOf = sb.indexOf(template);
          if (indexOf != -1) {
              sb.replace(indexOf, indexOf + template.length(), password);
          }
          String storeURLNameExpanded = sb.toString();
          return storeURLNameExpanded;
      }
  
  
      /**
       *  Check that the provider need is available
       *
       [EMAIL PROTECTED]  session  The javamail Session used for checking its 
providers.
       */
      protected void checkProviders(javax.mail.Session session) {
          Provider[] providers = session.getProviders();
          // just log the available providers
          for (int i = 0; i < providers.length; i++) {
              getLogger().info("mail provider " + providers[i]);
          }
      }
  
  
      /**
       *   Retrieve javamail objects
       *
       [EMAIL PROTECTED]                          List of retrieved javamail 
objects
       [EMAIL PROTECTED]  ProcessingException  thrown iff retrieval fails
       */
      protected List retrieveJavaMailObjects(MailContext mailContext) throws 
ProcessingException {
  
          List result = null;
          try {
  
              // do we have a MailCommandManager ?
              MailCommandManager mam = new MailCommandManager();
              mam.enableLogging(getLogger());
  
              // prepare the command(s)
              MailCommandBuilder mab = new MailCommandBuilder();
              mab.enableLogging(getLogger());
              AbstractMailCommand ama = 
mab.buildAbstractMailCommand(mailContext);
  
              // execute the command(s)
              result = mam.execute(ama);
  
              return result;
          } catch (Exception e) {
              String message = "Cannot retrieve javamail objects";
              getLogger().error(message, e);
              throw new ProcessingException(message, e);
          }
      }
  
  
      /**
       *   Generate SAX events from javamail objects
       *
       [EMAIL PROTECTED]  resultIterator           Description of the Parameter
       [EMAIL PROTECTED]  SAXException         Description of Exception
       [EMAIL PROTECTED]  ProcessingException  Description of Exception
       */
      protected void generateSAXFromJavaMailObject(Iterator resultIterator) 
throws SAXException, ProcessingException {
          if (resultIterator != null) {
              // marshal java mail objects
              MailContentHandlerDelegate mailContentHandlerDelegate = new 
MailContentHandlerDelegate(this.contentHandler);
              mailContentHandlerDelegate.enableLogging(getLogger());
              // Start the document and set the namespace.
              mailContentHandlerDelegate.startDocument();
              while (resultIterator.hasNext()) {
                  Object objRef = resultIterator.next();
  
                  if (objRef instanceof Folder) {
                      mailContentHandlerDelegate.marshalFolderToSAX((Folder) 
objRef);
                  } else if (objRef instanceof Folder[]) {
                      mailContentHandlerDelegate.marshalFolderToSAX((Folder[]) 
objRef);
                  } else if (objRef instanceof Message) {
                      mailContentHandlerDelegate.marshalMessageToSAX((Message) 
objRef);
                  } else if (objRef instanceof Message[]) {
                      Message[] messages = (Message[]) objRef;
                      for (int i = 0; i < messages.length; i++) {
                          
mailContentHandlerDelegate.marshalMessageEnvelopeToSAX(messages[i]);
                      }
                  } else {
                      getLogger().warn("Cannot generate SAX events from 
instanceof " + objRef.getClass().getName());
                  }
              }
              // End the document.
              mailContentHandlerDelegate.endDocument();
  
          }
      }
  
  
      /**
       *  Put javamail objects into request attribute map
       *
       [EMAIL PROTECTED]  request         holding the destination attribute map
       [EMAIL PROTECTED]  resultIterator  Iterator of
       */
      protected void putXMLizerToRequestAttribute(Request request, Iterator 
resultIterator) {
          if (resultIterator != null) {
              // marshal java mail objects
              Logger logger = getLogger();
              while (resultIterator.hasNext()) {
                  Object objRef = resultIterator.next();
  
                  if (objRef instanceof Folder) {
                      MailContentHandlerDelegate.FolderXMLizer fx = new 
MailContentHandlerDelegate.FolderXMLizer((Folder) objRef);
                      fx.enableLogging(logger);
                      request.setAttribute("folder", fx);
                  } else if (objRef instanceof Folder[]) {
                      Folder[] folders = (Folder[]) objRef;
                      MailContentHandlerDelegate.FolderXMLizer[] fxs = new 
MailContentHandlerDelegate.FolderXMLizer[folders.length];
                      for (int i = 0; i < folders.length; i++) {
                          fxs[i] = new 
MailContentHandlerDelegate.FolderXMLizer(folders[i]);
                          fxs[i].enableLogging(logger);
                      }
                      // trust that array of XMLizable is handled
                      request.setAttribute("folder", fxs);
                  } else if (objRef instanceof Message) {
                      MailContentHandlerDelegate.MessageXMLizer mx = new 
MailContentHandlerDelegate.MessageXMLizer((Message) objRef);
                      mx.enableLogging(logger);
                      request.setAttribute("message", mx);
                  } else if (objRef instanceof Message[]) {
                      Message[] messages = (Message[]) objRef;
                      MailContentHandlerDelegate.MessageXMLizer[] mxs = new 
MailContentHandlerDelegate.MessageXMLizer[messages.length];
                      for (int i = 0; i < messages.length; i++) {
                          mxs[i] = new 
MailContentHandlerDelegate.MessageXMLizer(messages[i]);
                          mxs[i].enableLogging(logger);
                      }
                      request.setAttribute("message", mxs);
                  }
              }
          }
      }
  
  }
  
  
  
  
  1.1                  
xml-cocoon2/src/scratchpad/src/org/apache/cocoon/mail/MimeMessageUtil.java
  
  Index: MimeMessageUtil.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.mail;
  
  import javax.mail.*;
  import javax.mail.internet.*;
  import java.util.*;
  import java.io.*;
  
  /**
   *  Description of the Class
   *
   [EMAIL PROTECTED]     Bernhard Huber
   [EMAIL PROTECTED]    26. Oktober 2002
   */
  public class MimeMessageUtil {
      /**
       *  Description of the Field
       */
      public final static String SENDER_NOT_AVAILABLE = "-not available-";
      /**
       *  Description of the Field
       */
      public final static String NO_SUBJECT = "-none-";
  
  
      /**
       *  Gets the sender attribute of the MimeMessageUtil class
       *
       [EMAIL PROTECTED]  msg  Description of the Parameter
       [EMAIL PROTECTED]      The sender value
       */
      public static String getSender(MimeMessage msg) {
          String sender = null;
          try {
              InternetAddress[] from = (InternetAddress[]) msg.getFrom();
              if (from != null && from.length > 0) {
                  sender = from[0].getPersonal();
                  if (sender == null) {
                      sender = from[0].getAddress();
                  }
              }
              if (sender == null) {
                  sender = SENDER_NOT_AVAILABLE;
              }
          } catch (AddressException e) {
              sender = SENDER_NOT_AVAILABLE;
          } catch (MessagingException e) {
              sender = SENDER_NOT_AVAILABLE;
          }
          if (sender == null || sender.trim().equals("")) {
              sender = SENDER_NOT_AVAILABLE;
          }
          return sender;
      }
  
  
      /**
       *  Gets the senderEmail attribute of the MimeMessageUtil class
       *
       [EMAIL PROTECTED]  msg  Description of the Parameter
       [EMAIL PROTECTED]      The senderEmail value
       */
      public static String getSenderEmail(MimeMessage msg) {
          String senderEmail = null;
          try {
              InternetAddress[] from = (InternetAddress[]) msg.getFrom();
              if (from != null && from.length > 0) {
                  senderEmail = from[0].getAddress();
              }
          } catch (AddressException e) {
              senderEmail = SENDER_NOT_AVAILABLE;
          } catch (MessagingException e) {
              senderEmail = SENDER_NOT_AVAILABLE;
          }
          if (senderEmail == null || senderEmail.trim().equals("")) {
              senderEmail = SENDER_NOT_AVAILABLE;
          }
          return senderEmail;
      }
  
  
      /**
       *  Gets the subject attribute of the MimeMessageUtil class
       *
       [EMAIL PROTECTED]  msg  Description of the Parameter
       [EMAIL PROTECTED]      The subject value
       */
      public static String getSubject(MimeMessage msg) {
          String subject = null;
          try {
              subject = msg.getSubject();
          } catch (MessagingException e) {
              subject = NO_SUBJECT;
          }
          if (subject == null || subject.trim().equals("")) {
              subject = NO_SUBJECT;
          }
          return subject;
      }
  
  
      /**
       *  Gets the date attribute of the MimeMessageUtil class
       *
       [EMAIL PROTECTED]  msg  Description of the Parameter
       [EMAIL PROTECTED]      The date value
       */
      public static Date getDate(MimeMessage msg) {
          Date date = null;
          try {
              date = msg.getReceivedDate();
          } catch (MessagingException messagingexception) {
              /*
               *  empty
               */
          }
          if (date == null) {
              try {
                  date = msg.getSentDate();
              } catch (MessagingException messagingexception) {
                  /*
                   *  empty
                   */
              }
          }
          return date;
      }
  
  
      /**
       *  Gets the iD attribute of the MimeMessageUtil class
       *
       [EMAIL PROTECTED]  msg  Description of the Parameter
       [EMAIL PROTECTED]      The iD value
       */
      public static String getID(MimeMessage msg) {
          String id = null;
          try {
              id = msg.getMessageID();
          } catch (MessagingException messagingexception) {
              /*
               *  empty
               */
          }
          return id;
      }
  
  
      /**
       *  Description of the Method
       *
       [EMAIL PROTECTED]  part    Description of the Parameter
       [EMAIL PROTECTED]  ctPref  Description of the Parameter
       [EMAIL PROTECTED]  v       Description of the Parameter
       */
      private static void flattenMessageHelper
              (MimePart part, ContentTypePreference ctPref, List l) {
          try {
              if (part.isMimeType("multipart/alternative")) {
                  MimeMultipart mp = (MimeMultipart) part.getContent();
                  MimePart bestPart = null;
                  int ctMax = 0;
                  for (int i = 0; i < mp.getCount(); i++) {
                      MimePart p = (MimePart) mp.getBodyPart(i);
                      int ctPrefN = ctPref.preference(part);
                      if (ctPrefN > ctMax) {
                          ctMax = ctPrefN;
                          bestPart = p;
                      }
                  }
                  if (bestPart != null) {
                      l.add(bestPart);
                  }
              } else if (part.isMimeType("multipart/*")) {
                  MimeMultipart mp = (MimeMultipart) part.getContent();
                  for (int i = 0; i < mp.getCount(); i++) {
                      flattenMessageHelper((MimePart) mp.getBodyPart(i),
                              ctPref, l);
                  }
              } else if (part.isMimeType("message/rfc822")) {
                  flattenMessageHelper((MimePart) part.getContent(), ctPref,
                          l);
              } else if (ctPref.preference(part) > 0) {
                  l.add(part);
              }
          } catch (MessagingException e) {
              /*
               *  empty
               */
          } catch (IOException ioexception) {
              /*
               *  empty
               */
          }
      }
  
  
      /**
       *  Description of the Method
       *
       [EMAIL PROTECTED]  message  Description of the Parameter
       [EMAIL PROTECTED]  ctPref   Description of the Parameter
       [EMAIL PROTECTED]          Description of the Return Value
       */
      public static MimePart[] flattenMessage(MimeMessage message,
              ContentTypePreference ctPref) {
          List parts = new ArrayList();
          flattenMessageHelper(message, ctPref, parts);
          return (MimePart[]) parts.toArray(new MimePart[0]);
      }
  }
  
  
  
  
  1.1                  
xml-cocoon2/src/scratchpad/src/org/apache/cocoon/mail/command/AbstractMailCommand.java
  
  Index: AbstractMailCommand.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.mail.command;
  
  import java.util.ArrayList;
  import java.util.Iterator;
  import java.util.List;
  import javax.mail.MessagingException;
  import org.apache.avalon.framework.logger.AbstractLogEnabled;
  
  /**
   *  An abstract MailCommand template
   *
   [EMAIL PROTECTED]     Bernhard Huber
   [EMAIL PROTECTED]    23. Oktober 2002
   [EMAIL PROTECTED]    CVS Version: $Id: AbstractMailCommand.java,v 1.1 
2003/01/06 21:51:21 huber Exp $
   */
  public abstract class AbstractMailCommand extends AbstractLogEnabled
           implements MailCommand {
  
      /**
       * List of result objects
       */
      private List result;
  
  
      /**
       *  Constructor for the AbstractMailCommand object
       */
      public AbstractMailCommand() {
          result = new ArrayList();
      }
  
  
      /**
       *  Gets the results attribute of the AbstractMailCommand object
       *
       [EMAIL PROTECTED]    The results value
       */
      public List getResults() {
          return result;
      }
  
  
      /**
       *  Adds a result to the Result attribute of the AbstractMailCommand 
object
       *
       [EMAIL PROTECTED]  o  The result to be added to the Result attribute
       */
      public void addResult(Object o) {
          result.add(o);
      }
  
  
      /**
       *  Adds a list of results to the Results attribute of the 
AbstractMailCommand object
       *
       [EMAIL PROTECTED]  list  The list of results to be added to the Results 
attribute
       */
      public void addResults(List list) {
          result.addAll(list);
      }
  
  
      /**
       *  Return an iterator over the results
       *
       [EMAIL PROTECTED]    result iterator
       */
      public Iterator iterator() {
          return result.iterator();
      }
  
  
      /**
       *  Execute this command
       *
       [EMAIL PROTECTED]  MessagingException  thrown if executing of this 
MailCommand fails
       */
      public abstract void execute() throws MessagingException;
  }
  
  
  
  
  
  1.1                  
xml-cocoon2/src/scratchpad/src/org/apache/cocoon/mail/command/MailCommand.java
  
  Index: MailCommand.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.mail.command;
  
  import javax.mail.MessagingException;
  
  /**
   *  This interface the basic contract of a MailCommand
   *
   * @author     Bernhard Huber
   * @created    23. Oktober 2002
   */
  public interface MailCommand {
      /**
       *  Execute this MailCommand
       *
       * @exception  MessagingException  Description of the Exception
       */
      void execute() throws MessagingException;
  }
  
  
  
  
  
  1.1                  
xml-cocoon2/src/scratchpad/src/org/apache/cocoon/mail/command/MailCommands.java
  
  Index: MailCommands.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.mail.command;
  
  import java.util.Iterator;
  import java.util.List;
  import javax.mail.MessagingException;
  
  /**
   *  Execute a list of commands.
   *
   [EMAIL PROTECTED]     Bernhard Huber
   [EMAIL PROTECTED]    23. Oktober 2002
   [EMAIL PROTECTED]    CVS Version: $Id: MailCommands.java,v 1.1 2003/01/06 
21:51:21 huber Exp $
   */
  public class MailCommands extends AbstractMailCommand {
  
      /**
       * the list of commands
       */
      private List commands;
  
  
      /**
       *  Constructor for the MailCommands object
       *
       [EMAIL PROTECTED]  commands  a list of AbstractMailCommand entries
       */
      public MailCommands(List commands) {
          this.commands = commands;
      }
  
  
      /**
       *  Execute the list of commands
       *  <p>
       *    Gather all results of all commands.
       *  </p>
       *
       [EMAIL PROTECTED]  MessagingException  Description of the Exception
       */
      public void execute() throws MessagingException {
          Iterator i = commands.iterator();
          while (i.hasNext()) {
              AbstractMailCommand command = (AbstractMailCommand) i.next();
              command.execute();
              addResults(command.getResults());
          }
      }
  }
  
  
  
  
  

----------------------------------------------------------------------
In case of troubles, e-mail:     [EMAIL PROTECTED]
To unsubscribe, e-mail:          [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to