Você está na página 1de 126

RedBeans

RedBack
B
A WEB APPLICATION DEVELOPMENT TOOL
®
All rights to this publication are reserved. No part of this document may be reproduced, transmitted,
transcribed, stored in a retrieval system, or translated into any language, in any form or by any means, without
prior written permission from Infomix Software, Corp. If you are a licensed user of this product, Infomix Soft-
ware, Corp. grants you a limited, nontransferable license to reproduce this particular document. This is limited
to photocopy reproduction of a Infomix Software-supplied master copy. Copies must include all pages con-
tained in the master copy (including this page) and must be intended strictly for internal distribution and use by
the licensee, its employees, and assigns. Reproduced copies may not be transferred, in whole or in part, to any
party outside the licensee’s place(s) of business. The software described in this document is furnished under a
license agreement. The software may be used or copied only in accordance with the terms of the agreement. It
is against the law to copy this software on magnetic tape, disk, or any other medium for any purpose other than
the licensee's personal use.

Copyright © 2001 Infomix Software, Corp.


All Rights Reserved
RedBack Release 3
Documentation DRB-3006
Rev.01102000

Infomix Software, Corp., reserves the right to make changes to this document and the software described
herein at any time and without notice. Infomix Software, Corp. makes no warranty, express or implied, other
than those contained in the terms and conditions of sale, and in no case is Infomix Software, Corp. liable for
more than the license fee or purchase price of this product.

Informix Software, Corp.


4100 Bohannon Drive
Menlo Park, CA 94025 USA

Phone: (650) 926-6300


Fax: (650) 926-6593
World Wide Web: www.informix.com

Principal Technical Provider


eTeam Software

Contributors and Technical Reviewers


Mario Delas, Nik Kesic, Jürgen Joarder, Ben Wedewer and Nghia La.

Infomix Software is a trademark of Infomix Software Corp. RedBack, uniVerse, UniData, SB+, SBOPEN,
SBClient, DATA/C++, TERMULATOR, SBDesktop, ObjectCall, EasyX, DataStage, ESL, UniVerse Call
Interface, UniVerse Objects, uV/Net, RetrieVe, PI/open and Prime INFORMATION are trademarks of Infomix
Software, Corp. TERMiTE is a trademark of Pixel Innovations, Ltd. Pick is a registered trademark of Pick Sys-
tems. Microsoft, Windows, Windows NT and Visual Basic are registered trademarks of Microsoft Corporation
in the United States and or other countries. UNIX is a registered trademark in the United States and other coun-
tries, licensed through X/Open Company. Java, and JavaBeans are a trademark of Sun MicroSystems. Delphi is
a trademark of the Inprise Corporation. All other products, standards, or company names mentioned may be
Contents

Chapter 1 - Installation ....................................................................9


Installation Details ....................................................................................10
Development Platforms ......................................................................11
Web Server .........................................................................................11
Important Notes ..................................................................................11

Chapter 2 - Introduction ................................................................15


RedBeans Architecture .............................................................................17
What are RedBack Business Objects? ................................................17
RBO Class Hierarchy ................................................................................19
RBO ....................................................................................................19
emailObject .........................................................................................19
SysInfo ................................................................................................19
uObject ................................................................................................20
uQuery ................................................................................................20
sbObject ..............................................................................................20

RedBeans 5
Contents

Chapter 3 - Using RedBeans.........................................................21


Introduction ...............................................................................................22
Step-by-Step Instructions for Using RedObject .......................................23
Create Connection object ....................................................................23
Create instance of RedObject .............................................................24
Attach a RBO Class to this object ......................................................24
Get/set property values of the RBO and call Methods .......................25
Set Property Value: .............................................................................26
Call RBO method ................................................................................26
RedObject Code Example .........................................................................28
Read Example .....................................................................................28
Write Example ....................................................................................29
RecordSet Code Example ...................................................................30
Step-by-Step Instructions for Using RedSet .............................................32
Create an instance of a RedSet object. ................................................32
Call the open Method ..........................................................................32
Add New Records to the Object .........................................................33
Select the Current Record ...................................................................33
Get/Set Property Values ......................................................................34
Clear the object (optional) ..................................................................34
RedSet Code Example ..............................................................................35
RedField Object ........................................................................................37
RedField Methods ...............................................................................38
Step-by-Step Instructions for Using RedField ..........................................46
Create an Instance of a RedField Object ............................................46

6 RedBeans
Contents

Assign the RedField a String Value ....................................................46


Manipulate the Field ...........................................................................46
Extract the Modified String ................................................................47
Destroy the Object ..............................................................................47
RedField Code Example ...........................................................................48
RbEvent ....................................................................................................50
Methods ..............................................................................................50
RbEventListener .......................................................................................51
Methods ..............................................................................................51
Debug Logging .........................................................................................52
Error and Alert Handling ..........................................................................53
Alerts ...................................................................................................53
RbException ..............................................................................................54
Methods ..............................................................................................54
Session Ids ................................................................................................55

Chapter 4 - Using RedBeansSvr ...................................................57


Introduction ...............................................................................................58
Step-by-Step Instructions for Using a Stateless Beans .......................58
Step-by-Step Instructions for Using a Stateful Beans ........................61

Appendix A - RedBeans Configuration........................................65


rgw.ini .......................................................................................................66
Example rgw.ini File Settings .............................................................66

Appendix B - EmpMaint Code.......................................................69


Applet Code Listing, EmpMaint.Java .......................................................70
JSP Code Listing, EmpMaint.JSP .............................................................82

RedBeans 7
Contents

Appendix C - Stateless Employee Enterprise Bean....................87


The Home Interface ............................................................................88

Appendix D - Stateful Employee Enterprise Bean ....................103


The Home Interface ..........................................................................104
The Remote Interface ........................................................................105
The Bean ...........................................................................................106

Appendix E - JSP & Stateful Enterprise Bean Example ...........113


The Client Bean ................................................................................114
A simple JSP example ......................................................................118

8 RedBeans
Chapter 1 - Installation

This chapter describes how to install RedBack RedBeans.

RedBeans 9
Chapter 1 - Installation

Installation Details
The files shipped with RedBeans are:
RedBeans.jar -RedBeans class files for development
RedBeansSvr.jar – RedBeans J2EE Server class files
RBExamples.jar – RedBeans examples
RBExamplesSrc.jar – RedBeans examples source
RBJ2EEDemo.jar – J2EE examples and test classes
RBJ2EEDemoSrc.jar – Source for J2EE examples
Windows batch (*.BAT) setup files

Note
The batch files need to be edited to ensure the correct location of your Java and J2SDKEE installa-
tion directories. All examples are compatible on other Java platforms such as Microsoft or Sun.

rbtools.jar - used by JSP RBOScope


rbjdoc.zip - JavaDoc output for redbeans package
Readme.txt
There is also a J2EE directory which contains J2EE Beans that are used by the examples and tests.
There are also ear files used by Sun’s Deploytool to deploy these beans to a J2EE server.
All these files and directories can be found on your RedBack installation CD under the RedBeans
directory.

10 RedBeans
Installation Details

Development Platforms
To install RedBeans, copy RedBeans.jar anywhere you wish as long as your preferred Java IDE or
editor can access RedBeans, via either CLASSPATH or library specification.
The RedBeans.jar file contains the RedBeans package and rbtools.jar file contains classes which
are only required in the RBOScope.
If you are building J2EE components then you will also need to install the RedBeansSvr.jar file
and specifiy it in your CLASSPATH

Once you have built your application, you need to ensure that the relevant classes (including Red-
Beans and if using J2EE the RedBeansSvr packages) are installed in the appropriate places for
your application.

Web Server
The RBODemo examples (applets and JSP) are installed as part of your RedBack Gateway install.
If you want to run JSP examples then you must add RedBeans to your JSP plugin CLASSPATH. If
you are going to run the JSP RBOScope then you will also have to add rbtools.jar to the JSP plugin
CLASSPATH.

Important Notes
To run the demos:

JSP
http://host/cgi-bin/rgw/rbodemo/welcome.jsp
or
http://host/scripts/rgw.dll/rbodemo/welcome.jsp

RedBeans 11
Chapter 1 - Installation

JSP RBOScope
http://host/cgi-bin/rgw/rboscope/scopelogin.jsp
or
http://host/scripts/rgw.dll/rboscope/scopelogin.jsp

RedBeans Examples
Some very simple examples that utilise RedBeans have been included. All examples whether JSP
or J2EE will use RedBeans, but these are specific examples thay may be useful as a guide to how
RedBeans can be used.
These examples can be run from Windows platforms using these bat files:
rbexempform.bat – create a very simple Java form that calls methods on the Employee RBO. Note
that this example uses a connection of rbodemo so if your platform does not support JNI JRGW,
then you will need to amend the source code and specify your required URL
rbexsel.bat – create a RBO uQuery and shows how to parse through a RecordSet
rbexrpc.bat – shows how to make a call to a RedBack account that uses RPC rather than RBO.
You will need to make sure you have an RPC enabled account. See Developing RBO Manual for
details on how to do this.

J2EE Examples
Deploy the required components to your J2EE Server (see your J2EE server’s documentation for
details).
The 4 jar files shipped in the J2EE directory are:
RBSLEmployeeClient.jar – Stateless Employee Bean
RBSFEmployeeClient.jar – Stateful Employee Bean
RBSLCustomerClient.jar – Stateless Customer Bean
rbempjsp.jar – stateful Employee JSP example
We also ship .ear files for each bean which can be used to deploy with Sun’s J2EE Server.

12 RedBeans
Installation Details

The tests in the RedBeans directory are:


rbj2eetester.bat – will create stateless beans for Employee and Customer and a stateful bean for
Employee, then run reads and writes to test.
rbslemptest.bat – will create a stateless bean for Employee RBO and run some tests.
rbemptest.bat will run tests on stateless and stateful Employee

Make sure you edit all these bat files to reflect your Java and J2EE locations.

Note
These examples connect to RBODemo using JNI (see admin guide for details). This may need per-
missions set in your J2EE server.

The RedBeansSvr package also creates a log file (redbeans.log) and you may need to allow
read/write permissions on this file within your J2EE server.

RedBeans 13
Chapter 1 - Installation

14 RedBeans
Chapter 2 - Introduction

This chapter provides an overview of RedBack Redbeans.

RedBeans 15
Chapter 2 - Introduction

What are RedBeans?


