Getting Started With 4D Open for Java


ACI - Documentation Français English German ACI Technical Notes ACI Technical Notes, By Subject Back Previous Next Find

Getting Started With 4D Open for Java

By Jamras Komoncharoensiri, 4D, Inc. Technical Support

Technical Note 00-47

Technical Notes for Technical Notes for 00-10 October 2000

Introduction


This Technical Note explains the use of 4D Open for Java with 4D databases using a Web connection. It will also show you how 4D Open for Java fits between Java code and a 4D database. Throughout this Technical Note, I will primarily use Windows terminology. The actual example will work on any platform with a Java virtual machine.

The four main topics that are covered in this Technical Note are:

4D Open for Java and 4D Databases

Using 4D Open for Java

Examining class Employee

Running the Example

4D Open for Java and 4D Databases


4D Open for Java defines Java classes to represent database connections. It allows a Java programmer to connect to a 4D Server and to send and receive data with it. 4D Open for Java is written entirely in Java and will run on any Virtual Machine (under Windows, Unix, Linux, MacOS platforms). It consists of a package containing twenty-three Java classes (all compressed into a single jar file). To use Java Open you will need to add this jar file in your CLASSPATH when compiling and running your program. You can use it from any development environment, such as JDK 1.2 or later, Visual J++, J Builder, MRJ SDK 2.2, CodeWarrior, etc.

4D Open for Java allows you to connect to 4D Server databases from an applet, a stand alone, or other Java component. It will work with both Internet Explorer and Netscape Communicator on any platform.

Java programs call methods in the 4D Open for Java package to connect with databases through their drivers, then retrieve, process, and write information.

Figure 1: Where 4D Open for Java fits.

Using 4D Open for Java


There are three steps that all Java programs must follow in order to talk to a 4D database using 4D Open for Java.

1. Create a connection to a 4D database served by 4D Server (given an IP address or a URL).

2. Start a 4D process with the startProcess method.

3. Use the 4D Open for Java statements to execute commands, send and retrieve data.

Step 1: Creating a connection on the driver with the destination IP address or URL.

Your application program tells the driver manager to open a connection to the specified URL or IP address. This connection stays open until your program decides to close the connection.

Once a 4D Server is running over the network (assuming that you know the IP address of the remote 4D Server or, in the case of web serving, you will need to know the URL or IP address of that web server), you can open a connection to it by creating an instance of opDriverManager and pass it as a parameter to an opConnection object. A typical call is written as follows:

try{

opDriverManager drvrManager = new opDriverManager();

connection = drvrManager.getConnection (ipAddress);

}catch(opException e){

//Manage an error

}

Step 2: Starting a 4D Process.

Your program creates a process on the current connection to the database of interest. Each client program can create up to six simultaneous processes for one connection. For each connection opened, you must create at least one new process in the 4D Server database. To create a new process, use the startProcess method from the opConnection class as follows:

