Skip Headers

Oracle9iAS Unified Messaging Application Developer's Guide
Release 9.0.2

Part Number A95455-01
Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index

Go to previous page Go to next page

2
JAVA API Reference

This chapter describes the JAVA APIs provided for Oracle9iAS Unified Messaging.

This chapter contains the following topics:

JavaMail API

The Oracle Javamail Service Provider (OJMA) implements the standard interfaces available with the Sun Javamail API(s) version 1.2. In addition, OJMA provides integration with Oracle Text, integration with Oracle S/MIME toolkit, support for Shared Folders, and support for Server Side Rules. The Javamail APIs can be used to authenticate the user, and perform folder and message operations. OJMA is integrated with Oracle Internet Directory (OID) and provides customized methods in the OracleStore class to authenticate mail users.

See Also:

The Oracle9iAS Unified Messaging JAVA API Documentation on http://otn.oracle.com for information about the OJMA Extensions 

See Also:

The Javamail Web site for Javamail documentation 

This section provides the following examples for using the JavaMail API:

Reading a User's Messages

The following is an example of how to read all the messages for a particular user's inbox:

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import oracle.mail.ldap.ESDSConstants;
import oracle.mail.sdk.esmail.OracleAuthenticator;

public class ReadMessage
{
        static String password = null;
        static String user = null;
        static String ldapHost = null;
        static int ldapPort = -1;
        static String mbox = "INBOX";

        public static void main (String argv[]) throws Exception
        {
                for (int i = 0; i < argv.length; i++)
                {
                        if (argv[i].equals("-U"))
                                user = argv[++i];
                        else if (argv[i].equals("-P"))
                                password = argv[++i];
                        else if (argv[i].equals("-D"))
                                ldapHost = argv[++i];
                        else if (argv[i].equals("-I"))
                                ldapPort = Integer.parseInt(argv[++i]);
                        else if (argv[i].equals("--")) {
                                i++;
                                break;
                        } 
                        else if (argv[i].startsWith("-")) {
                                System.out.println(
                                "Usage: ReadMessage [-D ldapHost] [-I ldapPort] [-U user] [-P password]");
                                System.exit(1);
                        }
                        else {
                                break;
                        }
                }

              
                Properties props = System.getProperties();

                // Set system properties - it is necessary to set up these
                // properties to obtain the database connect information
                // from oid. The database connect information is available only
                // to privileged users. 
                // NOTE: The password may umadmin password may be different
                // for your installation.
                props.setProperty("oracle.mail.ldap.admin_dn","cn=umadmin,cn=emailservercontainer,cn=products,cn=oraclecontext");
                props.setProperty("oracle.mail.ldap.admin_password","umadmin");

                Session session = Session.getDefaultInstance(props,new OracleAuthenticator());
                session.setDebug(true);

                Store store = null;

                store = session.getStore("esmail");  

                if (user != null && password != null && ldapPort != 0 && ldapHost != null){
                store.connect(ldapHost, ldapPort, user, password);

                // Open the folder - after store has connected
                Folder folder = store.getDefaultFolder();       

                folder = folder.getFolder(mbox);

                if (folder == null) {
                        System.out.println("Invalid folder");
                        System.exit(1);
                }
                else {
                        System.out.println("Folder name : " + folder.getName());
                }
                
                // try to open read/write and if that fails try read-only
                try {
                   folder.open(Folder.READ_WRITE);
                } catch (MessagingException ex) {
                   folder.open(Folder.READ_ONLY);
                }

                int totalMessages = folder.getMessageCount();

                if (totalMessages == 0) {
                   System.out.println("Empty folder");
                   folder.close(false);
                   store.close();
                   System.exit(1);
                }
                else
                {
                   System.out.println("Total messages: " + totalMessages);
                        
                   Message[] msgs = folder.getMessages();
                   if (msgs != null)
                        System.out.println("ReadMessage: Number of messages: " + msgs.length);
                   int my_uid = 0;
                   for (int i = 0; i < msgs.length; i++)
                   {
                        System.out.println("----------------------------");
                        System.out.println("This is the message uid# : " + (int)msgs[i].getMessageNumber());
                        my_uid = msgs[i].getMessageNumber();

                        if (my_uid > 0)
                        {
                           System.out.println("Retrieving msg_uid : " + my_uid);
                           Message msg = folder.getMessage(my_uid);
                           System.out.println("After getMessage");
                           //String[] aHdrArray = (String[])msg.getHeader("X-Mailer");
                           //System.out.println("X-Mailer => " + aHdrArray.length);
                           //System.out.println("X-Mailer => " + aHdrArray[0]);
                           System.out.println("Sent Date: " + msg.getSentDate());
                           System.out.println("Msg Size: " + msg.getSize());
                           System.out.println("Received Date: " + msg.getReceivedDate());
                           System.out.println("Before dumpPart");
                           dumpPart(msg);
                        }
                        else
                        {
                                System.out.println("No messages returned");
                        }
                     }  //end for

                        
                }
                }

            }

            public static void dumpPart(Part p) throws Exception
            {
                if (p instanceof Message)
                   dumpEnvelope((Message)p);

                System.out.println("----------------------------");
                pr("CONTENT-TYPE: " + p.getContentType());

                if (p.isMimeType("text/plain")) {
                        pr("This is plain text");
                        pr("---------------------------");
                        System.out.println((String)p.getContent());
                } else if (p.isMimeType("multipart/*")) {
                        pr("This is a Multipart");
                        pr("---------------------------");
                        Multipart mp = (Multipart)p.getContent();
                        int count = mp.getCount();
                        for (int i = 0; i < count; i++)
                              dumpPart(mp.getBodyPart(i));
                } else if (p.isMimeType("message/rfc822")) {
                        pr("This is a Nested Message");
                        pr("---------------------------");
                        dumpPart((Part)p.getContent());
                }
                else if (p.isMimeType("image/jpeg")) {
                    pr("--------> image/jpeg");
                    Object o = p.getContent();
                    if (o instanceof InputStream) {
                       System.out.println("o.length = " + ((InputStream)o).available());
                    }
                    InputStream x = (InputStream)o;
                    // Construct the required byte array
                    System.out.println("x.length = " + x.available());
                    int i = 0;
                    byte[] bArray = new byte[x.available()];
                         
                    while ((i = (int)((InputStream)x).available()) > 0)
                    {
                        int result = (int)(((InputStream)x).read(bArray));
                        if (result == -1) break;
                    }
                    System.out.println("B ARRAY SIZE : " + bArray.length);
                    FileOutputStream f2 = new FileOutputStream("/tmp/image.jpg");
                    f2.write(bArray);
                }
                else {
                        Object o = p.getContent();
                        if (o instanceof String) {
                                pr("This is a string");
                                pr("---------------------------");
                                System.out.println((String)o);
                        } else if (o instanceof InputStream) {
                                pr("This is just an input stream");
                                pr("---------------------------");
                                InputStream is = (InputStream)o;
                                is = (InputStream)o;
                                int c;
                                while ((c = is.read()) != -1)
                                     System.out.write(c);
                        } else {
                                pr("This is an unknown type");
                                pr("---------------------------");
                                pr(o.toString());
                        }
                }

            }