RedBeans is a set of JavaBeans which give access to RedBack Business Objects
(RBO's) that reside in a uniVerse/Unidata database via an HTTP interface.
This allows for easy building of Java applications against a universe/Unidata database. Any Java
authoring tools, such as JBuilder3 or Symantec Visual Café may be used to design the applications
for your web pages or Java Server Pages (JSP) or servlets etc.
The web pages themselves can of course be built using any HTML editor.
The RedBeans communicate either to a Web Server running the RedBack Gateway Requester,
which in turn communicates to the RBO Server or direct to the RBO Server using the JNI Gateway
component.

16 RedBeans
RedBeans Architecture

RedBeans Architecture
RedBeans functionality is provided by the redbeans package, which provides the classes required
to connect with and interact with RedBack Business Objects (RBOs) on the RBO Server.
In development mode, the RedBeans classes are installed wherever your Java IDE or editor are
installed. During development you do not make connections to the RBO Server and you can there-
fore install on any machine whether it has access to the Internet/Web Server or not.

For runtime, the RedBeans package needs to be installed where the required environment can
access them. For example, if using JSP then the JSP plug-in needs to know where the package is.

Note
On some platforms (Linux, Solaris, NT and AIX) a JNI Gateway Requester is installed. This pro-
vides a faster, more direct connection.

What are RedBack Business Objects?


RedBack enables you to design your business rules and logic using objects known as RBOs (Red-
Back Business Objects) based on classes that support inheritance.
RBOs reside on the host tier and are independent of the user interface. This provides flexibility to
change the user interface without having to modify the RBOs.
For more details on RBOs refer to the "Developing With RBOs" manual.
A visual tool called RedBack Designer is supplied as part of the RedBack product which is used to
design and maintain RBOs.
The RedBack Business Object model provides the following major benefits:
• Freedom to design HTML pages and graphics using third party web design tools such as
Visual Interdev, FrontPage, HomeSite and other HTML/ASP development tools. Accord-
ingly RedBack enables developers can use for example, Active Server Pages, using
RedPages or Java Server Pages (JSP), Java Servlets or J2EE Server, using RedBeans.

RedBeans 17
Chapter 2 - Introduction

• Ability to define business objects that contain the business logic (fields, calculations etc)
using the RedBack Designer, thus removing the business rules of the application from the
presentation layer. RedBack Designer has been designed to be quick and intuitive to use. It
requires almost no knowledge of the uniVerse/UniData development environment.

Note
For more information about RBOs refer to the "Developing With RBOs" manual.

18 RedBeans
RBO Class Hierarchy

RBO Class Hierarchy


The RedBack Business Object hierarchy comprises the following objects (see the "Developing
RBO Applications" manual for more information):
RBO
emailObject

SysInfo

uObject

uQuery
sbObject

RBO
The RBO class is the superclass for all the RedBack Business Object classes.

emailObject
The emailObject class is a subclass of RBO. This class provides properties and methods to allow
email messages to be sent from the Application Server.

SysInfo
The SysInfo class is a subclass of RBO. This class provides properties and methods to obtain
information about the operating system, database platform and RedBack installation.

RedBeans 19
Chapter 2 - Introduction

uObject
The uObject class is a subclass of RBO. This class provides properties and methods to facilitate
access to uniVerse and UniData databases. Typically, any classes that need to read/write data will
inherit from this class.

uQuery
The uQuery class is a subclass of uObject. This class provides properties and methods to enable
queries to be run against uniVerse and UniData databases.

sbObject
The sbObject class is a subclass of RBO. This class is used to interact with SB+ applications.

RBOs are stored on the uniVerse/UniData backend and RedBack is the interface used to store,
retrieve, and update data associated with RBOs.
For example, you may want to create an RBO called "Employee". The Employee RBO might con-
tain the employee's name, street address, starting date etc. as well as methods to perform server
side validations etc.

Note
See the "Developing With RBOs" manual for information about building RBOs.

20 RedBeans
Chapter 3 - Using
RedBeans

This chapter provides an overview of using RedBack RedBeans.

RedBeans 21
Chapter 3 - Using RedBeans

Introduction
RedBeans are a collection of non-visual Java Beans that are RedBack aware and can communicate
with RBOs on the RedBack Application Server.
RedBeans can be used within many Java environments in a variety of tiers to connect to an RBO
Server. The way in which RedBeans makes its connection to the RBO Server will be made more
efficient when using a JNI Gateway (currently NT, Linux, Solaris and AIX). Please see the Red-
Back pages at the Internet web site www.informix.com for more details.
A RedBeans communicates with an RBO through its RedObject class. The RedObject class pro-
vides methods that allow you to set and get values from the properties of its RBO and also to RBO
server methods.
Where the data has come from a query, then a RecordSet will be created. The RecordSet allows the
code to move through the rows of data returned from the server, and get/set properties for the cur-
rent row. Pages of data can be retrieved and then scrolled through and the result can is typically
displayed in a report or lookup.
In addition to RedObject and RecordSet, RedBeans provides two other classes called RedSet and
RedField.
RedField objects allow for easy manipulation of dynamic multi-valued strings within your Java
code. RedField also provides other useful string functions that the uniVerse/UniData Basic pro-
grammer is familiar with.
For details on the properties and methods of RedObject see “Step-by-Step Instructions for Using
RedObject” on page 23, for details on the properties and methods of RedSet see “Step-by-Step
Instructions for Using RedSet” on page 32.

22 RedBeans
Step-by-Step Instructions for Using RedObject

Step-by-Step Instructions for Using RedObject


These are the typical steps you use to access RedBack Business Objects on the host computer via
RedObjects. For full examples of Java code which demonstrate how to maintain a data file, and
display queries, see the EmpMaint Appendix B.
1. Create a Connection object
2. Create an instance of a RedObject
3. Attach a RBO Class to this object
4. Get/set property values of the RBO and call methods

Create Connection object


RedObjects use HTTP as the connection mechanism to the host provider where the RBO's reside.
The HTTP request will be passed to the RedBack requester which will then access the uni-
Verse/UniData backend. This is done in the following manner.

Syntax
Connection myConn = new Connection(accounturl);
where:

accounturl
Denotes the full URL as used by RedBack to represent a U2 (i.e. uniVerse or UniData) account.
e.g. http://servername/scripts/rgw.dll/accountname
The accountname corresponds to an entry in the rgw.ini file which maps the name to an IP address
and port number (see “rgw.ini” on page 66 for more information about this ini file).

Program Example

Connection myConn = new Connection("http://localhost/scripts/rgw.dll/rbodemo");

or with JSP and JNI Gateway

RedBeans 23
Chapter 3 - Using RedBeans

Connection myConn = new Connection("rbodemo")

Note
If you are using a JNI Gateway (NT, Linux, Solaris, AIX) you should be able to just specify the
accountname if want to use JSP. This will provide a faster more direct communication link.

Forexample:
Connection myConn = new Connection("rbodemo");

Create instance of RedObject


Syntax
RedObject currObj = new RedObject();
Or
RedObject currObj = new RedObject(Connection activeConnection, String
rboClass)
where:

activeConnection
Denotes a handle to a connection class

rboClass
Denotes an RBO class in the format module:rboclass

Attach a RBO Class to this object


Use the open method to attach this object to a RBO. The open will instantiate the RBO on the
host and make available the getting and setting of its properties via the RedObject. If the active
connection and RBOClass name have not been passed to the instance of the RedObject when it
was created then they need to be passed in the open method call

24 RedBeans
Step-by-Step Instructions for Using RedObject

Syntax
currObj.open();
or
currObj.open(Connection activeConnection, String RBOClass);
where:

activeConnection
Denotes a handle to a connection class

Note
open() throws RbException if an error occurs in the open.

rboClass
Denotes an RBO class in the format module:rboclass

Program Example

RedObject currObj = new RedObject(activeConnection, "OFFICE:Employee");


try {
currObj.open();
}
catch(RbException rbe)
....
}

Get/set property values of the RBO and call


Methods
Get Property Value
variable = handle.getProperty(String propname)

RedBeans 25
Chapter 3 - Using RedBeans

where:

propname
Denotes a property name from the current RBO

Program Example

String lastName = currObj.getProperty("LastName");

Set Property Value:


handle.setProperty(String propname, String value);
where:

propname
Denotes a property name from the current RBO

Program Example

currObj.setProperty("LastName", "Gubbins");

or

Program Example

currObj.setProperty("LastName", lastName.getText());

Call RBO method


handle.callMethod(String methodName);

26 RedBeans
Step-by-Step Instructions for Using RedObject

If the method is a "Select" on a RBO query object, then it returns a RecordSet object else a null
object pointer is returned.

Program Example

RecordSet rs = currObj.callMethod("Select");
try {
currObj.callMethod(“ReadData”);
}
catch(RbException rbe){
...

Note
The calMethod throws RbException on error when calling a method.

RedBeans 27
Chapter 3 - Using RedBeans

RedObject Code Example


Read Example
Program Example

//1. Create the connection object


Connection activeConnection =
new Connection("http://localhost/scripts/rgw.dll/rbodemo");
//activeConnection is now handle to current connection

//2. Now we will create a RedObject that will be used to communicate


//with the RBO Server
RedObject empObj = new RedObject(activeConnection, "OFFICE:Employee");

//3. Now create instance on the RBO on the RBO Server.


try {
empObj.open();
}
catch(RbException rbe) {
System.out.printIn(rbe.getTypeDesc()+ rbe.getMessage();
return;
}
/*4. Now we can specify the read. First we set the EmpId value in the RedObject,
this is because with RedObjects, all current data will be sent to the server,
and the application code is responsible to ensuring that the RedObject data //
upto date
*/
empObj.setProperty("EmpId", empId.getText());
try {
empObj.callMethod(“ReadData”);
//this will result in updated properties being returned to the Red Object.
}
catch(RbException rbe){
System.out.printIn(“callMethod ReadData Error” +
rbe.getTypeDesc() + rbe.getMessage();
return;
}
//5. Now in order to get the property values you would do the following, either
//get values into instance variables:

28 RedBeans
RedObject Code Example

String empFirstName = empObj.getProperty("FirstName");


String empLastName = empObj.getProperty("LastName");

//or set controls with current values


firstName.setText(empObj.getProperty("FirstName"));
lastName.setText(empObj.getProperty("LastName"));

Write Example
The following code is a typical example of a RedBack RedBeans applet which performs a write
action.

Program Example

//1. We already have the RedObject handle and need to set the current property
//values
empObj.setProperty("EmpId", empId.getText());
empObj.setProperty("LastName", lastName.getText());
empObj.setProperty("FirstName", firstName.getText());

//2. Call the WriteData method to save the Employee details


try {
empObj.callMethod(“WriteData”);
}
catch(RbException rbe) {
System.out.printIn(“callMethod WriteData error + rbe.getTypeDesc() +
rbe.getMessage());
return;
}

//3. Now reset the forms controls with current RBO data (should do this after
every //RBO method call
empId.setText(empObj.getProperty("EmpId");
lastName.setText(empObj.getProperty("LastName");
firstName.setText(empObj.getProperty("FirstName");

RedBeans 29
Chapter 3 - Using RedBeans

RecordSet Code Example


Program Example

/*The RecordSet is used to scroll through the result of a uQuery, where normally,
more than one row of data is returned.

First we need a connection object */

Connection activeConnection =
new Connection("http://localhost/scripts/rgw.dll/rbodemo");

//Then we need to create the RedObject


RedObject empQuery = new RedObject(activeConnection, "OFFICE:EMPLOOKUP");

//Then we create the instance on the RBO server


try {
empObj.open();
}
catch(RbException rbe) {
System.out.printIn(rbe.getTypeDesc()+
rbe.getMessage();
return;
}

/*Now we can do the actual selection. A RecordSet is returned from a Select. This
will return the first page*/
try {
empObj.callMethod(“WriteData”);
}
catch(RbException rbe) {
System.out.printIn(“callMethod WriteData error + rbe.getTypeDesc() +
rbe.getMessage());
return;
}

/*Now that we have the first page we can get and set values for that page, that
tell us how many items were selected and what the page size is (determined by
the RBO from the class definition).*/

int pageSize = rs.getPageSize();

30 RedBeans
RedObject Code Example

int maxRows = empQuery.getProperty("MaxRows");


int maxPages = rs.getMaxPages();

/*This section of code, will loop through each item on a page, displaying the
details in a textarea. The movement through each row is done with rs.MoveNext().

When a page is at the end then rs.isEOF() will be set to true.


In the following exmple, each row details are displayed in a textArea class
called display */

for(int z = 1; z <= itemsPerPage; z++) {


if(rs.isEOF())
return;

String s = "";
if(rs.isEOF())
s = "";
else {
s = rs.getProperty("EMP.ID") + " "+ rs.getProperty("FIRST.NAME") +
" " + rs.getProperty("LAST.NAME");

display.append(s);
}
rs.moveNext();
}

RedBeans 31
Chapter 3 - Using RedBeans

Step-by-Step Instructions for Using RedSet


These are the typical steps you use to create a RedSet object:
1. Create an instance of a RedSet object
2. Call the Open method
3. Add new records to the object
4. Select the current record.
5. Get/Set property values of the RedSet Object
6. Clear the RedSet (optional)

Create an instance of a RedSet object.


This creates an empty shell for a new RedSet object. Before anything can be done with the object
it must first be opened and the properties it supports defined. This is done with the open method

Syntax
handle = new RedSet();

Program Example

RedSet redSet = new RedSet();

Call the open Method


Call the open method, passing the list of property names the object should contain. Opening a
RedSet object defines the fields that will be supported in its internal arrays.

Syntax
handle.open(fieldlist);

32 RedBeans
Step-by-Step Instructions for Using RedSet

Where:

fieldlist
Denotes a comma separated list of names of properties the object should support.

Add New Records to the Object


To save data in the RedSet object you must first add a new record. This is done by calling the add-
New method. After you call the addNew method, the new record becomes the current record.

Syntax
handle.addNew();
or
handle.addNew(String[] fieldNames, String[] values);
where:

fieldNames
Denotes an array of fieldnames. Each field name must exist in the initial list passed in the open
method call.

values
Denotes an array of corresponding values

Select the Current Record


Moves to the first, last, next, or previous record in a specified RedSet object and makes that record
the current record.

Syntax
handle.{MoveFirst() | MoveLast() | MoveNext() | MovePrevious()}

RedBeans 33
Chapter 3 - Using RedBeans

Get/Set Property Values


Syntax for Get Property Value
variable = handle.getProperty(String propname);
where:

propname
Denotes a fieldname that must exist in the initial list passed in the open method call.

Syntax for Set Property Value


handle.setProperty(String propname, String value);
where:

propname
Denotes a fieldname that must exist in the initial list passed in the open method call.

Clear the object (optional)


Syntax
handle.close();
This will initialise all arrays within the RedSet

34 RedBeans
RedSet Code Example

RedSet Code Example

Program Example

<%@ page import = "RedBeans.*" %>

<HTML>
<HEAD>
<TITLE>RedBeans JSP RedSet Example</TITLE>
</HEAD>

<BODY>
<%

//1. create a RedSet object instance that will be used to manipulate our
strings
RedBeans.RedSet oRedSet = new RedBeans.RedSet();

//2. define "field name"

oRedSet.open("firstName,lastName,dept");

//3. assign the rows of data


String fields[] = { "firstName" , "lastName" , "dept"};
String values[] = { "Mike", "Kontorovich", "Eng" };
oRedSet.addNew(fields, values);

values[0] = "Jurgen";
values[1] = "Joarder";
values[2] = "Eng";
oRedSet.addNew(fields, values);

values[0] = "Simon";
values[1] = "Caddick";
values[2] = "Support";
oRedSet.addNew(fields, values);

values[0] = "Nghia";
values[1] = "La";
values[2] = "Eng";
oRedSet.addNew(fields, values);

RedBeans 35
Chapter 3 - Using RedBeans

//4. now scroll through the RedSet getting values


oRedSet.moveFirst();
out.println("<table border=1><tr><td>FirstName</td><td>Last-
Name</td><td>Dept</td></tr>");
while(!oRedSet.isEOF()) {
out.println("<tr><td>"+oRedSet.getProperty("firstName")+"</td>");
out.println("<td>"+oRedSet.getProperty("lastName")+"</td>");
out.println("<td>"+oRedSet.getProperty("dept")+"</td></tr>");
oRedSet.moveNext();
}
out.println("</table>");

//5. finished to can get rid of all data - this leaves object available for re-
use
oRedSet.close();

%>
</BODY>
</HTML>

36 RedBeans
RedField Object

RedField Object
RedField is a nested data structure, that can represent uniVerse/UniData nested data-base fields. It
is limited to two levels of nesting.

Note
chr(253) and chr(252) are the default values for ValueMarker and SubValueMarker. It is possible
to change these values using the SetVM() and SetSVM() methods.

Access to each of the two levels uses a syntax similar to that found in the uniVerse/UniData
BASIC language, using the getValue() method.

Program Example

//create RedField object


RedBeans.RedField rf = new RedPages.RedField();
//assign contents
rf.setStringValue("THIS");
//access this value
System.out.printIn(rf.getValue());
//set value in second multivalue
rf.ins(z,"GREAT");
//rf now contains "THIS<ValueMarker>GREAT"
//now insert subvalue marker
rf.ins(1,2,"IS");
//rf now contains “THIS”<SubValueMarker>IS<ValueMarker>GREAT”

RedBeans 37
Chapter 3 - Using RedBeans

RedField Methods
Methods
count
getLength
setStringValue
setVM()
setSVM()
del
ins
replace
swap
getValue

RedField Object Methods

count Method
Description
Returns the number of values, or subvalues contained in the specified portion of the object.

Syntax
Int rf.Count(); //returns number of multivalues in the string
Int rf.Count(mvpos); //returns number of subvalues in multivalue deter-
mined by mvpos

getLength Method
Description
Returns the string length contained in the specified portion of the object.

38 RedBeans
RedField Object

Syntax
int rf.getLength();
int rf.getLength(int mvpos);

RedBeans 39
Chapter 3 - Using RedBeans

setStringValue Method
Description
This sets, in string format, the contents of the RedField object. If the portion already contains a
string it is replaced.

Syntax
rf.setStringValue(StringValue);

setVM() Method
Description
This method sets the current char value that is used to delimit values within a dynamic string by
the RedField object.

Syntax
setVM(char VM);

setSVM() Method
Description
This method sets the current char subvalue that is used to delimit values within a dynamic string by
the RedField object.

Syntax
setSVM(char SVM);

del Method
Description
This deletes an element (Value or SubValue) from the specified portion of the RedField object.

Syntax
rf.del(int mvpos)

40 RedBeans
RedField Object

rf.del(int mvpos,int svmpos)

RedBeans 41
Chapter 3 - Using RedBeans

ins Method
Description
This inserts an element (Value or SubValue) into the specified portion of the RedField object.

Syntax
rf.ins(int mvpos);
rf.ins(int mvpos,int svmpos)

42 RedBeans
RedField Object

replace Method
Description
This replaces an element (Value or SubValue) from the specified portion of the RedField object.

Syntax
replace(int mvpos);
replace(int mvpos,int svmpos);

RedBeans 43
Chapter 3 - Using RedBeans

swap method
Description
This method is used on an initial string to replace all occurrences of one substring with another
substring.

Syntax
Static String RedField.swap(String Value,String OldStr,String NewStr);

This syntax has the following parts:

Part Description
Value The string that is to have its substrings swopped.
OldStr The sequence of characters to be replaced.
NewStr The sequence of characters to replace the OldStr with.

Parts of the Syntax

Remarks
OldStr and NewStr are strings so if you wish to replace a single character they should still be
passed as a string i.e. to replace all character ‘A’ with the character ‘B’ you would do a
RedField.swap(mystring,"A","B").

44 RedBeans
RedField Object

getValue Method
Description
This is a nesting operator to access a specific value or subvalue.

Syntax
String rf.getValue();
String rf.getValue(int mvpos);

RedBeans 45
Chapter 3 - Using RedBeans

Step-by-Step Instructions for Using RedField


These are the typical steps involved when using a RedField object.
1. Create an instance of a RedField object
2. Assign the RedField a string value
3. Manipulate the field
4. Extract the modified string
5. Destroy the object

Create an Instance of a RedField Object


This creates an empty RedField object.

Syntax
RedBeans.RedField rf = new RedBeans.RedField();

Assign the RedField a String Value


This can be done in a variety of different was Using the Ins, Replace and Append methods.

Syntax
rf.setStringValue(dynastring);

Manipulate the Field


The RedField allows individual elements to be added, deleted or replaced from the string value.

Syntax
To insert element at Value position 2:
rf.ins(2,stringValue);

46 RedBeans
Step-by-Step Instructions for Using RedField

To delete SubValue 3 of Value 1:


rf.del(1,3);
To add a new SubValue to the end of Value 2
rf.ins(2,rf.count(2)+1);

Extract the Modified String


Once the string has been manipulated using the RedField it can then be extracted again as a
dynamic string.

Syntax
rf.getValue();

Destroy the Object


When you have finished with any object it is important to close or reset the object to release any
resources it may be consuming.

Syntax
rf = null;

RedBeans 47
Chapter 3 - Using RedBeans

RedField Code Example

Program Example

<%@ page import = "RedBeans.*" %>

<HTML>
<HEAD>
<TITLE>RedBeans JSP RedField Example</TITLE>
</HEAD>

<BODY>
<%

//1. create a RedField object instance that will be used to manipulate our
string
RedBeans.RedField oFld = new RedBeans.RedField();

//2. create initial string - a list of names and item counts and convert
// the ":" and "," separators into subvalue and value marks

String myString = "Colin:100,Jurgen:205,Tony:400,Mike:400";


myString = oFld.swap(myString, ":", ""+oFld.SVM);
myString = oFld.swap(myString, ",", ""+oFld.VM);

//3. assign the string to the RedField


oFld.setStringValue(myString);

//4. display current contents


out.println("RedField contains "+oFld.getValue());

//5 now display each multi value


out.println("<br><br>");
for(int mvpos = 1; mvpos <= oFld.count(); mvpos++) {
out.println("value at "+mvpos+" = "+oFld.getValue(mvpos)+"<br>");
}

//6 now display each multi value, subvalue 1


out.println("<br><br>");
for(int mvpos = 1; mvpos <= oFld.count(); mvpos++) {
out.println("value at "+mvpos+",1 = "+oFld.getValue(mvpos,1)+"<br>");

48 RedBeans
RedField Code Example

//7. now insert nghia at multivalue position 3


oFld.ins(3, "Nghia");
oFld.ins(3,2, "800");

//8. now redisplay current values


out.println("<br><br>RedField contains "+oFld.getValue());
out.println("<br><br>");
for(int mvpos = 1; mvpos <= oFld.count(); mvpos++) {
out.println("value at "+mvpos+" = "+oFld.getValue(mvpos)+"<br>");
}

//9. delete Mike from the list


oFld.del(5);
out.println("<br><br>RedField contains "+oFld.getValue());

//10 now convert it back into the original format


myString = oFld.swap(oFld.getValue(), ""+oFld.VM, ",");
myString = oFld.swap(oFld.getValue(), ""+oFld.SVM, ":");
out.println("<br><br>myString = "+myString);

//11. remove the RedField


oFld = null;

%>
</BODY>
</HTML>

RedBeans 49
Chapter 3 - Using RedBeans

RbEvent
This is a RedBeans class that extends EventObject, it is used to let interested classes know about
RedBeans debugs. More types will be added in the future.

Methods
The methods available from an instance of RbEvent are:

public int getType()


This will return the type of RbEvent:
RbEvent.DEBUG

public String getText()


This will return the string value associated with the type.

50 RedBeans
RbEventListener

RbEventListener
To make your class(es) listeners for RbEvents, you need to implement RbEventListener.

Methods
The RbEventListener Interface has one method:

public void receiveRbEvent(RbEvent e)


You then need to add the class as a listener

Program Example

thisObj = new RedObject(currConn, "OFFICE:Employee");


// add ourselves as a listener for debugs
thisObj.addDebugListener(this);

RedBeans 51
Chapter 3 - Using RedBeans

Debug Logging
You can switch on debug for an instance of RedObject. This will result in the RedObject firing an
RbEvent which your code can listen for.

Syntax
currObj.setDebug(boolean flag);
where:

flag
If set to true will switch on logging, false will switch it off.
To listen for debugs, your class needs to implement RbEventListener.

Program Example

// receive an rbevent and display information


public void receiveRbEvent(RbEvent e) {
// get type and display information
if(e.getType() == RbEvent.DEBUG) {
// if we do not have debug display created then create it and show it now
if(debugDisplay == null) {
debugDisplay = new RedDebug(getFrame(this));
debugDisplay.show();
}
debugDisplay.displayDebugString(e.getText());
}
}

Note
This example displays a dialog to display debug information and is taken from an applet example.

52 RedBeans
Error and Alert Handling

Error and Alert Handling


The RBO Server and RedBeans themselves, can generate errors. The RBO Server can also gener-
ate alerts. Errors are thrown as RbException when RedObject methods open() and callMethod()
are called.

Program Example

try {
empObj.open();
}
catch(RbException rbe) {

//deal with error.

System.out.printIn(rbe.getType() + rbe.getMessage());
return;
}

Alerts
If you want to look for alerts generated by the RBO server callMethod() method call then use:
getServerAlert();

Program Example

If(thisempObj.getServerAlert().length()>0)
System.out.printIn(empObj.getServerAlert());

RedBeans 53
Chapter 3 - Using RedBeans

RbException
This is a RedBeans class that traps errors when the RedObject methods open() and callMethod()
are called.

Methods
The methods available are:

public int getType()


This will return the type of RbException:
CONNECTIONERROR
SERVERERROR
REDBEANSERROR

54 RedBeans
Session Ids

Session Ids
The RBO Server uses a unique session id to identify each request from a client.
If your RedBeans code is going to reference more than one RBO object, then you should pass the
session id to each instance of RedObject. By doing this you will maintain the association between
all RBO server objects created for a user and session. If you use applets on different HTML pages
then you will need to store the session id somewhere (e.g. cookies) and retrieve it on the subse-
quent pages.

Program Example

String sessionId = currObj.getSessionId();


currObj.SetSessionId(sessionId);

RedBeans 55
Chapter 3 - Using RedBeans

56 RedBeans
Chapter 4 - Using
RedBeansSvr

This chapter provides an overview of using the RedBeansSvr package which contains classes that
provide support for J2EE and RedBeans

RedBeans 57
Chapter 4 - Using RedBeansSvr

Introduction
RedBeansSvr provides support for J2EE Session beans, both stateless and stateful. Your J2EE cli-
ent/application can therefore communicate to RedBack RBOs via these session beans.
If you use the stateless session beans then your client/application will need to store the session
state for each client as the stateless beans by definition do not store state and can be used by many
clients.
You will pass the session state to each stateless bean request and updated session state will be
returned to you.
When using the stateful session beans, then each instance of the bean will maintain its own session
state on behalf of the client.

The RedBeansSvr package contains:


RedBeansEJB – this is the main Session class that contains methods that will communicate to the
RedBeans RedObjects for you. This class has stateless behaviour.
RedBeansSFEJB – inherits from RedBeansEJB but stores session state on your behalf.
RBLog – write logging information.

Step-by-Step Instructions for Using a Stateless


Beans
Note
An understanding of J2EE and creating enterprise beans is assumed.

Appendix C contains examples of a stateless enterprise bean that connects to the Employee RBO
from RBODemo account. It shows the Bean, Remote and Home classes that make up the enter-
prise bean.

58 RedBeans
Introduction

This section will look at how a client uses this stateless employee example. The example uses the
bean RBSLEmployeeClient.jar that is shipped with RedBeans.

This stateless bean is deployed with a JNDI name of SLEmployee


The first thing the client needs to do is to find the bean

Program Example

Context initial = new InitialContext();


Object objref1 = initial.lookup("SLEmployee");

Now create the Home interface

Program Example

EmployeeHome home = (EmployeeHome)PortableRemoteObject.narrow(objref1, Employee-


Home.class);

Now create the Remote interface which provides our link to the bean

Program Example

Employee empTest = home.create();

RedBeans 59
Chapter 4 - Using RedBeansSvr

We now specify the RBO and connection details, which will result in the RBO being opened. This
will return a Vector array that contains the session state for the client. The client needs to preserve
this state.

Program Example

Vector[] ourSession = empTest.createObj("OFFICE:Employee", URL);

The client can now make calls to the bean and communicate with the RBO.

Program Example

ourSession = empTest.doRead(ourSession1, empId);


String lastName = empTest.getLastName(ourSession);
String salary = empTest.getProperty(ourSession, “Salary”);
ourSession = empTest.callMethod(ourSession, “WriteData”);

60 RedBeans
Introduction

Step-by-Step Instructions for Using a Stateful


Beans
Note
An understanding of J2EE and creating enterprise beans is assumed.

Appendix D contains examples of a stateful enterprise bean that connects to the Employee RBO
from RBODemo account. It shows the Bean, Remote and Home classes that make up the enter-
prise bean.

This section will look at how a client uses this stateful employee example. The example uses the
bean RBSFEmployeeClient.jar that is shipped with RedBeans.

This stateful bean is deployed with a JNDI name of SFEmployee


The first thing the client needs to do is to find the bean

Program Example

Context initial = new InitialContext();


Object objref1 = initial.lookup("SFEmployee");

Now create the Home interface

RedBeans 61
Chapter 4 - Using RedBeansSvr

Program Example

EmployeeSFHome home = (EmployeeSFHome)PortableRemoteObject.narrow(objref1,


EmployeeSFHome.class);

Now create the Remote interface which provides our link to the bean

Program Example

EmployeeSF empTest = home.create(“rbodemo”, “OFFICE:Employee”);

We now request that the RBO is created, which will result in the RBO being opened. The bean will
store the session state.

Program Example

empTest.createObj();

62 RedBeans
Introduction

The client can now make calls to the bean and communicate with the RBO. Note that the client
does not store the session state as it did in the stateless example. Each bean has a one to one rela-
tionship with its client.

Program Example

empTest.doRead(empId);
String lastName = empTest.getLastName();
String salary = empTest.getProperty(“Salary”);
ourSession = empTest.callMethod(“WriteData”);

RedBeans 63
Chapter 4 - Using RedBeansSvr

64 RedBeans
Appendix A - RedBeans
Configuration

This chapter information about RedBeans configuration.

RedBeans 65
Appendix A - RedBeans Configuration

rgw.ini
Configuration of RedBeans is controlled via the file rgw.ini file which is located in the Web
Server's 'document root' directory. If a Web Server is not present on the machine where RedBeans
is installed then rgw.ini is placed in the Windows directory instead.

Note
An example rgw.ini is automatically generated by the install procedure. You may use this file as is
or edit it to suit your requirements.

Example rgw.ini File Settings


# example rgw.ini file. this is a comment line.
uvtest fred:8300
udttest fred:8301

uvtest/udttest are the account names (a unique key used throughout RGW), fred is the host name of
the RedBack Server Machine, and 8300/8301 are the ports used to connect to the Responder.
If the Web Server Machine and the RedBack Server Machine are the same machine, use 'localhost'
instead of 'fred' above.
You can use the raw ip address instead of the hostname if you prefer. For example, for the account
uvtest quoted in the above example, you could use:
uvtest 203.14.103.84:8300

instead of
uvtest fred:8300

You can further control RedBeans behavior for rgw.dll only by setting the RGWLOADINI system
environment variable as follows:

0
This is the default setting

66 RedBeans
rgw.ini

Load rgw.ini contents at dll attach and use that cache thereafter unless rgw.ini changes - in which
case reload rgw.ini for all subsequent requests.

1
This setting provides the fastest option.
Load at dll attach and never check on rgw.ini thereafter. It will be necessary to restart IIS or other
application using RedPages to pick up changes to rgw.ini.

2
This gets the location of rgw.ini at dll attach but unconditionally reload rgw.ini for every request
but is not particularly useful.

3
Do not do anything at dll attach. This gets the location of rgw.ini for each request and unconditio
nally reloads rgw.ini for every request.

RedBeans 67
Appendix A - RedBeans Configuration

68 RedBeans
Appendix B - EmpMaint
Code

This chapter contains the code listing for EmpMaint.Java which is an Applet example of using
RedBeans, RedObject and so on. A JSP example is also provided.

RedBeans 69
Appendix B - EmpMaint Code

Applet Code Listing, EmpMaint.Java

Program Example

package RBODemo;

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import RedBeans.*;

// extends RBDApplet!
public class EmpMaint extends RBDApplet implements RbEventListener {
boolean isStandalone = false;
Label label1 = new Label();
Label label2 = new Label();
Label label3 = new Label();
Label label4 = new Label();
Label label5 = new Label();
Label label6 = new Label();
Label label7 = new Label();
TextField empId = new TextField();
TextField firstName = new TextField();
RedDebug debugDisplay = null;

String origEmpValue = "", origSalaryValue = "";;

boolean selectRunning = false;

RedObject thisObj = null; // handle to RedObject for this applet


Connection currConn = null; // connection details for this applet
TextField lastName = new TextField();
TextField hireDate = new TextField();
TextField salary = new TextField();
Choice dept = new Choice();
TextArea interest = new TextArea(5,40);

RedField deptCodes = null; // used to store the department


//codes (description gets displayed in combo)
RBDImage image = new RBDImage(this);

70 RedBeans
Applet Code Listing, EmpMaint.Java

String ourURL = "";


Button saveButton = new Button();
Button clearButton = new Button();
Label Status = new Label();
Button button1 = new Button();
Button button2 = new Button();
GridBagLayout gridBagLayout1 = new GridBagLayout();

//Construct the applet


public EmpMaint() {
}

//Initialize the applet


public void init() {
super.init();
try {
jbInit();
}
catch (Exception e) {
e.printStackTrace();
}

// now create the redback objects


if(isApplet) {
ourURL = "http://"+getHost()+":"+getPort()+"/"+parentURL;
}

currConn = new Connection(ourURL);


thisObj = new RedObject(currConn, "OFFICE:Employee");
// add ourselves as a listener for errors and debugs
thisObj.addDebugListener(this);

// thisObj.setDebugOn(true); // this will switch on debug

// now open the object - will do a create


try {
thisObj.open();
}
catch(RbException rbe) {
RBDMessage message = new RBDMessage(getFrame(this), "Object Open
Error");
message.setMessage(rbe.getTypeDesc() + rbe.getMessage());
message.pack();

RedBeans 71
Appendix B - EmpMaint Code

message.show();
return;
}

// now look for an alert


if(thisObj.getServerAlert().length() > 0) {
RBDMessage message = new RBDMessage(getFrame(this), "Server
Alert");
message.setMessage(thisObj.getServerAlert());
message.pack();
message.show();
}

// get department codes and descriptions


deptCodes = new RedField(thisObj.getProperty("DeptCodes"));
// now update the combo box
RedField temprf = new RedField(thisObj.getProperty("DeptDescs"));
for(int z = 1; z <= temprf.count(); z++)
dept.addItem(temprf.getValue(z));

private void jbInit() throws Exception {


this.setBackground(Color.white);
label1.setText("Emp ID");
label2.setText("First Name");
label3.setText("Last Name");
label4.setText("Hire Date");
label5.setText("Salary");
label6.setText("Department");
label7.setText("Interests");

salary.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(FocusEvent e) {
salary_focusGained(e);
}
public void focusLost(FocusEvent e) {
salary_focusLost(e);
}
});
hireDate.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(FocusEvent e) {
hireDate_focusLost(e);
}

72 RedBeans
Applet Code Listing, EmpMaint.Java

});
image.setBackground(Color.white);
image.setScaleImage(false);
saveButton.setLabel("Save");
clearButton.setLabel("Clear");
Status.setForeground(new Color(255, 0, 77));
Status.setFont(new Font("Serif", 1, 12));
button1.setLabel("...");
button2.setLabel("...");
button2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
button2_actionPerformed(e);
}
});
button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
button1_actionPerformed(e);
}
});
saveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
saveButton_actionPerformed(e);
}
});
clearButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e) {
clearButton_actionPerformed(e);
}
});
empId.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(FocusEvent e) {
empId_focusGained(e);
}
public void focusLost(FocusEvent e) {
empId_focusLost(e);
}
});

