Writing Java to build applications using IBM Lotus Domino...

32
Writing Java to build applications using IBM Lotus Domino Designer Oscar I. Hernandez IBM Software Group Staff Software Engineer, Lotus Notes/Domino Austin, TX August 2009 © Copyright International Business Machines Corporation 2009. All rights reserved. Summary: The objective of the article is to help the traditional LotusScript® developer, who typically has no hard-core development background, move to Java TM . With little or no existing Java knowledge, this article will help you get started on developing Java applications in IBM® Lotus® Domino®. Table of Contents 1 Introduction.................................................................................................................. 2 2 Java language.............................................................................................................. 2 2.2 Line by line explanation........................................................................................ 3 2.3 Java language basics........................................................................................... 4 2.4 Differences between LotusScript and the Java language .................................. 10 3 Examples................................................................................................................... 10 3.1 Example 1: Sending an email ............................................................................. 10 3.2 Example 2: Cycling through a Notes view........................................................... 16 3.3 Example 3: Generate a report with mail database information ........................... 21 4 Other essentials......................................................................................................... 30 5 Conclusion................................................................................................................. 31 6 Resources.................................................................................................................. 31 7 About the author ........................................................................................................ 31 1

Transcript of Writing Java to build applications using IBM Lotus Domino...

Page 1: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

Writing Java to build applications using IBM LotusDomino Designer

Oscar I. HernandezIBM Software GroupStaff Software Engineer, Lotus Notes/DominoAustin, TX

August 2009

© Copyright International Business Machines Corporation 2009. All rights reserved.

Summary: The objective of the article is to help the traditional LotusScript® developer, whotypically has no hard-core development background, move to JavaTM. With little or no existingJava knowledge, this article will help you get started on developing Java applications in IBM®Lotus® Domino®.

Table of Contents1 Introduction .................................................................................................................. 2 2 Java language .............................................................................................................. 2

2.2 Line by line explanation ........................................................................................ 3 2.3 Java language basics ........................................................................................... 4 2.4 Differences between LotusScript and the Java language .................................. 10

3 Examples ................................................................................................................... 10 3.1 Example 1: Sending an email ............................................................................. 10 3.2 Example 2: Cycling through a Notes view ........................................................... 16 3.3 Example 3: Generate a report with mail database information ........................... 21

4 Other essentials ......................................................................................................... 30 5 Conclusion ................................................................................................................. 31 6 Resources .................................................................................................................. 31 7 About the author ........................................................................................................ 31

1

Page 2: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

1 IntroductionFor IBM Lotus Notes application developers, LotusScript and the LotusScript classes areinvaluable when designing Notes applications. The LotusScript API allows you to interactprogrammatically with databases, documents, and even with design elements. As Java hascontinued to emerge as a mainstream programming language, more and more Notesapplication developers are making the move to Java.

This article is intended for LotusScript developers who want to start programming with Java inIBM Lotus Domino. It is assumed that the reader is an experienced LotusScript programmer.

This document consists of three main sections: Java Language, Examples, and Otheressentials. Java programmers may feel comfortable enough to jump into the Examplessection, while beginners should review the Java Language section first.

2 Java languageReleased in 1995, Java is an object-oriented programming language that was created toaddress the need for platform independence. This was accomplished by compiling the Javasource code into bytecodes, which could then be interpreted by any Java Virtual Machine(JVM) on any platform.

Hence, as long there was a JVM implemented for the desired platform, it could run any Javaapplication. For more information, visit The History of Java Technology.

Java's syntax is similar to C, and its object-oriented implementation is similar to C++, making itan easy-to-learn language for C/C++ programmers. LotusScript developers, however, will findthe Java syntax quite different from LotusScript.

Since this article focuses on using Java in Lotus Domino, the examples presented will be in thecontext of Lotus Domino.

Let’s begin with the classic "Hello World" example. When you create a new Java agent inDomino Designer, you received the template code on the left-hand side of table 1. The codeon the right-hand side has been modified to accommodate the "Hello World" example.

2

Page 3: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

Table 1. Hello World exampleTemplate Java Agent Code Hello World Java Agent Code

import lotus.domino.*;

public class JavaAgent extends AgentBase {

public void NotesMain() {

try { Session session = getSession(); AgentContext agentContext =session.getAgentContext();

// (Your code goes here)

} catch(Exception e) { e.printStackTrace(); } }}

import lotus.domino.*;

public class JavaAgent extends AgentBase {

public void NotesMain() {

try { Session session = getSession(); AgentContext agentContext =session.getAgentContext();

// (Your code goes here) System.out.println("Hello World!");

} catch(Exception e) { e.printStackTrace(); } }}

2.2 Line by line explanationLet's examine the code, line by line:

import lotus.domino.*;Java uses the import statement to include other Java classes. In this case, all the lotus.dominoclasses are available to the agent code. Java classes are usually contained within JAR files.There are several methods for making JAR files available to an agent. Refer to the “Usingexternal JAR files with Java agents”paragraph in Section 4 of this paper for information on JARfiles.