            public static void dumpEnvelope(Message m) throws Exception {
                pr("This is the message envelope");
                pr("---------------------------");
                Address[] a;
                
                // FROM
                if ((a = m.getFrom()) != null) {
                        for (int j = 0; j < a.length; j++)
                                pr("FROM: " + a[j].toString());
                }

                // TO
                if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
                        for (int j = 0; j < a.length; j++)
                                pr("TO: " + a[j].toString());
                }

                // SUBJECT
                if (m.getSubject() != null)
                        pr("SUBJECT: " + m.getSubject());

                // DATE
                Date d = m.getSentDate();
                pr("SendDate: " + (d != null ? d.toString() : "UNKNOWN"));
            }

            public static void pr(String s){
                System.out.println(s);
            }
}

Creating a Shared Folder and Granting User Permissions

The following is an example of creating a shared folder and granting permissions to a user. The shared folder name and the user(grantee) are taken in as parameters in addition to the shared folder owner and the owner password.

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import oracle.mail.sdk.esmail.*;

public class SharedFolderCreate
{
        static String password = null;
        static String user = null;
        static String aSharedFolderUser = null;
        static String aSharedFolderName = null;
        static String ldapHost = null;
        static int ldapPort = -1;
        static String mbox = "INBOX";

        public static void main (String argv[]) throws Exception
        {
                for (int i = 0; i < argv.length; i++)
                {
                        if (argv[i].equals("-U"))
                                user = argv[++i];
                        else if (argv[i].equals("-P"))
                                password = argv[++i];
                        else if (argv[i].equals("-S"))
                                aSharedFolderUser = argv[++i];
                        else if (argv[i].equals("-N"))
                                aSharedFolderName = argv[++i];
                        else if (argv[i].equals("--")) {
                                i++;
                                break;
                        } 
                        else if (argv[i].startsWith("-")) {
                                System.out.println(
                                "Usage: SharedFolderCreate [-U user] [-P password] [-S sharedFolderUser] [-N sharedFolderName]");
                                System.exit(1);
                        }
                        else {
                                break;
                        }
                }

              
                // This property is used to set the default oracle home
                // in the iasv2 environment. The default ldap host and
                // ldap port information is picked up from the
                // $ORACLE_HOME/config/ias.properties config file
                // In the store.connect method, the ldapHost is set to
                // null and the ldapPort is set to -1 to make sure that
                // the default values are used. In this example, the oracle
                // home is retrieved from a system level ORACLE_HOME
                // property.
                Properties props = System.getProperties();
                String orclHome = System.getProperty("ORACLE_HOME");
                props.setProperty("oracle.mail.ldap.oracle_home",orclHome);

                Session session = Session.getDefaultInstance(props,null);
                session.setDebug(true);

                Store store = null;

                store = session.getStore("esmail");  

                if (user != null && password != null){
                   store.connect(null, -1, user, password);

                   // Open the folder - after store has connected
                   Folder folder = store.getFolder(aSharedFolderName);

                   if (!folder.exists()) {
                        System.out.println("Folder does not exist");
                        folder.create(Folder.HOLDS_MESSAGES);
                   }
                   System.out.println("Folder name : " + folder.getName());
                   System.out.println("Creating Shared Folder");
                   ((OracleFolder)folder).addACI(aSharedFolderUser, OracleACI.READACI);
                   //((OracleFolder)folder).modifyACI(aSharedFolderUser, OracleACI.READACI + OracleACI.WRITEACI);
                   System.out.println("Done Creating Shared Folder");
                 }
            }
}

Appending Simple Messages

The following is an example of how to append a simple message to a user's inbox. The message is appended to a user's INBOX.

import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;

import javax.mail.*;
import javax.mail.internet.*;

public class TestAppendMime 
{

        static String password = null;
        static String user = null;
        static String host = null;
        static String ldapHost = null;
        static int ldapPort = -1;
        static String mbox = "INBOX";

       public static void main(String[] argv) throws Exception{

           BufferedReader in =
                        new BufferedReader(new InputStreamReader(System.in));

                for (int i = 0; i < argv.length; i++)
                {
                        if (argv[i].equals("-U"))
                                user = argv[++i];
                        else if (argv[i].equals("-P"))
                                password = argv[++i];
                        else if (argv[i].equals("-D"))
                                ldapHost = argv[++i];
                        else if (argv[i].equals("-I"))
                                ldapPort = Integer.parseInt(argv[++i]);
                        else if (argv[i].equals("--")) {
                                i++;
                                break;
                        }
                        else if (argv[i].startsWith("-")) {
                                System.out.println(
                                "Usage: TestAppendMime [-D ldapHost] [-I ldapPort] [-U user] [-P password]");
                                System.exit(1);
                        }
                        else {
                                break;
                        }
                }
            Properties props = System.getProperties();

            // Set system properties - it is necessary to set up these
            // properties to obtain the database connect information
            // from oid. The database connect information is available only
            // to privileged users.
            // NOTE: The password may umadmin password may be different
            // for your installation.
            props.setProperty("oracle.mail.ldap.admin_dn","cn=umadmin,cn=emailservercontainer,cn=products,cn=oraclecontext");
            props.setProperty("oracle.mail.ldap.admin_password","umadmin");

            // Get a Session object
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(true);

     
        Store store = null;
        store = session.getStore("esmail");

        System.out.println(ldapHost + "\n" + ldapPort + "\n" + user + "\n" +
                 password);
        store.connect(ldapHost, ldapPort, user, password);

        // Get record Folder.  Create if it does not exist.
        Folder folder = store.getFolder("INBOX");
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("oracle@oracle.com"));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("testuser1@umdev.us.oracle.com", false));
        msg.setSubject("Welcome!!!");
        //collect(in, msg);
        msg.setText("Hello welcome\n");
        msg.setSentDate(new Date());

        System.out.println("Total Number of messages : " + folder.getMessageCount());

        Message[] msgs = new Message[1];
        msgs[0] = msg;
        folder.appendMessages(msgs);

        System.out.println("Total Number of messages : " + folder.getMessageCount());
        System.out.println("Mail was recorded successfully.");
   }

     public static void collect(BufferedReader in, Message msg)
                          throws MessagingException, IOException {
        String line;
        StringBuffer sb = new StringBuffer();
        while ((line = in.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }

        // If the desired charset is known, you can use
        // setText(text, charset)
        msg.setText(sb.toString());
    }
}