this.setLayout(gridBagLayout1);
drawForm();
}

private void drawForm() {

RedBeans 73
Appendix B - EmpMaint Code

GridBagConstraints c = new GridBagConstraints();


GridBagLayout gbl = new GridBagLayout();
setLayout(gbl);

c.anchor = GridBagConstraints.WEST;
c.gridx = 0; c.gridy = 0;c.gridwidth = 1; c.gridheight = 1;
gbl.setConstraints(label1, c); add(label1);

c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.gridx = 0;c.gridy = 1;c.gridwidth = 1;c.gridheight = 1;
gbl.setConstraints(label2, c); add(label2);

c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.gridx = 0; c.gridy = 2; c.gridwidth = 1; c.gridheight = 1;
gbl.setConstraints(label3, c); add(label3);

c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.gridx = 0; c.gridy = 3; c.gridwidth = 1; c.gridheight = 1;
gbl.setConstraints(label4, c); add(label4);

c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.gridx = 0;c.gridy = 4;c.gridwidth = 1;c.gridheight = 1;
gbl.setConstraints(label5, c);add(label5);

c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.gridx = 0;c.gridy = 4;c.gridwidth = 1;c.gridheight = 1;
gbl.setConstraints(label5, c);add(label5);

c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.gridx = 0;c.gridy = 5;c.gridwidth = 1;c.gridheight = 1;
gbl.setConstraints(label6, c);add(label6);

c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.gridx = 0;c.gridy = 6;c.gridwidth = 1;c.gridheight = 1;
gbl.setConstraints(label7, c);add(label7);

74 RedBeans
Applet Code Listing, EmpMaint.Java

c = new GridBagConstraints();
c.gridx = 1;c.gridy = 0;c.gridwidth = 1;c.gridheight = 1;
c.anchor = GridBagConstraints.WEST;c.ipadx = 20;
gbl.setConstraints(empId, c);add(empId);

c = new GridBagConstraints();
c.gridx = 2;c.gridy = 0;c.gridwidth = 1;c.gridheight = 1;
c.anchor = GridBagConstraints.WEST;
gbl.setConstraints(button2, c);add(button2);

c = new GridBagConstraints();
c.gridx = 3;c.gridy = 0;c.gridheight = 6;c.weightx = 1.0;
//c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.BOTH;c.anchor = GridBagCon-
straints.WEST;
c.insets = new Insets(0, 10, 0, 10);
gbl.setConstraints(image, c);add(image);

c = new GridBagConstraints();
c.gridx = 1;c.gridy = 1;c.gridwidth = 2;c.gridheight = 1;
//c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.WEST;c.ipadx = 70;
gbl.setConstraints(firstName, c);add(firstName);

c = new GridBagConstraints();
c.gridx = 1;c.gridy = 2;c.gridwidth = 2;c.gridheight = 1;
c.anchor = GridBagConstraints.WEST;
c.ipadx = 70;gbl.setConstraints(lastName, c);add(lastName);

c = new GridBagConstraints();
c.gridx = 1;c.gridy = 3;c.gridwidth = 1;c.gridheight = 1;
c.ipadx = 70;c.anchor = GridBagConstraints.WEST;
gbl.setConstraints(hireDate, c);add(hireDate);

c = new GridBagConstraints();
c.gridx = 2;c.gridy = 3;c.gridwidth = 1;c.gridheight = 1;
c.anchor = GridBagConstraints.WEST;
gbl.setConstraints(button1, c);add(button1);

c = new GridBagConstraints();
c.gridx = 1;c.gridy = 4;c.gridwidth = 1;c.gridheight = 1;
c.ipadx = 40;c.anchor = GridBagConstraints.WEST;
gbl.setConstraints(salary, c);add(salary);

RedBeans 75
Appendix B - EmpMaint Code

c = new GridBagConstraints();
c.gridx = 1;c.gridy = 5;c.gridwidth = 1;c.gridheight = 1;
c.ipadx = 40;c.anchor = GridBagConstraints.WEST;
gbl.setConstraints(dept, c);add(dept);

c = new GridBagConstraints();
c.gridx = 0;c.gridy = 7;c.gridwidth = 3;c.gridheight = 1;
gbl.setConstraints(interest, c);add(interest);

c = new GridBagConstraints();
c.gridx = 0;c.gridy = 8;c.gridwidth = 1;c.gridheight = 1;
c.anchor = GridBagConstraints.WEST;c.insets = new Insets(10,0,0,0);
gbl.setConstraints(saveButton, c);add(saveButton);

c = new GridBagConstraints();
c.gridx = 1;c.gridy = 8;c.gridwidth = 1;c.gridheight = 1;
c.anchor = GridBagConstraints.WEST;c.insets = new Insets(10,0,0,0);
gbl.setConstraints(clearButton, c);add(clearButton);

c = new GridBagConstraints();
c.gridx = 0;c.gridy = 9;c.gridwidth = 3;c.gridheight = 1;
c.ipadx = 80;c.anchor = GridBagConstraints.WEST;
gbl.setConstraints(Status, c);add(Status);
}
//Get Applet information
public String getAppletInfo() {
return "RBODemo Employee Maintenance";
}