try{

process = connection.startProcess("Work Station","User Name","Password","Process Name" );

} catch(opException e){

//Manage an error

Step 3: Using 4D Open for Java statements to read/write a database.

Once you have a connection with your database, you can start sending 4D Open for Java statements across and getting results.

Queries and updates are sent across to the database in the form of Open for Java request statement. All these commands are methods of the opProcess class. Each request must be executed by the current process. The results are obtained in different ways, depending in the kind of the command. 4D Open for Java has methods to access individual rows by index and to get the data back as a String or some other data type.

When you have finished all the processing, stop the process and close the connection.

try{

connection.stopProcess(process);

connection.CloseConnection();

}catch(opException e){

//Manage an error

}

Examining class Employee


The class Employee is an applet which consists of one constructor and eight methods.

import java.util.*;

import java.lang.*;

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

import j4d.open.*;

public class Employee extends Applet

implements ActionListener, opConstants

{

// Declaration of objects and variables

// Class Constructor

public Employee() { . . . }

// Methods

public void doConnect() { . . . }

public void closeConnection() { . . . }

public void printDataArray(opDataArray DA[], int len) { . . . }

public void doPrint() { . . . }

public opDataArray[] getResult(opDataArray DA[], int num) { . . . }

public int getRecordNumber(TextField field) { . . . }

public void actionPerformed(ActionEvent event) { . . . }

public void init() { . . . }

}

Initialization


In the Employee database, the start up mode is set to the option "Start Without Context". When a user connects to the 4D Server, it launches Employee.html as the home page. The Employee.html calls up the Employee.class and performs the initialization.

public void init()

{

Panel clientPanel = new Employee();

}

The method init() is called when the applet is loaded into memory. It initializes GUI objects by calling the class constructor, public Employee(). The constructor builds the interfaces for the main page and all other pop-up windows at the same time.

public Employee()

{

// Initialize elements in the main page

// Initialize New Entry Window

// Initialize Search Window

// Initialize Delete Window

// Initialize Modify Window

connection = null;

table = new opTable();

}

Note: The pop up windows will not be displayed until the user makes an appropriate selection from the interface.

Once the applet has been initialized, it waits for the user to make his or her request. All requests are handled by a method called void actionPerformed(ActionEvent event).

public void actionPerformed(ActionEvent event)

{

. . .

try{

if(source == connectButton)

{

// Connecting to the database

}else if(source == quitButton)

{

// Close connection

}else if(source == displayButton)

{

// Display all records

}else if(source == searchButton)

{

// Display Search Window

}else if(source == searchButton2)

{

// Perform a search on the selected category with the input string

// Display the search result

}else if(source == addButton)

{

// Display New Entry Window

}else if(source == addButton2)

{

// Add the new entry to the table

}else if(source == deleteButton)

{

// Display Delete Window

}else if(source == deleteButton2)

{

// Delete the selected record from the table

}else if(source == modifyButton)

{

// Display Modify Window

}else if(source == modifyButton2)

{

// Modify the selected record with the new data

}

}catch(opException e){ . . . }

}

When the user clicks on the button, an event is sent to the applet indicating that the user performed an action. The actionPerformed method catches it and processes the user's interaction based on the type of action.

Figure 2: How the Browser communicates with the database

Note: At the initial state, the only request available to the user is the request to connect.

Processing Requests


Opening the connection:

The method doConnect handles the request for opening a connection between the applet and the database and creates a new process in the 4D Server database. It is called when the action "connectButton" is caught by the method actionPerformed.

public void doConnect()

{

String IP = "10.96.0.5"; // IP address of the server

drvManager = new opDriverManager();

try{

output.setText("Trying to Connect...");

connection = drvManager.getConnection(IP);

process = connection.startProcess("","User Name","","Employee.4DB");

output.setText("Connected...");

table.mTableNumber = 1;

process.RecordsInTable(table);

recordTotal = table.mRecordsInTable;

}catch(opException e){ . . . }

}

Terminating the connection:

When the method actionPerformed receives the action "quitButton", it calls the method closeConnection to close all the existing processes and the connection. In this example, only one process will be closed.

public void closeConnection()

{

try{

connection.stopProcess(process);

connection.CloseConnection();

}catch(opException e){ . . . }

}

Displaying all records in the table:

The method doPrint retrieves all data from the specified table and displays them in the text area in the applet. It will be called when the action "displayButton" is caught by the method actionPerformed.

public void doPrint()

{

try{

selection = process.AllRecords(table);

recordTotal = selection.mRecordsInSelection;

opDataArray dataArray[] =new opDataArray[5];

dataArray = getResult(dataArray,recordTotal);

printDataArray(dataArray,recordTotal);

}catch(opException e){ . . . }

}

Searching:

The searching mechanism is handled by two actions. The first action is the "searchButton" that was sent when the user clicked on the Search button on the main page. The method actionPerformed calls

searchFrame.show();

to display a Search Window. After the user has selected a search category, entered the text to be search in the search field, and clicked the Search button (the one in the Search Window), the second action will be caught by the method actionPerformed. This action is called "searchButton2". Once the actionPerformed method verifies that the action is "searchButton2", it executes the following code:

String strToSearch = searchField.getText();

if(!strToSearch.equals(""))

{

boolean isTrue;

int fnum;

/*******Get the number of field that the user*******

*******wants to perform the search searched*******/

if((isTrue=c1.getState()) == true)

fnum=1;

else if((isTrue=c2.getState()) == true)

fnum=2;

else if((isTrue=c3.getState()) == true)

fnum=3;

else if((isTrue=c4.getState()) == true)

fnum=4;

else

fnum=5;

/*******Perform Search*******/

selection = process.AllRecords(table);

opSearchArray searchArray = new opSearchArray(1);

searchArray.mSearchArray[0] = new opSearch(NONE,1,fnum,EQUAL,

new opData(ALPHANUMERIC,strToSearch));

selection = process.SearchInSelection(searchArray);

selection.mTableNumber = 1;

process.RecordsInSelection(selection);

int found = selection.mRecordsInSelection;

/*******Print the search result*******/

opDataArray dataArray[] = new opDataArray[5];

dataArray = getResult(dataArray,found);

printDataArray(dataArray,found);

}

searchField.setText("");

searchFrame.hide();

This code will make all records in the table the current selection. It creates a search array with the search criteria that the user has submitted. This search criteria will determine which field the search operation will be performed on. Once the search operation is finished, it returns the result in the form of the current selection which will be displayed in the text area.

Adding:

When the user makes a request to add by clicking on the Add button, the applet sends the action "addButton" to the actionPerformed method resulting the applet to display the New Entry Window (This procedure is similar to a search procedure). Once the user clicks on the Add button (in the Add Window), the actionPerformed method will execute the following code:

/*******Create a data array with data from the Add Window*******/

opDataArray dataArray = new opDataArray(5);

dataArray.mDataArray[0] = new opData(ALPHANUMERIC,fname.getText());

dataArray.mDataArray[1] = new opData(ALPHANUMERIC,lname.getText());

dataArray.mDataArray[2] = new opData(ALPHANUMERIC,dept.getText());

dataArray.mDataArray[3] = new opData(ALPHANUMERIC,job.getText());

dataArray.mDataArray[4] = new opData(ALPHANUMERIC,supervisor.getText());

/*******Create a new record*******/

process.CreateRecord(table,dataArray);

/*******Clear all text fields before closing the Add window*******/

fname.setText("");

lname.setText("");

dept.setText("");

job.setText("");

supervisor.setText("");

addFrame.hide();

Note: The action "addButton" will create and add a new record to the database even if the user did not enter data.

Deleting:

Deleting a record from the current selection requires that the user know the record number of the record he or she wants to delete. The record number is determined by a previous action such as Display and Search.

When the user clicks on the Delete button, the Delete Window will appear, asking for the record number to be deleted. This action is established by:

deleteFrame.show();

After the number has been entered and the Delete button is clicked, actionPerformed will execute the following code.

/****Get the record number that the user wants to delete****/

int tmp = getRecordNumber(deleteField);

/****If the requested number is valid, perform the deletion****

****otherwise do nothing********************************/

if(tmp+1>0 && tmp+1<=selection.mRecordsInSelection)

{

table.mRecordNumber = tmp; // Target record

selection.mCurrentRecord = tmp; // Target record

process.GotoSelectedRecord(selection);

process.DeleteRecord(table);

deleteField.setText("");

output.setText("Your deletion was successful!!!");

}else

output.setText("This record doesn't exist");

/*******Hide the Delete Window*******/

deleteFrame.hide();

Modifying:

Modifying a record from the current selection also requires that the user know the record number. When the user specifies the record number into the field and clicks on the Modify button on the main page, the actionPerformed method checks if the number is in the current selection. If it is, the program will start performing the modification on the specified record. The following code illustrates the modification process.

/****Get the record number that the user wants to modify****/

int tmp = getRecordNumber(recordNumberField);

/****If the requested number is valid, perform the Modification****

****otherwise do nothing***********************************/

if(tmp+1>0 && tmp+1<=selection.mRecordsInSelection)

{

/*******Display the modify window*******/

modifyFrame.show();

/******Create a data array with the current record in selection*******/

opDataArray dataArray[] =new opDataArray[5];

dataArray = getResult(dataArray,selection.mRecordsInSelection);

/******Display the current record on the Modify window*******/

firstField.setText(dataArray[0].mDataArray[tmp].mString);

lastField.setText(dataArray[1].mDataArray[tmp].mString);

departmentField.setText(dataArray[2].mDataArray[tmp].mString);

titleField.setText(dataArray[3].mDataArray[tmp].mString);

spField.setText(dataArray[4].mDataArray[tmp].mString);

}else

output.setText("This record doesn't exist in your selection");

Running the Example


This example database is a Web Serving example. It has a Java applet that talks to the 4D Server through 4D Open for Java. There are a few requirements that you have to follow in order to run this example.

Requirements


A. You will need to install an Internet Extension license on your machine. If you wish to run the example in the demo mode, 4D will let you run its Web Server for one hour before it expires.

B. When you downloaded the example database package from 4D website or installed it from the Partner CD, all files and folders must be stored in the Server machine and there should be a total of 9 files for the PC version and 7 files for the Macintosh version as shown in Figure 3:

Figure 3: Files and folders included in the Employee folder.

C. Your client machine must have an Internet connection or at least connect to the same network as the Server machine.

D. A Client uses an Internet Browser to connect to the Server; therefore you should have at least one of these two browsers: Internet Explorer or Netscape Communicator.

Set up the program to be used in your environment


Open Employee.java with any text editor.

Modify the existing IP address in the program with the IP address of your Server machine (Do not use 127.0.0.1, you must use the actual IP of that machine).

To obtain your IP address on Windows: Open the DOS command line and issue the command "ipcon."

To obtain your IP address on MacOS: Open the TCP/IP Control Panel.

Go to the method doConnect() and replace the existing IP address with your own.

public void doConnect()

{

String IP = "xxx.xxx.xxx.xxx" //Replace it with your Server IP

. . .

}

Save and compile the program to activate the new setting.

For compilation on Windows or Unix, you should be using JDK 1.2 or later. Please follow these steps:

Open a command-line window by getting a DOS prompt on Windows. Type the following line into the command line to compile the program:

javac -classpath "JOpen.jar" Employee.java

NOTE : An alternative is to directly add the JOpen.jar file to the CLASSPATH environment variable of your operating system. This way you do not have to type '-classpath JOpen.jar' whenever you compile or run your program.

For compilation on Macintosh, you should be using MRJ SDK 2.2. This Java Development Kit is not well known to most Java programmers yet. You can download a copy of MRJ SDK 2.2 at: ftp://ftp.apple.com/developer/Development_Kits/MRJ_SDK_2.2_Install.sit.bin

Once you have installed MRJ SDK 2.2 onto your Macintosh, you can do the following procedure to compile your Java code.

Open the MRJ SDK 2.2:Tools:JDK Tools folder. Inside that folder, you will see a program called "javac." Now drag and drop your Employee.java onto the Javac application. Javac will now open. Now follow the steps below.

1) Select the destination folder (usually the same folder as Employee.java).