Basic Folder Operations

The following example demonstrates folder operations - the basic functionality of create folder, copy messages to folder, list folders, rename folders, delete msgs, list folders, delete folders is demonstrated through this script.

/
public class TestFolder
{
 static String password = null;
 static String user = null;
 static String host = null;
 static int port = -1;
 static String mbox = "INBOX";
 static String root = null;
 static boolean recursive = false;
 static String pattern = "*";
 static boolean verbose = false;
        static String namespace = null;

 public static void main (String argv[]) throws Exception
 {
  for (int i = 0; i < argv.length; i++)
  {
   if (argv[i].equals("-U"))
    user = argv[++i];
   else if (argv[i].equals("-P"))
    password = argv[++i];
   else if (argv[i].equals("-D"))
    host = argv[++i];
   else if (argv[i].equals("-I"))
    port = Integer.parseInt(argv[++i]);
   else if (argv[i].equals("--")) {
                  i++;
                  break;
              }
   else if (argv[i].startsWith("-")) {
                  System.out.println(
    "Usage: TestFolder [-D ldap_host] [-I ldap_port] [-U user] [-P password]");
                  System.exit(1);
   }
   else {
    break;
   }
  }

  Properties props = System.getProperties();
  Session session = Session.getDefaultInstance(props,null);
  session.setDebug(false);

  Store store = null;

  store = session.getStore("esmail");

  if (user != null && password != null && port != 0 && host != null){
  store.connect(host, port, user, password);

                namespace = user.substring(0, user.indexOf('@'));

  // Open the folder - after store has connected
  Folder folder = store.getDefaultFolder();


  if (folder == null) {
   System.out.println("Invalid folder");
   System.exit(1);
  }
  else {
                        /*** List folders ***************/
                        Folder[] f = folder.list(pattern);
                        for (int i = 0; i < f.length; i++)
                        {
                           System.out.println("Name: " + f[i].getName());
                           System.out.println("Full Name: " + f[i].getFullName());
                        }
                        /*** Create folder ***************/
   System.out.println("Creating folder xyz");
   Folder aFolder = store.getFolder("/" + namespace + "/xyz");

   if (!aFolder.exists()) //create
                        {
                                System.out.println("Creating folder....");
    aFolder.create(Folder.HOLDS_MESSAGES);
                        }
                        Folder aNewFolder = store.getFolder("/" + namespace + "/temp");
                        /****** Renaming Folder ***************/
                        System.out.println("Renaming Folder to temp");
                        aFolder.renameTo(aNewFolder);
                        /***** List folder again **************/
                        f = folder.list(pattern);
                        for (int i = 0; i < f.length; i++)
                        {
                           System.out.println("Name: " + f[i].getName());
                           System.out.println("Full Name: " + f[i].getFullName());
                        }
                        /***** Copy messages into folder ****/
                        Folder mbox = store.getFolder("/" + namespace + "/INBOX");
                        mbox.open(Folder.READ_WRITE);
                        Message[] msgArray = new Message[3];
                        System.out.println("********" + mbox.getMessageCount());
                        //Message[] mboxArray = new Message[mbox.getMessageCount()];
                        for (int j = 0; j < 3; j++)
                          msgArray[j] = mbox.getMessage(j+1);

                        //msgArray = mbox.getMessages(1,3);
                        mbox.copyMessages(msgArray, aFolder);
                        /***** Get message count **********/
                        System.out.println("Number of messages in folder  " +
                            aFolder.getFullName() + " is " +
                            aFolder.getMessageCount());

                        /***** delete messages in folder ****/
                        System.out.println("DELETING two MESSAGES ");
                        System.out.println("---> Number of messages in folder after delete " + aFolder.getFullName() + " is " + 
aFolder.getMessageCount());
                        aFolder.open(Folder.READ_WRITE);
                        Message aMessage = aFolder.getMessage(1);
                        Message aMessage2 = aFolder.getMessage(2);
                        aMessage.setFlag(Flags.Flag.DELETED,true);
                        aMessage2.setFlag(Flags.Flag.DELETED,true);
                        /******* expunge folder *************/
                        System.out.println("EXPUNGING");
                        aFolder.expunge();
                        aFolder.close(true);
                        System.out.println("---> Number of messages in folder after expunge " + aFolder.getFullName() + " is " + 
aFolder.getMessageCount());
                        /******* msg count of folder ********/


                        /***** List folder again **************/
                        System.out.println("***********LIST ***********");
                        f = folder.list(pattern);
                        for (int i = 0; i < f.length; i++)
                        {
                           System.out.println("Name: " + f[i].getName());
                           System.out.println("Full Name: " + f[i].getFullName());
                        }
                        /****** Delete Folder *******/
                        System.out.println("*********** DELETE ***********");
                        aFolder.delete(true);
                        /***** List folder again **************/
                        f = folder.list(pattern);
                        for (int i = 0; i < f.length; i++)
                        {
                           System.out.println("Name: " + f[i].getName());
                           System.out.println("Full Name: " + f[i].getFullName());
                        }

  }
      }
         store.close();
            }

     public static void dumpFolder(Folder folder, boolean recurse, String tab) throws Exception
     {
  System.out.println(tab + "Name:      " + folder.getName());
         System.out.println(tab + "Full Name: " + folder.getFullName());
         System.out.println(tab + "URL:       " + folder.getURLName());

         if (verbose) {
              if (!folder.isSubscribed())
                  System.out.println(tab + "Not Subscribed");

              if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {
                  if (folder.hasNewMessages())
                       System.out.println(tab + "Has New Messages");
                   System.out.println(tab + "Total Messages:  " +
                                                folder.getMessageCount());
                   System.out.println(tab + "New Messages:    " +
                                                folder.getNewMessageCount());
                   System.out.println(tab + "Unread Messages: " +
                                                folder.getUnreadMessageCount());
               }
              if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0)
                  System.out.println(tab + "Is Directory");
         }

         System.out.println();

         if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
              if (recurse) {
                  Folder[] f = folder.list();
                  for (int i = 0; i < f.length; i++)
                       dumpFolder(f[i], recurse, tab + "    ");
              }
         }
      }
}

*************************************************************************
SharedFolderRead.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;

Shared Folder and Message Fetching

The following is an example demonstrates basic shared folder and fetch message fetching functionality:

public class SharedFolderRead
{
        static String user = null;
        static String password = null;
        static String ldapHost = null;
        static int ldapPort = -1;
        static String mbox = "INBOX";
        static String pattern = "*";