void empId_focusGained(FocusEvent e) {
// store emp id so that we can check if value changes
origEmpValue = empId.getText();
}

void empId_focusLost(FocusEvent e) {

// if emp id has changed then do a read


if(empId.getText().equals(origEmpValue))
return; // nothing to do

76 RedBeans
Applet Code Listing, EmpMaint.Java

// set current employee id


thisObj.setProperty("EmpId", empId.getText());

// now do the read


try {
thisObj.callMethod("ReadData");
// now set the form values
setFormValues();
}
catch(RbException rbe) {
Status.setText("Error - "+rbe.getType()+" - "+rbe.getMessage());
return;
}
}

private void setFormValues() {

empId.setText(thisObj.getProperty("EmpId"));
lastName.setText(thisObj.getProperty("LastName"));
firstName.setText(thisObj.getProperty("FirstName"));
hireDate.setText(thisObj.getProperty("HireDate"));
salary.setText(thisObj.getProperty("Salary"));
Status.setText("");

// look for postition of dept


String deptcode = thisObj.getProperty("Dept");

for(int z = 1; z <= deptCodes.count(); z++) {

if(deptCodes.getValue(z).equals(deptcode)) {
dept.select(z-1);
break;
}
}

// interests needs to have value mark swapped with line feed


RedField rf = new RedField(thisObj.getProperty("Interests"));
rf.swap(String.valueOf(String.valueOf(rf.getVM())), "\n");
interest.setText(rf.getValue());

image.setImageId("http://"+getHost()+":"+getPort()+"/"+
imageDir+"/"+ thisObj.getProperty("ImageFile"));
}