2) Click the Add button in the Classpath area and open the Jopen.jar file.

3) Click the Do Javac button.

There should be no errors from this compilation. If there are, you probably typed something wrong in the file or the command. Correct the error and try again.

Note: Please ignore the warning that appears at the end of compilation. It only tells the user that there is a java method that was overridden by the programmer.

Launching 4D Server and the Client Applet


Now, everything should be set and ready for you to test. The following tour will take you through the usage of the Client Applet and the interaction between the Client user and the interface.

On the Server machine:

Start up your 4D Server with Employee.4DB (the same as any other 4D database). You should make sure that the Web Server is started.

On the Client machine:

Start up your Internet browser.

Connect to the Server machine by entering the Server IP Address in the Address field and pressing Enter.

The Employee applet appears in the browser as shown below.

Figure 4: Initial State

As you can see, the only option available at this time is Connect. This option allows the applet to make a connection to the database. Once you have established a connection to the Employee database, the rest of the options are enabled.

To establish a connection with the Employee database, click on the Connect button. If the Server has accepted your request for connection, you will see the message "Connected." in the text area.

Figure 5: After a connection has been established.

At this point, all other buttons are enabled and the Connect button has been disabled. Turning off the Connect button after the connection has been made is necessary. It prevents the user from overloading the Server with unnecessary processes. If the Connect button is active and it is clicked more than once, the Server will keep accepting a new connection and allow a new process to run on top of the old process.