        public static void main (String argv[]) throws Exception
        {
                for (int i = 0; i < argv.length; i++)
                {
                        if (argv[i].equals("-U"))
                                user = argv[++i];
                        else if (argv[i].equals("-P"))
                                password = argv[++i];
                        else if (argv[i].equals("-D"))
                                ldapHost = argv[++i];
                        else if (argv[i].equals("-I"))
                                ldapPort = Integer.parseInt(argv[++i]);
                        else if (argv[i].equals("--")) {
                                i++;
                                break;
                        } 
                        else if (argv[i].startsWith("-")) {
                                System.out.println(
                                "Usage: SharedFolderRead [-D ldap_host] [-I ldap_port] [-U user] [-P password]");
                                System.exit(1);
                        }
                        else {
                                break;
                        }
                }

                Properties props = System.getProperties();

                // Set system properties - it is necessary to set up these
                // properties to obtain the database connect information
                // from oid. The database connect information is available only
                // to privileged users.
                // NOTE: The password may umadmin password may be different
                // for your installation.
                props.setProperty("oracle.mail.ldap.admin_dn","cn=umadmin,cn=emailservercontainer,cn=products,cn=oraclecontext");
                props.setProperty("oracle.mail.ldap.admin_password","umadmin");

                Session session = Session.getDefaultInstance(props,null);
                session.setDebug(false);

                Store store = null;

                store = session.getStore("esmail");  

                if (user != null && password != null && ldapPort != 0 && ldapHost != null){
                        store.connect(ldapHost, ldapPort, user, password);

                        Folder aLocalFolder = store.getFolder(mbox);
                if (aLocalFolder == null) {
                        System.out.println("NULL FOLDER " + mbox);
                        System.exit(1);
                }
                else {
                        System.out.println("Folder Name: " + aLocalFolder.getFullName());
                }

                try {
                        aLocalFolder.open(Folder.READ_WRITE);
                } catch (MessagingException ex) {
                        aLocalFolder.open(Folder.READ_ONLY);
                }

                int totalMessages = aLocalFolder.getMessageCount();

                System.out.println("Total Number of messages in folder " +
                        aLocalFolder.getFullName() + " is " + totalMessages);

                Folder[] aSharedNSArray = store.getSharedNamespaces();

                if (aSharedNSArray == null) {
                        System.out.println("No shared namespaces");
                        System.exit(1);
                }
                else {
                        //For each namespace, list
                        System.out.println("Number of shared namespace : " + aSharedNSArray.length);

                        Folder folder = null;
                        for (int i = 0; i < aSharedNSArray.length; i++)
                        {
                           folder = aSharedNSArray[i];
                           System.out.println("Folder fullname : " + folder.getFullName());
                        }
                                Folder[] f = folder.list(pattern);
                                int aNum =0;
                                for (int j = 0; j < f.length; j++)
                                {
                                        System.out.println("Name:      " + f[j].getName());
                                        System.out.println("Full Name: " + f[j].getFullName());
                                        aNum = j;

                                try {
                                        f[aNum].open(Folder.READ_WRITE);
                                } catch (MessagingException ex) {
                                        f[aNum].open(Folder.READ_ONLY);
                                }

                         System.out.println("Shared Folder fullname : " + f[aNum].getFullName());

                         // Select and fetch messages from Shared Folder
                         int total_messages = f[aNum].getMessageCount();
                         System.out.println("Number of messages in " + f[aNum].getFullName() + " is " + f[aNum].getMessageCount());

                         if (total_messages == 0) {
                            System.out.println("Empty folder " + f[aNum].getFullName());
                            f[aNum].close(false);
                         }
                         else {
                                int my_uid = 0;
                                Message[] msgs = f[aNum].getMessages();
                                if (msgs != null)
                                        System.out.println("Number of messages : " + msgs.length);
                                for (int i = 0; i < msgs.length; i++)
                                {
                                  my_uid = msgs[i].getMessageNumber();
                                  System.out.println("MSG_NUMBER : " + my_uid);
                                  if (my_uid > 0)
                                  {
                                    System.out.println("Retrieving msg_num : " + my_uid);
                                    Message msg = f[aNum].getMessage(my_uid);
                                    dumpPart(msg);
                                   }
                                }

                               // Copy message from shared folder to local folder
                               //System.out.println("----- BEFORE COPY -------");
                               //f[aNum].copyMessages(msgs, aLocalFolder);
                               //System.out.println("----- AFTER COPY -------");
                         }
                     }
                  }
                }
                store.close();
    }

    //Fetch message part by part
    public static void dumpPart(Part p) throws Exception
    {
        if (p instanceof Message)
          //pr("Envelope out of order------------>");
          dumpEnvelope((Message)p);

        //InputStream is = p.getInputStream();
        //System.out.println("SIZE of INPUT STREAM : " + is.available());
        System.out.println("----------------------------");
        pr("CONTENT-TYPE: " + p.getContentType());

        if (p.isMimeType("text/plain")) {
            pr("This is plain text");
            pr("---------------------------");
            System.out.println((String)p.getContent());
        } else if (p.isMimeType("multipart/*")) {
            pr("This is a Multipart");
            pr("---------------------------");
            Multipart mp = (Multipart)p.getContent();
            int count = mp.getCount();
            for (int i = 0; i < count; i++)
               dumpPart(mp.getBodyPart(i));
            } else if (p.isMimeType("message/rfc822")) {
               pr("This is a Nested Message");
               pr("---------------------------");
               dumpPart((Part)p.getContent());
            }
            else {
              Object o = p.getContent();
              if (o instanceof String) {
               pr("This is a string");
               pr("---------------------------");
               System.out.println((String)o);
              } 
             else if (o instanceof InputStream) {
                  pr("This is just an input stream");
                  pr("---------------------------");
                  InputStream is = (InputStream)o;
                  //is = (InputStream)o;
                  int c;
                  while ((c = is.read()) != -1)
                     System.out.write(c);
              } else {
                  pr("This is an unknown type");
                  pr("---------------------------");
                  pr(o.toString());
              }
             }
        }       

    public static void dumpEnvelope(Message m) throws Exception {
        pr("This is the message envelope");
        pr("---------------------------");
        Address[] a;
        
        // FROM
        if ((a = m.getFrom()) != null) {
            for (int j = 0; j < a.length; j++)
                pr("FROM: " + a[j].toString());
        }

        // TO
        if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
                for (int j = 0; j < a.length; j++)
                        pr("TO: " + a[j].toString());
        }

        // SUBJECT
                pr("SUBJECT: " + m.getSubject());