RedBeans 77
Appendix B - EmpMaint Code

void saveButton_actionPerformed(ActionEvent e) {
// first update all the properties in current object
getFormValues();
// now do the write
try {
thisObj.callMethod("WriteData");
// now set the form values
setFormValues();
}
catch(RbException rbe) {
Status.setText("Error " + rbe.getType() + " -
"+rbe.getMessage());
return;
}
}

void clearButton_actionPerformed(ActionEvent e) {
// do the clear
try {
thisObj.callMethod("Clear");
// now set the form values
setFormValues();
}
catch(RbException rbe) {
Status.setText("Error " + rbe.getType() + " -
"+rbe.getMessage());
return;
}
}

private void getFormValues() {


thisObj.setProperty("FirstName", firstName.getText());
thisObj.setProperty("LastName", lastName.getText());
thisObj.setProperty("Salary", salary.getText());
thisObj.setProperty("HireDate", hireDate.getText());
thisObj.setProperty("Dept",
deptCodes.getValue(dept.getSelectedIndex()+1));
System.out.println(deptCodes.getValue(dept.getSelectedIndex()+1));
RedField temprf = new RedField(interest.getText());
// now convert line feeds into value marks
temprf.swap("\n", String.valueOf(RedField.VM));
thisObj.setProperty("Interests", temprf.getValue());
}

78 RedBeans
Applet Code Listing, EmpMaint.Java

void hireDate_focusLost(FocusEvent e) {
// validate this date. To this use validate date method from parent
applet
if(hireDate.getText().equals(""))
return;
String dateValue = validateDate(hireDate.getText(),
RBDApplet.INTLDATE);
if(dateValue == null) {
Status.setText("INVALID DATE INPUT, PLEASE RE-ENTER USING
DD/MM/YYYY");
hireDate.requestFocus();
}
else {
Status.setText("");
hireDate.setText(dateValue);
}

void salary_focusGained(FocusEvent e) {
// store orig value so that we can check salary if value changed
origSalaryValue = salary.getText();
}

void salary_focusLost(FocusEvent e) {
// now look to see if we need to validate salary on the server
if(origSalaryValue.equals(salary.getText()) || salary.get-
Text().equals(""))
return; // now change

thisObj.setProperty("Salary", salary.getText());
try {
thisObj.callMethod("ValidateSalary");

// look for server status to be set - this indicates


// application error
if(thisObj.getProperty("ServerStatus").equals("1")) {
Status.setText(thisObj.getProperty("ServerMessage"));
salary.requestFocus();
}
else
Status.setText("");
}
catch(RbException rbe) {

RedBeans 79
Appendix B - EmpMaint Code

Status.setText("Error - "+rbe.getType()+" - "+rbe.getMessage());


return;
}
}

void button1_actionPerformed(ActionEvent e) {
RBDDateFrame rdf = new RBDDateFrame(getFrame(this), "Employee Hire
Date");
rdf.setWeekendBackground(Color.black);
rdf.setWeekendForeground(Color.white);
rdf.setDateBackground(new Color(200, 200, 150));
rdf.setDateForeground(Color.black);
rdf.setBackground(Color.white);
rdf.DispFrame();
String selDate = rdf.getSelDate();
if(selDate.length() > 0)
hireDate.setText(selDate);
}

// call emp select display


void button2_actionPerformed(ActionEvent e) {
if(selectRunning)
return; // already running - they clicked twice on
// the button!
selectRunning = true;
EmpSelect es = new EmpSelect(getFrame(this), "Employee Select",
ourURL);
es.pack();
es.show();
if(es.hasSelected()) {
String s = es.getSelectedItem();
if(s != null) {
// set current employee id
empId.setText(s);
thisObj.setProperty("EmpId", empId.getText());
// now do the read
try {
thisObj.callMethod("ReadData");
// now set the form values
setFormValues();
}
catch(RbException rbe) {
Status.setText("Error - "+rbe.getType()+" -
"+rbe.getMessage());

80 RedBeans
Applet Code Listing, EmpMaint.Java

return;
}
}
}
selectRunning = false;
}

// receive an rbevent and display information


public void receiveRbEvent(RbEvent e) {
// get type and display information
if(e.getType() == RbEvent.DEBUG) {
// if we do not have debug display created then
// create it and show it now
if(debugDisplay == null) {
debugDisplay = new RedDebug(getFrame(this));
debugDisplay.show();
}
debugDisplay.displayDebugString(e.getText());
}
}
}

RedBeans 81
Appendix B - EmpMaint Code

JSP Code Listing, EmpMaint.JSP

Program Example

<%@ include file="rbodmain.inc"%>


<%@ include file="CheckSession.inc"%>
<%@include file="rbodemo.inc"%>
<%
RedBeans.RedObject obj = null; // handle to this page's redobject
RedBeans.RedField oDescs = null, oFld = null, oCodes = null;
session.putValue("pageDesc", "Employee Maintenance"); // used in error page
session.putValue("pageId", "EmpMaint.jsp"); // this page - used in error page
// serverMessage and serverStatus are set by server methods. errorMsg is used to
display messages
String serverMessage = "", serverStatus = "", errorMsg = "", warning = "";
String origSalary = ""; // stored in case of too high a salary

// if first time here then create the instance


if(session.getValue("empMaint") == null) { // set the connection, class name and
then open
// create redfields
oCodes = new RedBeans.RedField();
oDescs = new RedBeans.RedField();
oFld = new RedBeans.RedField();
obj = new RedBeans.RedObject();
session.putValue("empMaint", obj);
obj.setActiveConnection(connection);
obj.setRBOClass("OFFICE:Employee");
obj.open();
oCodes.setStringValue(obj.getProperty("DeptCodes"));
oDescs.setStringValue(obj.getProperty("DeptDescs"));
session.putValue("codes", oCodes);
session.putValue("descs", oDescs);
session.putValue("ofld", oFld);
// check for warning from server
warning = obj.getServerAlert();
}
else {
obj = (RedBeans.RedObject)session.getValue("empMaint");
oCodes = (RedBeans.RedField)session.getValue("codes");
oDescs = (RedBeans.RedField)session.getValue("descs");

82 RedBeans
JSP Code Listing, EmpMaint.JSP

oFld = (RedBeans.RedField)session.getValue("ofld");
}

// get action
String action = request.getParameter("action");
if(action == null)
action = "";
if(action.equals("ReadData")) {
obj.setProperty("EmpId", request.getParameter("EmpId"));
obj.callMethod(action);
}
else if(action.equals("WriteData")) {
// update properties before sending back to server
obj.setProperty("EmpId", request.getParameter("EmpId"));
obj.setProperty("FirstName", request.getParameter("FirstName"));
obj.setProperty("LastName", request.getParameter("LastName"));
obj.setProperty("HireDate", request.getParameter("HireDate"));
obj.setProperty("Salary", request.getParameter("Salary"));
oFld.setStringValue(request.getParameter("Interests"));
oFld.swap("\n", String.valueOf(oFld.getVM()));
obj.setProperty("Interests", oFld.getValue());
obj.callMethod(action);
}

else if(action.equals("ValidateSalary")) {
origSalary = obj.getProperty("Salary"); // get current salary in case new one
is too high
obj.setProperty("Salary", request.getParameter("Salary"));
obj.callMethod(action);
serverMessage = obj.getProperty("ServerMessage");
serverStatus = obj.getProperty("ServerStatus");
if(serverStatus.equals("1")) // reset salary
obj.setProperty("Salary", origSalary);

obj.setProperty("ServerMessage", "");
obj.setProperty("ServerStatus", "0");
}
else if(action.equals("ClearForm")) {
obj.callMethod("Clear");
}
// check for server status and message if no current error message from server
if(serverStatus.equals("1") && errorMsg.length() == 0)

RedBeans 83
Appendix B - EmpMaint Code

errorMsg = serverMessage;

%>

<HTML>
<HEAD>
<TITLE>RedBeans JSP Employee Maintenence</TITLE>
<SCRIPT>
var VM = unescape("%FD")
</SCRIPT>
</HEAD>

<SCRIPT language="JavaScript">
function SendToWebServer(action)
{
document.Form1.action = "EmpMaint.jsp?action=" + action;
document.Form1.submit();
}
</SCRIPT>

<BODY BGCOLOR="#FFFFFF">
<% if(errorMsg.length() > 0) { %>
<TABLE BGCOLOR=RED WIDTH='90%'><TD align=center><font color=yellow><b><%=
errorMsg%></b></font></TD></TABLE>
<% }%>
<% if(warning.length() > 0) { %>
<TABLE BGCOLOR=CYAN WIDTH='90%'><TD align=center><font color=blue><%=warn-
ing%></font></TD></TABLE>
<% }%>

<FORM NAME="Form1" METHOD=POST>


<TABLE CELLSPACING=0 CELLPADDING=3 BORDER=0 WIDTH=450 STYLE="font-fam-
ily:Arial;font-size:12">
<TR><TD COLSPAN=3 ALIGN="CENTER"><H3 STYLE="back-
ground:#D29B9E;color:#633132;font-family:Arial">Employee Mainte-
nance</H3></TD></TR>
<TR>
<TD nowrap>Employee ID</TD>
<TD>
<INPUT name="EmpId" size=5 value="<%=obj.getProperty("EmpId")%>" onChange=
SendToWebServer("ReadData")>
<A HREF="EmpLookup.jsp"><IMG height=30 src="/rbodemo/images/btn_lookup.jpg"
border=0></A>

84 RedBeans
JSP Code Listing, EmpMaint.JSP

</TD>
<TD vAlign=top width="59%" ROWSPAN=4 ALIGN="RIGHT">
<% String imageFile = obj.getProperty("ImageFile");
if(imageFile.equals(""))
imageFile = "onepixel.gif";
%>
<IMG height=121 src="/rbodemo/images/<%=imageFile%>" width=102>
</TD>

</TR>
<TR>
<TD>First Name</TD>
<TD>
<INPUT name="FirstName" size=25 value="<%=obj.getProperty("FirstName")%>">
</TD>
</TR>
<TR>
<TR>
<TD>Last Name</TD>
<TD>
<INPUT name="LastName" size=25 value="<%=obj.getProperty("Last-
Name")%>"> </TD>
</TR>
<TR>
<TR>
<TD>Hire Date</TD>
<TD>
<INPUT name="HireDate" size=10 value="<%=obj.getProperty("Hire-
Date")%>"> </TD>
</TR>
<TR>
<TR>
<TD>Salary</TD>
<TD>
<INPUT name="Salary" size=10 value="<%=obj.getProperty("Salary")%>"
onChange=SendToWebServer("ValidateSalary")>
</TD>
<TD vAlign=top width="20%" ROWSPAN=3 ALIGN="right">
<A HREF="JavaScript:SendToWebServer('WriteData')"><IMG height=30 src=
"/rbodemo/images/btn_accept.jpg" border=0><br></A>
<A HREF="JavaScript:SendToWebServer('ClearForm')"><IMG height=30 src=
"/rbodemo/images/btn_clear.jpg" border=0><br></A>
<A HREF="JavaScript:SendToWebServer('DeleteData')"><IMG height=30 src=
"/rbodemo/images/btn_delete.jpg" border=0><br></A>

RedBeans 85
Appendix B - EmpMaint Code

</TD>

</TR>
<TR>
<TR>
<TD vAlign=center>Department</TD>
<TD vAlign=top>
<SELECT name="Dept">
<%
String sel = "";
for(int i = 1;i <= oCodes.count(); i++) {
if(obj.getProperty("Dept").equals(oCodes.getValue(i)))
sel = "SELECTED";
else sel = "";
%>
<OPTION <%=sel%> VALUE=<%=oCodes.getValue(i)%> > <%=oDescs.getValue(i)%>
<% } %>
</SELECT>
</TD>
</TR>
<TR>
<TD vAlign=top>Interests</TD>
<TD WIDTH="59%" VALIGN="top">
<%
oFld.setStringValue(obj.getProperty("Interests"));
oFld.swap(String.valueOf(oFld.getVM()), "\n");
%>
<TEXTAREA name="Interests" wrap=off rows=4 cols=24> <%=
oFld.getValue()%></TEXTAREA>
</TD>
</TR>
</TABLE>
</FORM>

</BODY>
</HTML>

86 RedBeans
Appendix C - Stateless
Employee Enterprise
Bean

This chapter describes the setup and configuration of a Java stateless Enterprise Bean.

RedBeans 87
Appendix C - Stateless Employee Enterprise Bean

The Enterprise Beans is made up of three classes, the Bean itself, the Remote Interface and the
Home Interface

The Home Interface

Program Example

package RBJ2EEDemo;
/*
*
* Employee Home Interface
* Example code for RedBack RBODemo
*
*/

import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.RemoveException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;

/**
* Home Interface for stateless EJB that connects to RBO Employee, in RBODemo
*/

88 RedBeans
public interface EmployeeHome extends EJBHome {
/**
* required signature for create method, no arguments and therefore stateless
* @exception RemoteException by container
* @exception CreateException by container
*/
Employee create() throws RemoteException, CreateException;
}

The Remote Interface

Program Example

package RBJ2EEDemo;
/*
*
* Employee Remote Interface
*
* Example code for RedBack RBODemo
*
*/

import javax.ejb.EJBObject;
import java.rmi.RemoteException;
import java.util.Hashtable;
import RedBeans.*;

RedBeans 89
Appendix C - Stateless Employee Enterprise Bean

import RedBeansSvr.*;
import java.util.*;

/**
* This is the remote interface for a stateless EJB that communicates with
* the Employee RBO in RBODemo
*/
public interface Employee extends EJBObject {

/**
* Creates the RBO and triggers the Open()
* @param the object name in format Module:Classname
* @param url for RBODemo, can either be full http reference or
* JNI reference if jrgw being used.
* @returned session details to be retained and passed with further
* method calls by client
* @exception RemoteException by container
* @exception RbException by RedBeans if cannot connect to URL or open objname
*/
public Vector[] createObj(String objname, String url) throws RemoteException,
RbException;
/**
* Sets debug flag on
* @param flag, <code>true</code> will switch debug on, <code>false</code> will
* switch it off
* @exception RemoteException by container
*/
public void setDebugOn(boolean flag) throws RemoteException;
/**
* Method used to call RBO methods on RBO Server
* @param ourRbSession, current session details

90 RedBeans
* @param methodName, the name of the RBO method to call
* @returns updated state after the RBO method call
* @exception RemoteException by container
* @exception RbException by RedBeans if method cannot be called
*/
public Vector[] callMethod(Vector[] ourRbSession, String methodName) throws
RemoteException, RbException;
/**
* Gets current value of property from current state
* @param ourRbSession, current state
* @param name, the name of the property
* @returns the current value of the property
* @exception RemoteException by container
* @exception RbException by RedBeans if property cannot be found
*/
public String getProperty(Vector[] ourRbSession, String name) throws RemoteEx-
ception, RbException;
/**
* Sets current value of property from current state
* @param ourRbSession, current state
* @param name, the name of the property
* @param value, the value for the property
* @returns updated state after the property value has been set
* @exception RemoteException by container
* @exception RbException by RedBeans if property cannot be found
*/
public Vector[] setProperty(Vector[] ourRbSession, String name, String value)
throws RemoteException, RbException;
/**
* Does a read by calling <code>ReadData</code>
* @param ourRbSession, current state

RedBeans 91
Appendix C - Stateless Employee Enterprise Bean

* @param id, the employee id to be read


* @returns updated state after the read on the RBO server
* @exception RemoteException by container
* @exception RbException by RedBeans if employee id property cannot be found
or the ReadData could be called
*/
public Vector[] doRead(Vector[] ourRbSession, String id) throws RemoteExcep-
tion;
/**
* Gets the current value for the LastName property
* @param ourRbSession, current state
* @returns the current value for the LastName property
* @exception RemoteException by container
* @exception RbException by RedBeans if LastName property cannot be found
*/
public String getLastName(Vector[] ourRbSession) throws RemoteException;
/**
* Does a write by calling <code>WriteData</code>
* @param ourRbSession, current state
* @param id, the employee id of the item to be written
* @returns updated state after the write on the RBO server
* @exception RemoteException by container
* @exception RbException by RedBeans if the write could not take place
*/
public Vector[] doWrite(Vector[] ourRbSession, String id) throws RemoteExcep-
tion;
/**
* Gets the current value for the FirstName property
* @param ourRbSession, current state
* @returns the current value for the FirstName property
* @exception RemoteException by container

92 RedBeans
* @exception RbException by RedBeans if FirstName property cannot be found
*/
public String getFirstName(Vector[] ourRbSession) throws RemoteException;
/**
* Sets the current value for the LastName property within the current state.
This will not trigger
* a call to the RBO server
* @param ourRbSession, current state
* @param lastName, the value to be set
* @returns updated state after the last name has been set
* @exception RemoteException by container
* @exception RbException by RedBeans if LastName property cannot be found
*/
public Vector[] setLastName(Vector[] ourRbSession, String lastName) throws
RemoteException;
/**
* Sets the current value for the Dept property within the current state. This
will not trigger
* a call to the RBO server
* @param ourRbSession, current state
* @param dept, the value to be set
* @returns updated state after the dept has been set
* @exception RemoteException by container
* @exception RbException by RedBeans if dept property cannot be found
*/
public Vector[] setDept(Vector[] ourRbSession, String dept) throws RemoteExcep-
tion;
/**
* Sets the current value for the Employee Id property within the current
state. This will not trigger
* a call to the RBO server
* @param ourRbSession, current state

RedBeans 93
Appendix C - Stateless Employee Enterprise Bean

* @param empid, the value to be set


* @returns updated state after the employee id has been set
* @exception RemoteException by container
* @exception RbException by RedBeans if employee id property cannot be found
*/
public Vector[] setEmpId(Vector[] ourRbSession, String empid) throws RemoteEx-
ception;
/**
* Gets the current value for the Dept property
* @param ourRbSession, current state
* @returns the current value for the Dept property
* @exception RemoteException by container
* @exception RbException by RedBeans if Dept property cannot be found
*/
public String getDept(Vector[] ourRbSession) throws RemoteException;
}

The Bean

Program Example

package RBJ2EEDemo;
/*
*

94 RedBeans
* Employee EJB for use with RBO Employee in RBODemo Account
*
* Example code
*
*/
import java.rmi.RemoteException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.EJBException;
import java.util.*;
import RedBeans.*;
import RedBeansSvr.*;

/**
* Stateless EJB for Employee RBO in RBODemo
*/
public class EmployeeEJB extends RedBeansEJB implements SessionBean {

public EmployeeEJB() {}

/**
* Gets the current value for the LastName property
* @param ourRbSession, current state
* @returns the current value for the LastName property
* @exception RemoteException by container
* @exception RbException by RedBeans if LastName property cannot be found
*/
public String getLastName(Vector[] ourRbSession) {
String name = "";
try {

RedBeans 95
Appendix C - Stateless Employee Enterprise Bean

name = getProperty(ourRbSession, "LastName");


}
catch(RbException rbe) {
System.out.println("RbException on getLastName - " + rbe);
}
return name;
}

/**
* Gets the current value for the FirstName property
* @param ourRbSession, current state
* @returns the current value for the FirstName property
* @exception RemoteException by container
* @exception RbException by RedBeans if FirstName property cannot be found
*/
public String getFirstName(Vector[] ourRbSession) {
String name = "";
try {
name = getProperty(ourRbSession, "FirstName");
}
catch(RbException rbe) {
System.out.println("RbException on getFirstName - " + rbe);
}
return name;
}

/**
* Sets the current value for the Employee Id property within the current
state. This will not trigger
* a call to the RBO server
* @param ourRbSession, current state

96 RedBeans
* @param empid, the value to be set
* @returns updated state after the employee id has been set
* @exception RemoteException by container
* @exception RbException by RedBeans if employee id property cannot be found
*/
public Vector[] setEmpId(Vector[] ourRbSession, String empId) {
try {
ourRbSession = setProperty(ourRbSession, "EmpId", empId);
}
catch(RbException rbe) {
System.out.println("RbException on setempid " + rbe);
}
return ourRbSession;
}

/**
* Gets the current value for the Dept property
* @param ourRbSession, current state
* @returns the current value for the Dept property
* @exception RemoteException by container
* @exception RbException by RedBeans if Dept property cannot be found
*/
public String getDept(Vector[] ourRbSession) {
String dept = "";
try {
dept = getProperty(ourRbSession, "Dept");
}
catch(RbException rbe) {
System.out.println("RbException on getDept - " + rbe);
}

RedBeans 97
Appendix C - Stateless Employee Enterprise Bean

return dept;
}

/**
* Sets the current value for the LastName property within the current state.
This will not trigger
* a call to the RBO server
* @param ourRbSession, current state
* @param lastName, the value to be set
* @returns updated state after the last name has been set
* @exception RemoteException by container
* @exception RbException by RedBeans if LastName property cannot be found
*/
public Vector[] setLastName(Vector[] ourRbSession, String lastName) {
try {
ourRbSession = setProperty(ourRbSession, "LastName", lastName);
}
catch(RbException rbe) {
System.out.println("RbException on setlastname " + rbe);
}
return ourRbSession;
}

/**
* Sets the current value for the Dept property within the current state. This
will not trigger
* a call to the RBO server
* @param ourRbSession, current state
* @param dept, the value to be set
* @returns updated state after the dept has been set
* @exception RemoteException by container

98 RedBeans
* @exception RbException by RedBeans if dept property cannot be found
*/
public Vector[] setDept(Vector[] ourRbSession, String dept) {
try {
ourRbSession = setProperty(ourRbSession, "Dept", dept);
}
catch(RbException rbe) {
System.out.println("RbException on setDept " + rbe);
}
return ourRbSession;
}

/**
* Does a read by calling <code>ReadData</code>
* @param ourRbSession, current state
* @param id, the employee id to be read
* @returns updated state after the read on the RBO server
* @exception RemoteException by container
* @exception RbException by RedBeans if employee id property cannot be found
or the ReadData could be called
*/
public Vector[] doRead(Vector[] ourRbSession, String id) {
try {
ourRbSession = setProperty(ourRbSession, "EmpId", id);
ourRbSession = callMethod(ourRbSession, "ReadData");
}
catch(RbException rbe) {
System.out.println("could not do the read " + rbe);
}
catch(Exception e) {
System.out.println("Exception on read "+ e);

RedBeans 99
Appendix C - Stateless Employee Enterprise Bean

}
return ourRbSession;
}

/**
* Does a write by calling <code>WriteData</code>
* @param ourRbSession, current state
* @param id, the employee id of the item to be written
* @returns updated state after the write on the RBO server
* @exception RemoteException by container
* @exception RbException by RedBeans if the write could not take place
*/
public Vector[] doWrite(Vector[] ourRbSession, String id) {
try {
ourRbSession = setProperty(ourRbSession, "EmpId", id);
ourRbSession = callMethod(ourRbSession, "WriteData");

}
catch(RbException rbe) {
System.out.println("could not do the write " + rbe);
}
catch(Exception e) {
System.out.println("Exception on write "+ e);
}
return ourRbSession;
}

100 RedBeans
RedBeans 101
Appendix C - Stateless Employee Enterprise Bean

102 RedBeans
Appendix D - Stateful
Employee Enterprise
Bean

This chapter describes the setup and configuration of a Java stateful Enterprise Bean

RedBeans 103
Appendix D - Stateful Employee Enterprise Bean

The Enterprise Beans is made up of three classes, the Bean itself, the Remote Interface and the
Home Interface.

The Home Interface

Program Example

package RBJ2EEDemo;
/*
*
* Copyright 2000 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the proprietary information of Sun Microsystems, Inc.
* Use is subject to license terms.
*
*/

import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.RemoveException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;

public interface EmployeeSFHome extends EJBHome {

104 RedBeans
EmployeeSF create(String objName, String URL) throws RemoteException, CreateEx-
ception;
}

The Remote Interface

Program Example

package RBJ2EEDemo;
/*
*
* Copyright 2000 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the proprietary information of Sun Microsystems, Inc.
* Use is subject to license terms.
*
*/

import javax.ejb.EJBObject;
import java.rmi.RemoteException;
import java.util.Hashtable;
import RedBeans.*;
import RedBeansSvr.*;
import java.util.*;

RedBeans 105
Appendix D - Stateful Employee Enterprise Bean

public interface EmployeeSF extends EJBObject {


public void createObj() throws RemoteException, RbException;
public void setDebugOn(boolean flag) throws RemoteException;
public void callMethod(String methodName) throws RemoteException, RbException;
public String getProperty(String name) throws RemoteException, RbException;
public void setProperty(String name, String value) throws RemoteException,
RbException;
public void doRead(String id) throws RemoteException;
public String getLastName() throws RemoteException;
public void doWrite(String id) throws RemoteException;
public String getFirstName() throws RemoteException;
public void setLastName(String lastName) throws RemoteException;
public void setDept(String dept) throws RemoteException;
public void setEmpId(String empid) throws RemoteException;
public String getDept() throws RemoteException;
}

The Bean

Program Example

package RBJ2EEDemo;
/*

106 RedBeans
*
* Copyright 2000 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the proprietary information of Sun Microsystems, Inc.
* Use is subject to license terms.
*
*/
import java.rmi.RemoteException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.EJBException;
import java.util.*;
import RedBeans.*;
import RedBeansSvr.*;

public class EmployeeSFEJB extends RedBeansSFEJB implements SessionBean {

public String getLastName() {


//System.out.println("in getprop");
String name = "";
try {
name = getProperty("LastName");
}
catch(RbException rbe) {
System.out.println("RbException on getLastName - " + rbe);
}
catch(Exception e) {
name = "???";
}
return name;

RedBeans 107
Appendix D - Stateful Employee Enterprise Bean

public String getFirstName() {


//System.out.println("in getprop");
String name = "";
try {
name = getProperty("FirstName");
}
catch(RbException rbe) {
System.out.println("RbException on getFirstName - " + rbe);
}
return name;
}

public void setEmpId(String empId) {


try {
setProperty("EmpId", empId);
}
catch(RbException rbe) {
System.out.println("RbException on setempid " + rbe);
}
}

public String getDept() {


String dept = "";
try {
dept = getProperty("Dept");
}
catch(RbException rbe) {

108 RedBeans
System.out.println("RbException on getDept - " + rbe);
}
return dept;
}

public void setLastName(String lastName) {


try {
setProperty("LastName", lastName);
}
catch(RbException rbe) {
System.out.println("RbException on setlastname " + rbe);
}
}

public void setDept(String dept) {


try {
setProperty("Dept", dept);
}
catch(RbException rbe) {
System.out.println("RbException on setDept " + rbe);
}
}

public EmployeeSFEJB() {}

public void doRead(String id) {


try {
setProperty("EmpId", id);
callMethod("ReadData");

RedBeans 109
Appendix D - Stateful Employee Enterprise Bean

}
catch(RbException rbe) {
System.out.println("could not do the read " + rbe);
}
catch(Exception e) {
System.out.println("doaread e="+e);
}
}

public void doWrite(String id) {


try {
setProperty("EmpId", id);
callMethod("WriteData");
}
catch(RbException rbe) {
System.out.println("could not do the write " + rbe);
}
catch(Exception e) {
System.out.println("Exception found "+e);
}
}

public void ejbCreate() {


}

110 RedBeans
RedBeans 111
Appendix D - Stateful Employee Enterprise Bean

112 RedBeans
Appendix E - JSP &
Stateful Enterprise
Bean Example

This chapter describes a Client Bean used by JSP to reference a Stateful Employee Enterprise
Bean

RedBeans 113
Appendix E - JSP & Stateful Enterprise Bean Example

The Client Bean

Program Example

package RBJ2EEDemo;
/*
*
*
*/

import java.util.*;
import java.io.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import java.rmi.RemoteException;
import RedBeans.*;

public class EmployeeBean {

private String action;


private String id = "";
private String firstName = "";
private String lastName = "";
private String imageFile = "";
private EmployeeSFHome employeeHome;
private EmployeeSF employee;

114 RedBeans
private EmployeeSF emp;
private String URL = "http://localhost/scripts/rgw.dll/rbodemo";

public EmployeeBean() {
try {
Context ic = new InitialContext();
java.lang.Object objref = ic.lookup("SFEmployee");
employeeHome = (EmployeeSFHome) PortableRemoteObject.narrow(objref,
EmployeeSFHome.class);

emp = employeeHome.create("OFFICE:Employee", URL);


emp.createObj();

} catch (Exception re) {


System.err.println ("Couldn't locate Employee Home!");
}

public void setId(String id) {


this.id = id;
}

public String getId() {


return id;
}

RedBeans 115
Appendix E - JSP & Stateful Enterprise Bean Example

public void setImageFile(String imageFile) {


System.out.print("i=" + imageFile);
this.imageFile = imageFile;
}

public String getImageFile() {


if(imageFile.equals(""))
imageFile = "onepixel.gif";

return imageFile;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getFirstName() {


return firstName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

public String getLastName() {


return lastName;
}

public void processRequest() {

116 RedBeans
if(action == null) {
return;
}
else if(action.equals("ReadData")) {
try {
emp.doRead(id);
setLastName(emp.getLastName());
setFirstName(emp.getFirstName());
setImageFile(emp.getProperty("ImageFile"));
}
catch(RemoteException re) {
System.err.println("Remote Exception in read " + re);
}
catch(RbException rbe) {
System.err.println("RbException " + rbe);
}
}
return;
}
}

RedBeans 117
Appendix E - JSP & Stateful Enterprise Bean Example

A simple JSP example

Program Example

<html>
<jsp:useBean id="employeeBean" scope="session" class="RBJ2EEDemo.EmployeeBean"
/>

<jsp:setProperty name="employeeBean" property="*" />

<%! String status = "init"; %>

<% employeeBean.processRequest(); %>

<head>
<title>Employee JSP</title>
</head>

<h1><b><center>Employee JSP Example</center></b></h1>


<hr>

<SCRIPT language="JavaScript">
function SendToWebServer(action)
{
document.Form1.action = "RBEmp.jsp?action="+action;
document.Form1.submit();

118 RedBeans
}
</SCRIPT>
<body>
<form name=Form1 method=POST>
<BR>
<TABLE CELLSPACING=0 CELLPADDING=3 BORDER=0 WIDTH=450 STYLE="font-fam-
ily:Arial;font-size:12">
<TR><TD COLSPAN=3 ALIGN="CENTER"><H3 STYLE="back-
ground:#D29B9E;color:#633132;font-family:Arial">Employee Mainte-
nance</H3></TD></TR>
<tr><td>
Emp Id
</td>
<td><input type=text name=id onChange=SendToWebServer("ReadData") value=
<jsp:getProperty name="employeeBean" property="id" />></td>
<TD vAlign=top width="59%" ROWSPAN=4 ALIGN="RIGHT">
<IMG height=121 src=images/<jsp:getProperty name="employeeBean" property=
"imageFile"/> width=102>
</TD>
</tr>
<tr><td>First Name</td>
<td><input type=text name=firstName value=<jsp:getProperty name="employeeBean"
property="firstName"/>></td>
</tr>
<tr><td>Last Name</td>
<td><input type=text name=lname value=<jsp:getProperty name="employeeBean" prop-
erty="lastName" />></td>
</tr>
</table>
</form>

</body>
</html>

RedBeans 119
Appendix E - JSP & Stateful Enterprise Bean Example

120 RedBeans
A
accounturl, 23
activeconnection, 24, 25
Applet, 55

C
CallMethod, 53
callMethod, 53
Code example
Recordset example, 30
RedObject, 28
Write example, 29

D
Debug logging
RedObject, 52

E
Errors
RbException, 53

G
Gateway
Requestor, 16
getServerAlert, 53

H
HTML, 55

J
JSP, 11

M
Method
addNew, 33
callMethod, 26, 53
close, 34
count, 38
del, 40
getLength, 38
getProperty, 25, 34
getValue, 45
ins, 42
open, 32, 53
receiveRbEvent, 51
replace, 43
setProperty, 26, 34
setStringValue, 40
setSVM(), 40
setVM(), 40
swap, 44

O
open, 53

R
RbEvent, 50
Method, getText, 50
Method, getType, 50
RbEventListener, 51
Method, receiveRbEvent(RbEvent), 51
RbException, 54
Method, getType, 54
RBO, 17, 55
Class hierachy, 19
rboClass, 25
rboclass, 24
RBOScope
JSP, 12
RedBack Business Object, 17
RedBack Gateway
Requestor, 16
RedField
Method, count, 38
Method, del, 40
Method, getLength, 38
Method, getValue, 45
Method, ins, 42
Method, replace, 43
Method, setStringValue, 40
Method, setSVM(), 40
Method, setVM(), 40
Method, swap, 44
object, 37
RedObject, 23
accounturl, 23
activeConnection, 24, 25
Method, callMethod, 26
Method, getProperty, 25
Method, open, 25
Method, setProperty, 26
rboClass, 24, 25
RedSet
fieldNames, 33
Method, AddNew, 33
Method, addNew, 33
Method, close, 34
Method, getProperty, 34
Method, MoveFirst, 33
Method, MoveLast, 33
Method, MoveNext, 33
Method, MovePrevious, 33
Method, open, 32
Method, setProperty, 34
Using, 32
values, 33

S
sbObject, 20
Session Ids, 55
Symantec
Visual Café, 16

U
uObject, 20
uQuery, 20

V
Visual Café, 16
W
Web server, 11
RedBeans DRB-3006

Você também pode gostar