public class JavaAgent extends AgentBase {Java is an object-oriented programming language. This line demonstrates that, when youcreate a Java agent, it creates a JavaAgent class, which will be the main class where you willwrite your Java code.

You may also notice that the JavaAgent class extends the AgentBase class. Since Java isobject-oriented, extending the AgentBase class gives us an entry point into the agent, whichbrings us to the next line.

public void NotesMain() {The NotesMain method is the entry point to the agent. Here we override the AgentBasemethod definition with our own.

try {In Java, error handling is handled through try and catch blocks. Methods that throw exceptionsin Java must be surrounded by a try block, and every try block must have a corresponding

3

Page 4: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

catch block. The try and catch blocks are required in the "Hello World" example because thegetAgentContext method throws a NotesException. To see which Domino methods throw anexception, refer to their method signature in the Domino Designer Help file.

Session session = getSession();The getSession method from the AgentBase class allows us to create a session object. TheJava Session class is similar to the LotusScript NotesSession class.

AgentContext agentContext = session.getAgentContext();The AgentContext class lets you get a handle to the current database (using itsgetCurrentDatabase method). In LotusScript, this additional class is not required to get ahandle to the current database.

// (Your code goes here)The thing to note with this line is that a single line comment begins with "//". For multiple linecomments we use "/*" at the beginning and end with "*/" (similar to C++).

System.out.println("Hello World!");This is the Java method used to print to the console. To open the Java console in Notes, selectTools > Show Java Debug Console, from the menu. The System.out.println method is similarto the LotusScript Print method.

} catch(Exception e) {This is the corresponding catch statement for the try above.

e.printStackTrace();In the catch block, you can opt to handle the exception as you wish; in this case, we are simplyprinting out the stack trace.

2.3 Java language basicsJava provides eight primitive types: byte, short, int, long, char, float, double, and Boolean.Table 2 describes each type and indicates the LotusScript equivalent (if any).

Table 2. Primitive types and LotusScript equivalentsJava Primitive Type Java Description LotusScript Equivalent

byte 8-bit signed two's complementinteger (-128 to 127)

Byte Similar: 8-bitDifference: unsigned (0 to 255)

short 16-bit signed two's complementinteger (-32,768 to 32,767)

IntegerSimilar: 16-bit, signed (-32,768 to32,767)

int 32-bit signed two's complementinteger (-2,147,483,648 to2,147,483,647)

LongSimilar: 32-bit, signed(-2,147,483,648 to2,147,483,647)

long 64-bit signed two's complement N/A

4

Page 5: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

integer(-9,223,372,036,854,775,808 to9,223,372,036,854,775,807)

char single 16-bit Unicode character N/AHowever, LotusScript doesprovide a String type which cancontain multiple characters.

float single-precision 32-bit IEEE 754floating point

SingleSimilar: single-precision 32-bitfloating point

double double-precision 64-bit IEEE 754floating point

DoubleSimilar: double-precision 64-bitfloating point

Boolean true or false value BooleanSimilar: true or false value

Operators Java has a rich set of operators. Table 3 shows merely a subset of its operators along with thedescription and LotusScript equivalent. For a complete listing, visit the Java Tutorials Operators page.

Table 3. Java operatorsJava Arithmetic Operator Description LotusScript Equivalent

= Assignment =

+ Addition +

++ Increment N/A

+= Addition assignment N/A

- Subtraction (also unary minus) -

-- Decrement N/A

-= Subtraction assignment N/A

* Multiplication *

*= Multiplication assignment N/A

/ Division /

/= Division assignment N/A

% Modulus Mod

%= Modulus assignment N/A

Java Relational Operator Description LotusScript Equivalent

== Equal =

5

Page 6: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

!= Not equal <>, ><

> Greater than >

>= Greater than or equal to >=, =>

< Less than <

<= Less than or equal to <=, =<

Java Logical (bitwise)Operator

Description LotusScript Equivalent

& Bitwise And And

| Bitwise Or Or

^ Bitwise exclusive Or Xor

~ Bitwise complement Not

>> Shift bits right with signextension

N/A

<< Shift bits left N/A

Java Logical (Boolean)Operator

Description LotusScript Equivalent

&& Boolean And And

|| Boolean Or Or

== Boolean equals Eqv

! Boolean Not Not

Declaring a variableThe syntax for declaring a variable in Java is the type, followed by the variable name:

type variable_name;

In Java, variable names can consist of letters, digits, and the underscore. Variable names arecase sensitive and cannot begin with a digit:

Java LotusScript

int i; Dim i as Integer

String s; Dim s as String

6

Page 7: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

Creating a functionThere are two key differences regarding the function syntax between LotusScript and Java.First, the return type is placed in front of the function name (as opposed to LotusScript, inwhich it is placed at the end). Secondly, Java uses the return keyword to return the value fromthe function (see listing 1).

Listing 1. Creating a function examplereturn_type function_name(parameter_type1 parameter_name1, parameter_type2parameter_name2){ //function code... return return_type_object;}

Java LotusScript

public int product(int x, int y) { return x*y; }

Function product(x As Integer, y As Integer) AsInteger product = x * y End Function

Calling the function: int i = product(2,4); System.out.println(i);

Calling the function: Dim i As Integer i = product(2, 4) Print i

Creating a classThe syntax for creating classes in Java is similar to that of LotusScript. Both use the classkeyword with the private/public option, and both allow class members as well as classmethods. Note, however, that the LotusScript class constructor uses the New keyword, whileJava uses the name of the class with zero arguments (see listing 2 and table 4).

Listing 2. Example of creating a classclass class_name{ type class_member1; type class_member2; ....

class_name() //constructor { //constructor code }

return_type class_method1(parameter list) { //method code

7

Page 8: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

}

return_type class_method2(parameter list) { //method code } ....

}

Table 4. Creating a classJava LotusScript

public class Person{ private String Name; private int Age;

public Person() { this.Name=""; this.Age=0; }

public void SetName(String name) { this.Name = name; }

public String GetName() { return this.Name; }

public void SetAge(int age) { this.Age = age; }

public int GetAge() { return this.Age; }

public void AddYears(int i) { this.Age = this.Age + i; }}

Public Class Person Private PName As String Private PAge As Integer

Sub New PAge = 0 PName = "" End Sub

Public Property Set Person_Name As String PName = Person_Name End Property

Public Property Get Person_Name As String Person_Name = PName End Property

Public Property Set Age As Integer PAge = Age End Property

Public Property Get Age As Integer Age = PAge End Property

Sub AddYears (i As Integer) PAge = PAge + i End Sub

End Class

8

Page 9: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

Creating an Instance of the Class:

Person p = new Person(); p.SetName("John Doe"); p.SetAge(20);

System.out.println(p.GetName() + " " +p.GetAge());

p.AddYears(5);

System.out.println(p.GetName() + " " +p.GetAge());

Creating an Instance of the Class:

Dim p As New Person p.Person_Name = "John Doe" p.Age = 20

Messagebox p.Person_Name & " " & Cstr(p.Age)

p.AddYears(5)

Messagebox p.Person_Name & " " & Cstr(p.Age)

Flow control statementsTo control the flow of your script, Java provides all the standard flow control statements youwould expect from any programming language. Table 5 lists Java's most common flow controlstatements and their LotusScript equivalent. For further information on Java's flow controlstatements, visit the Java Tutorials Control Flow Statements page.

Table 5. Java flow control statementsJava Flow Control Statements LotusScript Equivalent

if (condition) {//perform these statements

}

If condition Then'perform these statements

End If

if (condition) {//perform these statements

}else {

//perform these statements}

If condition Then'perform these statements

Else'perform these statements

End If

switch (expr) { case c1: //perform these statements if expr == c1 break; case c2: //perform these statements if expr == c2 break; . . . default: //perform these statements if expr != anyof cases}

Select Case expr Case c1

'perform these statements if expr = c1 Case c2

'perform these statements if expr = c2... Case Else

'perform these statements if expr <> anyof the casesEnd Select

while (condition) {//perform these statements

}

While condition'perform these statements

Wend

do {//perform these statements

} while (condition);

Do While condition'perform these statements

Loop

9

Page 10: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

for (initialization; termination; increment) {//perform these statements

}

For countVar = first To last 'perform these statements

Next

2.4 Differences between LotusScript and the Java languageLotusScript and Java are similar in that they are both are object-oriented programminglanguages. Besides the syntax, one of the main differences between the languages is thatJava is strongly typed, while LotusScript is not.

In Java, you must declare all variables (name and type) before they are used. This is not arequirement in LotusScript, although there is some type enforcement.

Another major difference is that Java is case sensitive, while LotusScript is not. You shouldkeep this in mind when writing Java code because p and P are two different variables, andsetName and SetName are two different methods.

Domino-specific differencesAlthough the names may differ, most of the Domino classes provided for LotusScript areavailable in Java. In LotusScript, Domino classes begin with “Notes”; for example, the class fordealing with databases is “NotesDatabase”, and for documents it's “NotesDocument”.

In Java, on the other hand, the names of the classes do not begin with “Notes”. Hence, theclass for dealing with databases is just “Database”, and for documents it's “Document”.

A major difference between the LotusScript and Java Domino classes is the UI classes.LotusScript provides the following classes for UI interaction:

NotesUIWorkspace, NotesUIDatabase, NotesUIDocument, and NotesUIView

These classes let you interact with the current database, document, or view open in Notes. InJava, however, there are no equivalent UI classes. For a complete listing of the Java Dominoclasses, refer to the Domino Designer Help file.

3 ExamplesLet's look at some common tasks that are performed using LotusScript and see how we cando the equivalent in Java. Our first example is sending an email message.

3.1 Example 1: Sending an emailTake a minute to examine the LotusScript code in listing 3 below:

Listing 3. Example LotusScript send email code1 Dim session As New NotesSession2 Dim database As NotesDatabase3 Dim email As NotesDocument4 Dim sendto As String

10

Page 11: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

5 Dim subject As String6 Dim body As String

7 Set database = session.CurrentDatabase8 Set email = database.CreateDocument9 sendto = "Enter_Email_Address_Here" 10 subject = "Email sent by LotusScript code"11 body = "Text in body of email sent by LotusScript code"

12 Call email.ReplaceItemValue("Form", "Memo")13 Call email.ReplaceItemValue("SendTo", sendto)14 Call email.ReplaceItemValue("Subject", subject)15 Call email.ReplaceItemValue("Body", body)16 Call email.Send(False)

Now let's code the above example in Java, starting off with the Java template code that isprovided for us (see listing 4).

Listing 4. Java template codeimport lotus.domino.*;

public class JavaAgent extends AgentBase {

public void NotesMain() {

try { Session session = getSession();

AgentContext agentContext = session.getAgentContext();

// (Your code goes here)

} catch(Exception e) { e.printStackTrace();

} }

}

In lines 1--6 of the LotusScript example in listing 3 above, we declare the session, database,email, sendto, subject, and body variables. Since the template code already provides us with asession object, let's declare the remaining variables (see listing 5).

Listing 5. Declaring the remaining variablesimport lotus.domino.*;

11

Page 12: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

public class JavaAgent extends AgentBase {

public void NotesMain() {

try { Session session = getSession();

AgentContext agentContext = session.getAgentContext();

// (Your code goes here)

Database database;Document email;String sendto;String subject;String body;

} catch(Exception e) { e.printStackTrace();

} }

}

In lines 7--11 from listing 3, we initialize our database, email, sendto, subject, and bodyvariables (see listing 6). As mentioned earlier, we must use the agentContext object instead ofthe session object to get a handle to the current database. Also, we do not need the Setkeyword in Java to set the variables.

Listing 6. Initializing the variablesimport lotus.domino.*;

public class JavaAgent extends AgentBase {

public void NotesMain() {

try { Session session = getSession();

AgentContext agentContext = session.getAgentContext();

// (Your code goes here)

Database database;Document email;String sendto;String subject;

12

Page 13: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

String body;

database = agentContext.getCurrentDatabase();email = database.createDocument();sendto = "Enter_Email_Address_Here";subject = "Email sent by Java code";body = "Text in body of email sent by Java code";

} catch(Exception e) { e.printStackTrace();

} }

}

In lines 12--15 of listing 3, we replace the value of fields Form, SendTo, Subject, and Body,and finally, in line 16, we send the email. Notice Java does not require the Call keyword (seelisting 7) when calling methods.

Also, even though the replaceItemValue and send methods have the same spelling betweenLotusScript and Java, you must remember to use the correct case in Java (since Java is casesensitive).

Listing 7. Setting the appropriate fields and sending the email import lotus.domino.*;

public class JavaAgent extends AgentBase {

public void NotesMain() {

try { Session session = getSession();

AgentContext agentContext = session.getAgentContext();

// (Your code goes here)

Database database;Document email;String sendto;String subject;String body;

database = agentContext.getCurrentDatabase();email = database.createDocument();sendto = "Enter_Email_Address_Here";subject = "Email sent by Java code";body = "Text in body of email sent by Java code";

13

Page 14: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

email.replaceItemValue("Form", "Memo");email.replaceItemValue("SendTo", sendto);email.replaceItemValue("Subject", subject);email.replaceItemValue("Body", body);

email.send(false);

} catch(Exception e) { e.printStackTrace();

} }

}

There are no more LotusScript lines left, but we still have some additional work to perform inour Java agent. Specifically, in Java, we must call recycle on all Domino objects (see listing 8).Calling recycle ensures that all the memory allocated for those objects is released. For moreinformation on the recycle method, see the “The recycle() method” paragraph in Section 4.

Listing 8. Calling recycle on Domino objectsimport lotus.domino.*;

public class JavaAgent extends AgentBase {

public void NotesMain() {

try { Session session = getSession();

AgentContext agentContext = session.getAgentContext();

// (Your code goes here)

Database database;Document email;String sendto;String subject;String body;

database = agentContext.getCurrentDatabase();email = database.createDocument();sendto = "Enter_Email_Address_Here";subject = "Email sent by Java code";body = "Text in body of email sent by Java code";

email.replaceItemValue("Form", "Memo");

14

Page 15: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

email.replaceItemValue("SendTo", sendto);email.replaceItemValue("Subject", subject);email.replaceItemValue("Body", body);

email.send(false);

//recycle Java Domino objectsif (session !=null)

session.recycle();if (agentContext !=null)

agentContext.recycle();if (database !=null)

database.recycle();if (email !=null)

email.recycle();

} catch(Exception e) { e.printStackTrace();

} }

}

Table 6 sums up this example comparison. Table 6. Side-by-side comparison of Example 1

LotusScript JavaExample 1: Sending an Email

Dim session As New NotesSession

Dim database As NotesDatabase Dim email As NotesDocument Dim sendto As String Dim subject As String Dim body As String

Set database = session.CurrentDatabase Set email = database.CreateDocument sendto = "Enter_Email_Address_Here" subject = "Email sent by LotusScript code" body = "Text in body of email sent byLotusScript code"

Call email.ReplaceItemValue("Form", "Memo") Call email.ReplaceItemValue("SendTo", sendto) Call email.ReplaceItemValue("Subject", subject) Call email.ReplaceItemValue("Body", body)

Call email.Send(False)

Example 1: Sending an Email

Session session = getSession(); AgentContext agentContext =session.getAgentContext();

Database database; Document email; String sendto; String subject; String body;

database = agentContext.getCurrentDatabase(); email = database.createDocument(); sendto = "Enter_Email_Address_Here"; subject = "Email sent by Java code"; body = "Text in body of email sent by Javacode";

email.replaceItemValue("Form", "Memo"); email.replaceItemValue("SendTo", sendto); email.replaceItemValue("Subject", subject); email.replaceItemValue("Body", body);

15

Page 16: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

email.send(false);

//recycle Java Domino objects if (session !=null) session.recycle(); if (agentContext !=null) agentContext.recycle();

if (database !=null) database.recycle(); if (email !=null) email.recycl

3.2 Example 2: Cycling through a Notes viewFor our second example, we cycle through a Notes view (see listing 9). Though fairly simple,this example is very important when coding in Java since it demonstrates using the recyclemethod properly so as to prevent memory exceptions.

Listing 9. LotusScript code for cycling through a view 1 Dim session As New NotesSession2 Dim database As NotesDatabase3 Dim view As NotesView4 Dim document As NotesDocument

5 Set database = session.CurrentDatabase6 Set view = database.GetView("Enter_View_Name_Here")7 Set document = view.GetFirstDocument

8 While (Not document Is Nothing) 'Process the document

9 Print document.Created10 Set document = view.GetNextDocument(document)11 Wend

Starting out with the Java template, let's declare the database, view, and document variables(LotusScript lines 1--4 in listing 9). In addition to these three variables, we need a temporaryDocument. The temp Document variable is required in our while loop, to recycle the currentdocument (see listing 10).

Listing 10. Declaring database, view, and document variablesimport lotus.domino.*;

public class JavaAgent extends AgentBase {

public void NotesMain() {

16

Page 17: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

try { Session session = getSession();

AgentContext agentContext = session.getAgentContext();

// (Your code goes here)

Database database;View view;Document document;Document temp;

} catch(Exception e) { e.printStackTrace();

} }

}

Moving on to lines 5--7 (see listing 9), let's initialize our database, view, and documentvariables, as shown in listing 11. Listing 11. Initializing database, view, and document variables

import lotus.domino.*;

public class JavaAgent extends AgentBase {

public void NotesMain() {

try { Session session = getSession();

AgentContext agentContext = session.getAgentContext();

// (Your code goes here)

Database database;View view;Document document;Document temp;

database = agentContext.getCurrentDatabase();view = database.getView("Enter_View_Name_Here");document = view.getFirstDocument();

} catch(Exception e) { e.printStackTrace();

}

17

Page 18: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

}}

In lines 8--11 in listing 9, we cycle through each document in the view. Java has the samewhile keyword for the loop; however, we must use != instead of Not, and null instead ofNothing (see listing 12).

Also, if we're to assign the same Domino variable multiple times in Java, we need to callrecycle on it before the new assignment, to prevent memory leaks (hence the need for thetemp variable).

Listing 12. Cycling through each document in viewimport lotus.domino.*;

public class JavaAgent extends AgentBase {

public void NotesMain() {

try { Session session = getSession();

AgentContext agentContext = session.getAgentContext();

// (Your code goes here)

Database database;View view;Document document;Document temp;

database = agentContext.getCurrentDatabase();view = database.getView("Enter_View_Name_Here");document = view.getFirstDocument();

while (document != null) {//Process the documentSystem.out.println(document.getCreated());temp = view.getNextDocument(document); // get the next

documentdocument.recycle(); // recycle the document we're done withdocument = temp;

}

} catch(Exception e) { e.printStackTrace();

} }

18

Page 19: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

}

We wrap up this example by calling recycle on all the other Domino objects we created, asshown in listing 13.

Listing 13. Calling recycle on all other Domino objectsimport lotus.domino.*;

public class JavaAgent extends AgentBase {

public void NotesMain() {

try { Session session = getSession();

AgentContext agentContext = session.getAgentContext();

// (Your code goes here)

Database database;View view;Document document;Document temp;

database = agentContext.getCurrentDatabase();view = database.getView("Enter_View_Name_Here");document = view.getFirstDocument();

while (document != null) {//Process the documentSystem.out.println(document.getCreated());temp = view.getNextDocument(document); // get the next

documentdocument.recycle(); // recycle the document we're done withdocument = temp;

}

if (session !=null) session.recycle();

if (agentContext !=null) agentContext.recycle();

if (database !=null) database.recycle();

if (view != null)view.recycle();

19

Page 20: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

} catch(Exception e) { e.printStackTrace();

} }

}

Table 7 sums up this comparison.

Table 7. Side-by-side comparison of Example 2LotusScript Java

Example 2: Cycling through a Notes View

Dim session As New NotesSession

Dim database As NotesDatabase Dim view As NotesView Dim document As NotesDocument

Set database = session.CurrentDatabase Set view = database.GetView("Enter_View_Name_Here") Set document = view.GetFirstDocument

While (Not document Is Nothing) 'Process the document Print document.Created Set document = view.GetNextDocument(document) Wend

Example 2: Cycling through a Notes View

Session session = getSession(); AgentContext agentContext =session.getAgentContext();

Database database; View view; Document document; Document temp;

database = agentContext.getCurrentDatabase(); view = database.getView("Enter_View_Name_Here"); document = view.getFirstDocument();

while (document != null) { //Process the document System.out.println(document.getCreated()); temp = view.getNextDocument(document); // get the next document document.recycle(); // recycle the documentwe're done with document = temp; }

if (session !=null) session.recycle(); if (agentContext !=null) agentContext.recycle();

if (database !=null) database.recycle(); if (view != null) view.recycle();

20

Page 21: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

3.3 Example 3: Generate a report with mail database informationOur last example is fairly extensive. Here we cycle through mail databases on a Domino serverand create an email report with various items from from each mail file. First, take a moment toreview the LotusScript example in listing 14.

21

Page 22: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

Listing 14. LotusScript code example1 Dim session As New Notessession2 Dim nab As New Notesdatabase("Enter_Server_Name_Here", "names.nsf")3 Dim reportDatabase As Notesdatabase4 Dim personDocument As NotesDocument5 Dim report As NotesDocument6 Dim view As NotesView7 Dim temp As String

8 Set reportDatabase = session.CurrentDatabase9 Set report = reportDatabase.CreateDocument

10 Call report.ReplaceItemValue("Form" , "Memo")11 Call report.ReplaceItemValue("Subject" , "Mail Applications Report")

12 Dim richTextItem As New NotesRichTextItem(report, "Body")13 Set view = nab.GetView("People")14 Set personDocument = view.GetFirstDocument15 While Not personDocument Is Nothing16 On Error Resume Next17 Dim mailDatabase As New NotesDatabase(personDocument.mailserver(0),personDocument.mailfile(0))18 If mailDatabase.IsOpen Then19 temp = "Mail Owner: " & personDocument.fullname(0) & " Size: " &Cstr(mailDatabase.size) & " _ bytes Template: " + mailDatabase.DesignTemplateName20 Else21 temp = "Could not open mail file for: " & personDocument.fullname(0) &" Server: " & personDocument.mailserver(0) & " , " & personDocument.mailfile(0)22 End If

23 richTextItem.AppendText(temp)24 richTextItem.AddNewline(1)25 temp = ""26 Set personDocument = view.GetNextDocument(personDocument)27 Wend

28 Call report.Send(False, "Enter_Email_Address_Here")

We start out with lines 1--7 (in listing 14), declaring the needed variables, and we initialize thenab Database variable. In Java, notice that we must use the session object to set nab (seelisting 15).

22

Page 23: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

Listing 15. Declaring the variablesimport lotus.domino.*;

public class JavaAgent extends AgentBase {

public void NotesMain() {

try { Session session = getSession();

AgentContext agentContext = session.getAgentContext();

// (Your code goes here)

Database nab;nab = session.getDatabase("Enter_Server_Name_Here","names.nsf");Database reportDatabase;Document personDocument;Document report;Document tempDocument;View view;String temp;

} catch(Exception e) { e.printStackTrace();

} }

}

The main difference between the LotusScript lines 8--14 (in listing 14) and the Java equivalentis the RichTextItem class; in Java, you need to use the createRichTextItem method of theDocument class to create the rich text field (see listing 16).

Listing 16. Initializing the variables and creating the report email import lotus.domino.*;

public class JavaAgent extends AgentBase {

public void NotesMain() {

try { Session session = getSession();

AgentContext agentContext = session.getAgentContext();

// (Your code goes here)

23

Page 24: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

Database nab;nab = session.getDatabase("Enter_Server_Name_Here","names.nsf");Database reportDatabase;Document personDocument;Document report;Document tempDocument;View view;String temp;

reportDatabase = agentContext.getCurrentDatabase(); report = reportDatabase.createDocument();

report.replaceItemValue("Form" , "Memo"); report.replaceItemValue("Subject" , "Mail Applications Report");

RichTextItem richTextItem; richTextItem = report.createRichTextItem("Body");

view = nab.getView("People"); personDocument = view.getFirstDocument();

} catch(Exception e) { e.printStackTrace();

} }

}

In lines 15--27 of listing 14, we do most of the work in the while loop. In Java, we use try/catchblocks for error handling instead of the On Error statement in LotusScript. Since thegetDatabase method can throw an exception, we take advantage of the catch block to set thetemp string variable (see listing 17).

Another thing we must remember in Java is to use the recycle method within loops whenreusing Domino variables. In this particular while loop, we must remember to recycle themailDatabase and personDocument before each new assignment.

Listing 17. Gathering the mail database information import lotus.domino.*;

public class JavaAgent extends AgentBase {

public void NotesMain() {

try { Session session = getSession();

24

Page 25: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

AgentContext agentContext = session.getAgentContext();

// (Your code goes here)

Database nab;nab = session.getDatabase("Enter_Server_Name_Here","names.nsf");Database reportDatabase;Document personDocument;Document report;Document tempDocument;View view;String temp;

reportDatabase = agentContext.getCurrentDatabase(); report = reportDatabase.createDocument();

report.replaceItemValue("Form" , "Memo"); report.replaceItemValue("Subject" , "Mail Applications Report");

RichTextItem richTextItem; richTextItem = report.createRichTextItem("Body");

view = nab.getView("People"); personDocument = view.getFirstDocument();

while (personDocument != null) { Database mailDatabase; try { mailDatabase = session.getDatabase(personDocument.getItemValueString("MailServer"), personDocument.getItemValueString("MailFile")); temp = "Mail Owner: " +personDocument.getItemValueString("FullName") + " Size: " + mailDatabase.getSize()

+ " _ bytes Template: " +mailDatabase.getDesignTemplateName(); mailDatabase.recycle(); } catch (Exception e) { temp = "Could not open mail file for: " +personDocument.getItemValueString("FullName") + " Server: " +

personDocument.getItemValueString("MailServer") + " , " + personDocument.getItemValueString("MailFile"); } richTextItem.appendText(temp); richTextItem.addNewLine(1);

25

Page 26: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

temp = ""; tempDocument = view.getNextDocument(personDocument); personDocument.recycle(); personDocument = tempDocument; }

} catch(Exception e) { e.printStackTrace();

} }

}

We wrap up this example by sending the email (line 28 of listing 14) and then recycling the restof the Domino objects we created (see listing 18).

Listing 18. Sending email and calling recycle on Domino objects import lotus.domino.*;

public class JavaAgent extends AgentBase {

public void NotesMain() {

try { Session session = getSession();

AgentContext agentContext = session.getAgentContext();

// (Your code goes here)

Database nab;nab = session.getDatabase("Enter_Server_Name_Here","names.nsf");Database reportDatabase;Document personDocument;Document report;Document tempDocument;View view;String temp;

reportDatabase = agentContext.getCurrentDatabase(); report = reportDatabase.createDocument();

report.replaceItemValue("Form" , "Memo"); report.replaceItemValue("Subject" , "Mail Applications Report");

RichTextItem richTextItem; richTextItem = report.createRichTextItem("Body");

26

Page 27: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

view = nab.getView("People"); personDocument = view.getFirstDocument();

while (personDocument != null) { Database mailDatabase; try { mailDatabase = session.getDatabase(personDocument.getItemValueString("MailServer"), personDocument.getItemValueString("MailFile")); temp = "Mail Owner: " +personDocument.getItemValueString("FullName") + " Size: " + mailDatabase.getSize()

+ " _ bytes Template: " +mailDatabase.getDesignTemplateName(); mailDatabase.recycle(); } catch (Exception e) { temp = "Could not open mail file for: " +personDocument.getItemValueString("FullName") + " Server: " +

personDocument.getItemValueString("MailServer") + " , " + personDocument.getItemValueString("MailFile"); } richTextItem.appendText(temp); richTextItem.addNewLine(1); temp = ""; tempDocument = view.getNextDocument(personDocument); personDocument.recycle(); personDocument = tempDocument; }

report.send(false, "Enter_Email_Address_Here");

if (session !=null) session.recycle(); if (agentContext !=null) agentContext.recycle(); if (nab != null) nab.recycle(); if (reportDatabase !=null) reportDatabase.recycle(); if (personDocument !=null) personDocument.recycle(); if (report !=null) report.recycle(); if (view !=null)

27

Page 28: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

view.recycle(); if (richTextItem !=null) richTextItem.recycle();

} catch(Exception e) { e.printStackTrace();

} }

}

Table 8 sums up the comparison.

Table 8. Side-by-side comparison of Example 3LotusScript Java

Example 3: Generate a Report with Mail DatabaseInformation

Dim session As New Notessession

Dim nab As New Notesdatabase("Enter_Server_Name_Here", "names.nsf")

Dim reportDatabase As Notesdatabase

Dim personDocument As NotesDocument Dim report As NotesDocument

Dim view As NotesView Dim temp As String

Set reportDatabase = session.CurrentDatabase Set report = reportDatabase.CreateDocument

Call report.ReplaceItemValue("Form" , "Memo") Call report.ReplaceItemValue("Subject" , "MailApplications Report")

Dim richTextItem As New NotesRichTextItem(report, "Body")

Set view = nab.GetView("People") Set personDocument = view.GetFirstDocument While Not personDocument Is Nothing On Error Resume Next Dim mailDatabase As New NotesDatabase( personDocument.mailserver(0), personDocument.mailfile(0)) If mailDatabase.IsOpen Then

Example 3: Generate a Report with Mail DatabaseInformation

Session session = getSession(); AgentContext agentContext =session.getAgentContext();

Database nab; nab = session.getDatabase("Enter_Server_Name_Here","names.nsf"); Database reportDatabase;

Document personDocument; Document report; Document tempDocument; View view; String temp;

reportDatabase =agentContext.getCurrentDatabase(); report = reportDatabase.createDocument();

report.replaceItemValue("Form" , "Memo"); report.replaceItemValue("Subject" , "MailApplications Report");

RichTextItem richTextItem; richTextItem = report.createRichTextItem("Body");

view = nab.getView("People"); personDocument = view.getFirstDocument(); while (personDocument != null) { Database mailDatabase; try { mailDatabase = session.getDatabase(

28

Page 29: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

temp = "Mail Owner: " &personDocument.fullname(0) & " Size: " & Cstr(mailDatabase.size) &" _ bytes Template: " +mailDatabase.DesignTemplateName

Else temp = "Could not open mail file for: " & personDocument.fullname(0) & " Server: " & personDocument.mailserver(0)& " , " & personDocument.mailfile(0) End If

richTextItem.AppendText(temp) richTextItem.AddNewline(1) temp = "" Set personDocument =view.GetNextDocument(personDocument)

Wend Call report.Send(False,"Enter_Email_Address_Here")

personDocument.getItemValueString("MailServer"), personDocument.getItemValueString("MailFile")); temp = "Mail Owner: " + personDocument.getItemValueString("FullName") + " Size: " + mailDatabase.getSize() + " _bytes Template: " +mailDatabase.getDesignTemplateName(); mailDatabase.recycle(); } catch (Exception e) { temp = "Could not open mail file for: " + personDocument.getItemValueString("FullName") + " Server: " +personDocument.getItemValueString("MailServer") + " , " + personDocument.getItemValueString("MailFile");

}

richTextItem.appendText(temp); richTextItem.addNewLine(1); temp = ""; tempDocument = view.getNextDocument(personDocument); personDocument.recycle(); personDocument = tempDocument;

} report.send(false,"Enter_Email_Address_Here");

if (session !=null) session.recycle(); if (agentContext !=null) agentContext.recycle();

if (nab != null) nab.recycle(); if (reportDatabase !=null) reportDatabase.recycle(); if (personDocument !=null) personDocument.recycle(); if (report !=null) report.recycle(); if (view !=null) view.recycle(); if (richTextItem !=null) richTextItem.recycle();

29

Page 30: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

4 Other essentialsLet's go over some other essential points relevant to our discussion of Java code andLotusScript.

JVM versions. Unlike LotusScript, Java code is run on a Java Virtual Machine (JVM). Table 9shows the JVM version that is shipped with the various Notes/Domino releases.

Table 9. JVM and Notes/Domino versionsNotes/Domino Version JVM Version

6.5.x 1.3.1

7.0.x 1.4.2

8.0.x 1.5.0

8.5 1.6.0

The JVM is installed during the normal client/server install and is independent from a JVM thatcan be installed on the operating system. The version is important when using classesprovided by the JVM since there are differences between versions.

The recycle() method. If you browse through the Domino classes in the Designer Help file,you will notice that each Java class has an additional method called the recycle method (thereis no corresponding LotusScript method). The description of this method (from the Help file)states “The recycle method unconditionally destroys an object and returns its memory to thesystem.”

We won't go into the importance of why you should call the recycle method because this topicis covered in detail in Lotus Support Technote #1097861, “Why it is important to use Recycle() method on every Java object . ” Just remember that, to prevent memory leaks, you shouldALWAYS call the recycle method on all Domino Java objects you create.

Security exceptions. Since Java code is run on the JVM, there is an additional security layerfor Java code that is not present when using LotusScript. Depending on the Java classes /methods being used, you may run into security exceptions such as thejava.security.AccessControlException exception when running your Java code in LotusDomino.

If you do encounter security exceptions, you must explicitly grant access in the java.policy fileof the JVM. For more information, see the Lotus Support Technote #1279509, “Security exceptions are encountered when developing Java agents.”

Using external JAR files with Java agents. Similar to LotusScript .lss files, Java agents canuse existing Java classes. If you have a JAR file with the Java classes you want to use, youcan make these classes available to an agent by using one of the following three methods:

30

Page 31: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

• Attach the JAR file to the agent itself:

1. Open the Java agent in Domino Designer and click “Edit Project”.2. Select the directory in which the JAR file is located in the Base directory field.3. Select and add the JAR file.

• Copy the JAR file to the {Lotus Notes\Domino program directory}\jvm\lib\ext.

• Use the JavaUserClasses Notes.ini variable; in your Notes or Domino Notes.ini file, add thevariable and point to one or more JAR files, for example:

JavaUserClasses=C:\jar_files\file1.jar;C:\jar_files\file2.jar

NOTE: After making the JAR files available, you must use the import statement in the agent torefer to the specific class you want to use.

5 ConclusionHopefully this paper has helped provide a bridge for the traditional Domino developer to begindeveloping Java agents in Domino Designer. The examples presented above can serve astemplate code in developing more extensive Java agents. Remember that the DominoDesigner 8.5 Help file provides an extensive collection of Java examples for each Dominoclass.

6 Resources• The Java Tutorials

• Lotus Domino Designer 8.5 Information Center, Java/CORBA Classes section

• developerWorks Lotus Notes and Domino product page

• IBM Lotus Notes/Domino 8.5 Forum

• Lotus Notes and Domino wiki

7 About the authorOscar I Hernandez is a Staff Software Engineer with the IBM Lotus Technical Supportorganization. He is a member of the Application Development team for Lotus Notes/Dominoand is an IBM Certified Advanced Application Developer. You can reach Oscar at [email protected].

31

Page 32: Writing Java to build applications using IBM Lotus Domino ...public.dhe.ibm.com/.../JavaForLotusScriptDevsFinal.pdf · Hence, as long there was a JVM implemented for the desired platform,

Trademarks• Domino, IBM, Lotus, LotusScript, and Notes are trademarks or registered trademarks of IBM

Corporation in the United States, other countries, or both.

• Java and all Java-based trademarks and logos are trademarks or registered trademarks of SunMicrosystems, Inc. in the United States, other countries, or both.

• Other company, product, and service names may be trademarks or service marks of others.

32