        // DATE
        Date d = m.getSentDate();
        pr("SendDate: " +
                        (d != null ? d.toString() : "UNKNOWN"));
    }

    public static void pr(String s){
        System.out.println(s);
    }
    ////--------------
}

Directory Management API

The directory management API is a set of Java classes that can be used to create, access, and manage various entries, such as mail users, public distribution lists, and private address book entries (contact information and private distribution lists). The entries are stored in the LDAP directory for a given domain.

This section contains the following topics:

Directory Components

In Oracle9iAS Unified Messaging, an e-mail system can contain more than one domain. Mail users and public distribution lists exist for a particular domain. A mail user for a given domain is a valid user in that domain who can send and receive e-mail and use all of the exposed e-mail server functionality.

A public distribution lists is a mailing list that has an its own e-mail ID and contains a group of e-mail IDs or other mailing lists. When an e-mail is sent to a public distribution list, all the members of the list receive the e-mail. A valid mail user can subscribe to any public distribution list.

Private address book entries consist of private contacts and private mailing lists belonging to a particular mail user.

A private distribution list consists of private contact information, such as the contact's phone number, e-mail ID, and address. Users can use the private address book entries from the Thin Client to send and receive e-mails. These entries are also used by the Calendar application.

Authentication

Before a caller can access any of the directory components, the caller must authenticate with the LDAP directory using the oracle.mail.OESContext class. Once authenticated, the instance of oracle.mail.OESContext representing a trusted session must be passed to all of the directory APIs.

Authentication Example:

ESDSDirectoryAccess dirAccess = oesctx.getDSAccess();
dirAccess.CreateMailUser(oesctx, ...... 
where, oesctx is an instance of OESContext. 

Retrieving the MetaData and Validation

Before an entry is created in the directory, the caller needs to retrieve the metadata for that particular entry from the directory. The metadata for a particular entry consists of the mandatory and optional attributes the caller must set in order to create an entry. It also contains information about all the attributes, such as the syntax, multiplicity of the attributes, and default values for attributes (if any defaults are set in the directory.

When the caller sets the attribute value on the metadata object, validation is performed to ensure that the caller sets the value of an attribute that is present in that particular entry. In UI-based applications using the metadata, the caller can perform any input validations for the data entered.

Example:

ESDSDirectoryAccess dirAccess = oesctx.getDSAccess(); 
//This call retrieves metadata associated with a mailuser for the domain 
oracle.com 
ESDSLdapObject ldapobj = access. GetMailUserMetaData(oesctx,"oracle.com "); 
//Getting the mandatory attributes for a mailuser from the metadata 
if (ldapobj.getMandatoryAttribs() != null) { 
Enumeration enum = ldapobj.getMandatoryAttribs().elements(); 
while (enum.hasMoreElements()) { 
String attr = enum.nextElement().toString(); // Name of the attribute 
//Retrieve the metadata for this attribute 
ESDSAttribMetaData mdata = ldapobj.getMetaData(attr); 
// The multiplicity of the attribute returns "SINGLE" or "MULTIPLE" 
String mult = mdata.getMultiplicity(); 
// Returns the syntax of the string, "String", "byte", "boolean" or "int" 
String syntax = mdata.getAttributeType(); 
//Returns a vector of String values if any default has been set, else returns 
null 
Vector defaultvals = mdata.getDefaultValues(); 
} 
} 

Similarly, the ldapobj.getOptionalAttribs() method returns the list of optional attributes and in a similar manner, the optional attributes and the metadata can be retrieved. After retrieving the metadata, the user can set the value of an attribute in the following manner. When creating an entry, the attribute value can be set using the setAttributeValue method of the ESDSLdapObject class.

Example:

This example sets the value for the telephonenumber attribute.

//This sets the value to the default values provided mdata.getDefaultValues() is 
not null 
ldapobj.setAttributeValue("telephonenumber", mdata.getDefaultValues());

This example sets a new set of values for the telephonenumber attribute.


Vector newVals = new Vector(); 
newVals.add("408 7394050"); 
newVals.add("650 7394050"); 
ldapobj.setAttributeValue("telephonenumber", newVals);

While modifying an entry, the attribute value can be set using the modifyAttributeValue method of the ESDSLdapObject class. The caller needs to specify the type of modification.

The list of allowed modifications are as follows.

Example:

This example adds two new values for the telephonenumber attribute.

Vector newVals = new Vector(); 
newVals.add("408 7394050"); 
newVals.add("650 7394050"); 
ldapobj.modifyAttributeValue("telephonenumber", newVals, ESDSConstants.DS_
MODIFY_ADD);

Directory Management Code Examples

In the following examples, it is assumed that oesctx is an instance of the OESContext class that the caller obtains during login. The instance of ESDSDirectoryAccess is obtained as follows:

ESDSDirectoryAccess dirAccess = oesctx.getDSAccess(); 


Note:

To run these examples, the CLASSPATH environment variable must include jndi.jar, ldap.jar, providerutil.jar, classes12.zip, repository.jar, esldap.jar, and escommon.jar 


Mail User Examples

The following examples show how to use the mail user APIs to create, modify, look up, and delete a mail user.

/**
Retrieving Mail User Metadata and Creating a New Mail Use
**/ 
ESDSLdapObject ldapobj = dirAccess.GetMailUserMetaData(oesctx,"oracle.com "); 
//This example sets the mail id of the new user, all other attributes it sets to 
the default values. 
if (ldapobj.getMandatoryAttribs() != null) { 
Enumeration enum = ldapobj.getMandatoryAttribs().elements(); 
while (enum.hasMoreElements()) { 
String attr = enum.nextElement().toString(); 
if (attr.equalsIgnoreCase("mail")) { 
Vector vals = new Vector(); 
vals.add("newuser@oracle.com"); 
ldapobj.setAttributeValue(attr, vals); 
} 
else { 
//Set everything else same as default values 
ESDSAttribMetaData mdata = ldapobj.getMetaData(attr); 
if (mdata.getDefaultValues() != null) 
ldapobj.setAttributeValue(attr, mdata.getDefaultValues());
} 
} 
} 
//Set the default values for the optional attributes 
enum = ldapobj.getOptionalAttribs().elements(); 
while (enum.hasMoreElements()) { 
String attr = enum.nextElement().toString(); 
//Set everything else same as default values 
ESDSAttribMetaData mdata = ldapobj.getMetaData(attr); 
if (mdata.getDefaultValues() != null) 
ldapobj.setAttributeValue(attr, mdata.getDefaultValues());
} 
// Now Create The Mailuser 
dirAccess.CreateMailUser(oesctx,"cn=newuser,dc=oracle,dc=com",ldapobj); 
// Here ,"cn=newuser,dc=oracle,dc=com" is the dn of the public user
/** 
Looking Up a Mail User 
**/ 
ldapobj = dirAccess.LookupMailUser(oesctx,"newuser@oracle.com"); 
//Get the telephonenumber of this mailuser 
ESDSAttribMetaData mdata = ldapobj.getMetaData("telephonenumber"); 
Vector values = mdata.getDefaultValues(); 
/*** 
Modifying a Mail User 
**/ 
//Modifying the orclmailquota of the user 
Vector modify = new Vector(); 
modify.add ("50000000"); 
// If you don't want to use the existing ldapobj, you can use as follows 
//ldapobj = new ESDSLdapObject(ESDSConstants.DS_USER); 
ldapobj.modifyAttributeValue("orclmailquota", 
modify, 
ESDSConstants.DS_MODIFY_REPLACE);
dirAccess.ModifyMailUser(oesctx, "newuser@oracle.com",ldapobj); 
/*** 
Delete A User 
***/ 
dirAccess.DeleteMailUser(oesctx,"user1@oracle.com"); 

Distribution List Example

The following code describes how to use the distribution list APIs to create, modify, look up, resolve, and delete a distribution list.

/**
Getting DL Metadata And Creating A New DL
**/ 
ESDSLdapObject ldapobj = 
dirAccess.GetDistributionListMetaData(oesctx,"oracle.com ");
//This example sets the mail id of the new DL, all other attributes it sets to 
the default values. 
if (ldapobj.getMandatoryAttribs() != null) { 
Enumeration enum = ldapobj.getMandatoryAttribs().elements(); 
while (enum.hasMoreElements()) { 
String attr = enum.nextElement().toString(); 
if (attr.equalsIgnoreCase("mail")) { 
Vector vals = new Vector(); 
vals.add("newlist@oracle.com"); 
ldapobj.setAttributeValue(attr, vals); 
} 
else { 
//Set everything else same as default values 
ESDSAttribMetaData mdata = ldapobj.getMetaData(attr); 
if (mdata.getDefaultValues() != null) 
ldapobj.setAttributeValue(attr, mdata.getDefaultValues());
} 
} 
} 
//Set the default values for the optional attributes 
enum = ldapobj.getOptionalAttribs().elements(); 
while (enum.hasMoreElements()) { 
String attr = enum.nextElement().toString(); 
//Set everything else same as default values 
ESDSAttribMetaData mdata = ldapobj.getMetaData(attr); 
if (mdata.getDefaultValues() != null) 
ldapobj.setAttributeValue(attr, mdata.getDefaultValues());
} 
//Add some members to the Dl, if you don't want to add members then the members 
hashtable can be null. 
Hashtable members = new Hashtable(); 
/**USERS***/ 
Vector v = new Vector(); 
v.add ("htanaya@oracle.com"); 
v.add ("newuser@oracle.com"); 
members.put(ESDSConstants.DS_USER,v); 
/**OTHER DL's***/ 
v = new Vector(); 
v.add("anotherdl@dmv.gov"); 
members.put(ESDSConstants.DS_LIST,v); 
// Now Create The DL 
dirAccess.CreateDistributionList(oesctx, ldapobj, members);
/** 
Looking up a DL 
**/ 
ldapobj = dirAccess.LookupDistributionList(oesctx,"newlist@oracle.com"); 
/*** 
Modifying a DL 
**/ 
//Modifying the orclmailquota of the user 
Vector modify = new Vector(); 
modify.add ("newhost"); 
// If you don't want to use the existing ldapobj, you can use as follows 
//ldapobj = new ESDSLdapObject(ESDSConstants.DS_LIST); 
ldapobj.modifyAttributeValue("mailhost", 
modify, 
ESDSConstants.DS_MODIFY_REPLACE);
dirAccess.ModifyDistributionList(oesctx, "dl1@oracle.com",ldapobj); 
/*** 
Delete A DL 
***/ 
dirAccess.DeleteDistributionList(oesctx,"dl1@oracle.com");
/**
Resolving a DL
**/ 
//Resolving dl2@oracle.com 
Hashtable result = dirAccess.ResolveDistributionList(oesctx, "l2@oracle.com"); 
//Get the users, other dls and foreign members out of it 
Vector users = (Vector) result.get(ESDSConstants.DS_USER);
Vector lists = (Vector) result.get(ESDSConstants.DS_LIST);
Vector foreign = (Vector) result.get(ESDSConstants.DS_FOREIGN); 
/*** 
Modifying DL Members 
**/ 
//Adding two new foreign members to the list 
Vector newmembers = new Vector(); 
newmembers.add("usr@mail.com"); 
newmembers.add ("user1@netscape.net"); 
dirAccess.ModifyDistributionListMembers(oesctx, "dl1@oracle.com", 
ESDSConstants.DS_MODIFY_ADD,
ESDSConstants.DS_FOREIGN, newmembers);

Private Address Book Contact Information Examples

The following code describes how to use the private address book contact information APIs to create, modify, look up, resolve, and search contacts.

/** 
Getting Contact Info Metadata And Creating A New Contact Info 
**/ 
ESDSLdapObject ldapobj = dirAccess.GetContactInfoMetaData(oesctx); 
//This example sets the name and email id of the new contact. Other attributes 
can be set in a similar way. 
ldapobj.setAttributeValue("name","myfriend1"); 
ldapobj.setAttributeValue("orclmailemail","test@hotmail.com"); 
// Now Create The Contact 
dirAccess. CreateContactInfo(oesctx, ldapobj);
/** 
Looking up a Contact Info 
**/ 
ldapobj = dirAccess.LookupContactInfo(oesctx,"myfriend1");
/*** 
Modifying a Contact 
**/ 
//Modifying the given name of the contact 
Vector modify = new Vector(); 
modify.add ("myfriend_name"); 
ldapobj.modifyAttributeValue("givenname", 
modify, 
ESDSConstants.DS_MODIFY_ADD);
dirAccess.ModifyContactInfo(oesctx, "myfriend1",ldapobj);
/*** 
Delete A Contact Info 
***/ 
dirAccess.DeleteContactInfo(oesctx,"friend ");
/** 
Get All Contacts 
**/ 
String[] contacts = dirAccess.GetAllContacts(oesctx); 
/** 
Get All Contacts For a Given Filter 
**/ 
contacts = dirAccess.SearchContacts(oesctx,"name=t*"); 

Private Distribution List Example

The following code describes how to use the private distribution list APIs to create, modify, look up, resolve, and search contacts.

/** 
Getting Private List Metadata And Creating A New Private List 
**/ 
ESDSLdapObject ldapobj = dirAccess.GetPrivateListMetaData(oesctx); 
//This example sets the name and email id of the new contact. Other attributes 
can be set in a similar way. 
ldapobj.setAttributeValue("name","myfriends"); 
ldapobj.setAttributeValue("orclmailemail","test@hotmail.com"); 
ldapobj.setAttributeValue("orclmailemail","test2@hotmail.com"); 
// Now Create The Contact 
dirAccess.CreatePrivateList(oesctx, ldapobj);
/** 
Looking up Private List 
**/ 
ldapobj = dirAccess.LookupPrivateList(oesctx,"myfriends");
/*** 
Modifying a private list 
**/ 
//Modifying the given name of the contact 
Vector modify = new Vector(); 
modify.add ("myfriend_name"); 
ldapobj.modifyAttributeValue("givenname", 
modify, 
ESDSConstants.DS_MODIFY_ADD);
dirAccess.ModifyContactInfo(oesctx, "myfriends_new",ldapobj); 
/*** 
Delete A Private List 
***/ 
dirAccess.DeletePrivateList(oesctx,"friends ");
/** 
Get All Private Lists 
**/ 
String[] lists= dirAccess.GetAllPrivateLists((oesctx); 
/** 
Get All Lists For a Given Filter 
**/ 
lists = dirAccess.SearchPrivateLists(oesctx,"name=t*"); 
/** 
Private list resolution 
**/ 
Vector resolved = dirAccess.ResolvePrivateList(oesctx, "friends" , 
"orclmailemail"); 
// This call resolves the given entry to the attribute "orclmailemail". It 
resolved the other private dl's and contacts also to this type. 

Rule Management API

The rule management API is a set of Java classes that can be used to create, access and manage server side rules. Rules are represented as Java objects and can be saved persistently in the LDAP directory as an attribute of a user.

This section contains the following topics:

What Are Server Side Rules?

A mail rule is a potential action that, when a certain event happens and a certain condition is satisfied, is taken upon an e-mail message on behalf of the owner of the rule. Rules can be created and stored persistently on the mail server.

The following is an example of a rule, expressed in English:

If an e-mail message arrives in my inbox and its subject contains the phrase "Get paid to surf," then delete the message.

In this example:

Each event represents a change of state on a particular message during its lifecycle in the mail server. In the above example, the event changes the state of the message from To be delivered to Delivered.

Conditions are similar to Boolean expressions, in which relational and logical operations test message attributes. In the example, the subject is the mail attribute to be tested, and the conditional expression is a relational operation that tests whether the attribute contains "Get paid to surf."

Optionally, multiple conditions can be combined using logical operators such as And and Or to form compound conditions. Additionally, a condition can be an external function call that returns a Boolean value.

Actions are operations that can act upon a message, such as the deletion of the message. In addition, an action can be any external procedure that is callable in PL/SQL from within the mail server.

Rule Components

Rules are owned by either individual users or a group of users collectively. The top-level entity owning the rules can therefore be either a mail user, a domain, or an entire e-mail system, which can contain more than one domain. The top-level entities are referred to as accounts.

For every account, one can have rules defined under a set of events, such as when new mail is delivered or when the message is read. Each event is associated with a rule list, and an account can have several rule lists, with at most one per event. For any event, a rule list can contain a list of rules that are executed sequentially when the event occurs.

A rule is defined by a condition and a list of actions. A rule with no condition is said to be unconditional, therefore the actions are always carried out.

Conditions can be simple and complex. For example, a condition that compares an attribute with a literal value using the relational operator "contains" is a simple condition. A complex condition can combine several sub-conditions. A condition can be also be a user-defined procedure, referred to as an external condition. There is also a special kind of condition, called an InSection condition, which performs a content-based search on a message.

When a rule's conditions are met, actions are taken. Actions are defined by the rule's commands, such as "move message to a folder" or "forward message to a recipient," and associated parameters, such as the name of the folder to which the message is moved or the address of the recipient to whom the message is forwarded. Once all the rules for a user are constructed in Java objects, the RuleParser object can be used to save it.

Authentication

Before a caller can access a user's rules, it must be authorized. The caller must authenticate with the LDAP directory using the oracle.mail.OESContext class. Once authenticated, the instance of the oracle.mail.OESContext class representing a trusted session must be passed into the RuleParser rule management class using the setAuthContext() method.

Example:

     RuleParser parser = new RuleParser(); 
     parser.setAuthContext(oesctx);

Validation

Before a rule is created on the server, the content of the rule is validated, preventing illegal rules from being executed at runtime. You can disable validation using the RuleParser.setValidation() method, which is useful if you want to temporarily save an incomplete rule. A non-validated rule can be saved persistently, but cannot be run during runtime.

Validation is disabled as follows:

parser.setValidation(false);

Rule Visibility, Activeness, and Group Affiliation

A rule has several attributes that are classified as follows:

Visibility

A rule can be visible or invisible. An invisible rule functions as a normal rule, except that it is not shown to the user. The actual implementation of hiding a rule is left to the caller. The API is able to retrieve both visible and invisible rules.

Visibility is set using the setVisible() RuleType class method.

Activeness

A rule can be active or inactive. An inactive rule exists on the server but is not executed at runtime.

Activeness is set using the setActive() RuleType class method.

Group Affiliation

A rule can belong to a group. All rules belonging to the same group can be retrieved, activated, and disabled together in one call.

Group affiliation is set using the setGroup() RuleType class method.

RuleType Example:

RuleType rule_t = new RuleType(); 
rule_t.setVisible("no"); 
rule_t.setActive("no"); 
rule_t.setGroup("group1");

External Condition

An external condition is a PL/SQL function that takes the following format:

function <func_name> (p_folderid in integer, 
p_msguid in integer, 
p_msgid in integer) return integer; 

Given the current folder ID, the current message's UID, and the current message ID, the function should return a number that indicates whether the condition is met. If the return value is 0, the server regards it as a positive condition match, and if the return value is non-zero, it is regarded as a failed condition match. If a rule uses an external condition, the condition function must be manually loaded to the database server where the user resides before the condition can take effect.

To set a condition to be an external condition, use the ConditionType class method addProcCall().

External Condition Example:

ConditionType cond_t = new ConditionType(); 
cond_t.addProcCall("ext_func_name");

External Action

An external action is a PL/SQL procedure that takes the following format:

procedure <proc_name>(p_event in number, 
p_userid in number, 
p_folder in varchar2, 
p_msguid in number, 
p_msgid in numner, 
p_param1 in varchar2, 
p_param2 in varchar2, 
p_status out number); 
The event ID parameter takes the following possible values: 
es_rule.c_copy 
es_rule.c_deliver 
es_rule.c_expunge 
es_rule.c_flagchange 

The procedure also takes the user ID, current folder name in its full path, the current message UID and ID, and two user-defined parameters set at rule creation time. After the procedure is completed, it should put a execution result value in the status parameter. A zero value in status indicates a normal execution, and a positive status indicates an abnormal execution.

To set an external action in rules, use the Action Type class addCommand() method, then call addParameter() three times, with the first added parameter being the procedure name, and the second and third parameters being the user-defined parameters p_param1 and p_param2 above.

External Action Example:

ActionType action_t = new ActionType(); 
action_t.addCommand("call"); 
action_t.addParameter("ext_proc_name"); 
action_t.addParameter("param1"); 
action_t.addParameter("param2");

Message Templates

Some rules require an action to generate a new message as a reply or a notification. The reply or notification can be stored in the rule content as templates containing substitutable parameters denoted by a parameter name enclosed by two percent (%) signs.

For example, an auto-reply template can be "Your e-mail regarding %rfc822subject% sent on %rfc822date% has been received." When the rule engine generates the reply message, the variables %rfc822subject% and %rfc822date% are replaced by the real subject and date sent information obtained from the incoming message. The set of supported substitutable parameters is the same as the set of supported message attributes.

See Also:

The Javadoc for Unified Messaging for information on the AttributeType class on ***OTN.  

Message template text is used as parameter values for rule actions such as Notify, Reply, Replyall, and Forward.

Message Template Example:

ActionType action_t = new ActionType(); 
action_t.addCommand("notify"); 
action_t.addParameter("jdoe@acme.com"); 
action_t.addParameter("Message Alert"); 
action_t.addParameter("You have received email from %rfc822from% regarding
%rfc822subject%");

Auto-Reply Effective Duration

To prevent auto-reply messages from flooding user inboxes, there is a concept of effective duration for a specific reply action. The duration is specified as a number of days. If an auto-reply is sent to a particular address using a particular message template, the same reply is not sent to the same user again for the period of the effective duration, starting from the time when the first reply is sent. The value is required in rule actions Reply and Replyall.

Effective Duration Example:

ActionType action_t = new ActionType(); 
action_t.addCommand("reply"); 
action_t.addParameter("7"); 
action_t.addParameter("Message received"); 
action_t.addParameter("Your email regarding %rfc822subject% sent on %rfc822date% 
has been received.");

XML Representation

Rule data can be serialized, or converted into plain text format using XML. It can then be easily transported between applications or stored off line. In fact, the rule API internally uses XML as the format to store in the LDAP directory. To flatten rule Java objects into XML text, use the print() method from the Account class.

XML Example:

XMLOutputStream out = new XMLOutputStream(System.out); 
account.print(out); 
out.writeNewLine(); 
out.flush();

The following code demonstrates using the API to compose a simple rule:

 
import oracle.xml.classgen.InvalidContentException;
import oracle.xml.parser.v2.XMLOutputStream;
import java.util.*;
import java.io.*;
import oracle.mail.*;
import oracle.mail.sdk.rule.*;
import oracle.mail.sdk.ldap.*;
public class Demo {
 
    public static main (String args[]) throws Exception {
        // login to LDAP using Directory APIs
        OESContext appCtx = new OESContext();
        OESLoginContext appLogin =
            appCtx.createDSLoginContext(DirectoryConstants.DS_CALLERTYPE_APP);
        appLogin.authenticate(null, "/your/local/oracle/home");
        // authenticate as a rule owner
        OESContext clientCtx = new OESContext();
        OESLoginContext clientLoginCtx =
            clientCtx.createDSLoginContext(ESDSConstants.DS_CALLERTYPE_MAILUSER);
        clientLoginCtx.authenticate("testuser1@oracle.com", null, appLogin);
        // set authentication context in RuleParser
        parser = new RuleParser();
        parser.setAuthContext(clientCtx);
        // first create the top level user account type object
        AccountType acnt_t = new AccountType();
        // set ownerType, either system, domain or user (default)
        acnt_t.setOwnerType("user");
        // for system rules, this is the installation name in LDAP,
        // such as "install1", for domain rules this is the domain
        // name, such as "oracle.com", for user rules this is the
        // fully qualified username, such as testuser1@oracle.com
        acnt_t.setQualifiedName("testuser1@oracle.com");
        // create a rulelist type object, set the event
        RuleListType rlist_t = new RuleListType();
        rlist_t.setEvent("deliver");
        // create a rule type object
        RuleType rule_t = new RuleType();
        rule_t.setVisible("yes"); // this is the default
        rule_t.setActive("yes"); // this is the default
        rule_t.setDescription("a new rule");
        rule_t.setGroup("group1");
        // create a condition type object
        ConditionType cond_t = new ConditionType();
        cond_t.setJunction("and"); // this is the default
        cond_t.setNegation("no"); // this is the default
        // create a simple attribute:
        cond_t.addAttribute("rfc822subject");
        // or create an attribute object with parameters:
        //
        // AttributeType attr_t = new AttributeType("xheader");
        // attr_t.setParam("X-Priority"); // this is optional
        // cond_t.addAttribute(attr_t);
        // create a simple operator:
        cond_t.addOperator("contains");
        cond_t.addOperand("Hello");
        // create another condition with an external call
        ConditionType cond_t2 = new ConditionType();
        cond_t2.addProcCall("extproc");
        // create a third condition with sectional match
        ConditionType cond_t3 = new ConditionType();
        // create an "InSection" object searching for word "Oracle" in
        // message body
        InSectionType sect_t = new InSectionType("Oracle");
        sect_t.setTag("body");
        cond_t3.addInSection(sect_t);
        // create a negation of disjunction of above three conditions
        ConditionType cond_t4 = new ConditionType();
        cond_t4.setJunction("or");
        cond_t4.setNegation("yes");
        cond_t4.addCondition(cond_t);
        cond_t4.addCondition(cond_t2);
        cond_t4.addCondition(cond_t3);
        // add the condition object to the rule type object
        rule_t.addCondition(cond_t4);
        // create an action type object
        ActionType action_t = new ActionType();
        action_t.addCommand("pass");
        // add the action to the rule object
        rule_t.addAction(action_t);
        // create a second action object and add it in the rule type
        ActionType action2_t = new ActionType();
        action2_t.addCommand("discard");
        rule_t.addAction(action2_t);
 
        // add the rule object in the rulelist type object
        rlist_t.addRule(rule_t);
        // add the rulelist object in the account type object
        acnt_t.addRulelist(rlist_t);
        // create an account object on based the type object
        Account acnt = new Account(acnt_t);
        parser.setValidation(true); // default
        parser.setRuleObjects(acnt);
    }
}

Go to previous page Go to next page
Oracle
Copyright © 2002 Oracle Corporation.

All Rights Reserved.
Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index