To list all records on the table, click the Display button. The records will be listed as shown below.

Figure 6: Records listed in the text area.

- The Search button will display a Search window, in which you can search the database.

Figure 7: Search Window

The Search window is not case-sensitive. You can enter your search text with upper or lower case. The only requirement is that you must enter the entire search string.

For example:

To search in Job Title category, your search text could be "customer service rep", "technical support", etc.

To search in Supervisor category, your search text must include both first and last name, such as "Brendan Coveney".

The Add button on the main page displays a New Entry window, in which you can create a new record.

Figure 8: New Entry Window.

In the New Entry window, you can select one of three options:

1. The Add button adds the new record to the database. If you click the Add button without entering text into the fields, an empty record will be added to the database.

2. The Clear button clears all the data fields.

3. The Cancel button aborts the data entry.

The Delete button displays a dialog box in which you can delete a record by record number. Before you click the Delete button, you should find the record number of the record you want to delete. It can be found in front of each record that is displayed in the text area. The record numbers are not fixed. The previous operation, such as displaying or searching, will determine the record number in the current selection.

For example:

The Display operation makes all the records in the table the current selection and displays them in the text area. The list will be displayed in the order number of 1 (the first record in the selection) to N (the last record in the selection).

The Search operation displays all the records that match the search criteria in the text area. Suppose there three records are found; they will be set to the current selection. Each record is assigned a record number according to its order. In this case, 1 is assigned to the first, 2 is assigned to the second record, and 3 is assigned to the third record in the current selection.

Once you know the record number of the record you want to delete in the current selection, you can click the Delete button to display the Delete window.

Figure 9: Delete Window.

Enter the record number in the field and click the Delete button. You will then see a message "Your deletion was successful!!!" in the text field.

To modify a record, enter the record number that you want to modify in the input field next to the Modify button and click the Modify button.

The Modify window appears, displaying the record you want to modify.

Figure 10: Modify Window

When you finish modifying the data, click the Modify button to send the updated data to the database. All records are sent back to the client and displayed in the text area, including the record that has been modified.

To terminate the connection, click the Quit button. The applet will be disconnected from the Server. Once your connection is terminated, the text area will display a message "Connection has been terminated." and everything else will be set to the initial state as in Figure 4.

Summary


This technical note is a good start for those who are new to 4D Open for Java and the concept of open connection. It gives you an inside look of how 4D Open for Java works with a Java code and the 4D Server. It also gives you some basic ideas on how you can use applets to interact with 4D Server.

Nevertheless, the material in this technical note can useful to all Java programmers, regardless of level of experience.


ACI - Documentation Français English German ACI Technical Notes ACI Technical Notes, By Subject Back Previous Next Find