Essentials of the Java(TM) Programming Language, Part 2

Java Technology Home Page

A-Z Index Java Developer Connection(SM)

Online Training

Downloads, APIs, Documentation Java Developer Connection Tutorials, Tech Articles, Training Online Support Community Discussion News & Events from Everywhere Products from Everywhere How Java Technology is Used Worldwide Print Button

Essentials of the Java Programming Language: A Hands-On Guide, Part 2
TM

by Monica Pawlan
[CONTENTS] [NEXT>>]

This series of lessons builds on the material presented in JavaTM Programming Language Basics, Part 1, which introduced applications, applets, and servlets; simple file and database access operations; and remote method invocation (RMI). The lessons and code examples for Part 2 are somewhat more complex. They walk you through network communications, building a user interface using more components, data encryption and decryption (pseudo code only), grouping multiple data elements into one object (collections), and internationalizing a program. Part 2 concludes with some object-oriented programming concepts.

Contents
Lesson 1: Socket Communications
q q q q q q

What are Sockets and Threads? About the Examples Example 1: Server-Side Program Example 1: Client-Side Program Example 2: Multithreaded Server Example More Information About the Example Fruit Order Client Code
r r r r r

Lesson 2: User Interfaces Revisited
q q

Global Variables Constructor Event Handling Cursor Focus Converting Strings to Numbers and Back

q q q

Server Program Code View Order Client Code Program Improvements

file:///T|/General/Documentation/Java/Basic Java 2/HTML/index.html (1 of 3) [24.07.2000 12:33:21]

Essentials of the Java(TM) Programming Language, Part 2
q

More Information About the Example Running the Example Pseudo Code More Information About the Example Wrapping the Data Sending Data Server Program Receiving Data More Information About Collections Creating a Set Printing More Information Identify Culturally Dependent Data Create Keyword and Value Pair Files Internationalize Application Text Localize Numbers Compile and Run the Application Program Improvements More Information Setting up Class Packages
r r r r r

Lesson 3: Cryptography
q q q q

Lesson 4: Serialization
q q q q q q

Lesson 5: Collections
q q q q

Lesson 6: Internationalization
q q q q q q q

Lesson 7: Packages and Java Archive File Format
q

Create the Directories Declare the Packages Make Classes and Fields Accessible Change Client Code to Find the Properties File Compile and Run the Example Server Set of Files Fruit Order Client Set of Files View Order Client Set of Files More Information

q

Using JAR Files to Deploy
r r r r

file:///T|/General/Documentation/Java/Basic Java 2/HTML/index.html (2 of 3) [24.07.2000 12:33:21]

Essentials of the Java(TM) Programming Language, Part 2

Lesson 8: Object-Oriented Programming
q q q q q q q q q q

Object-Oriented Programming Defined Classes Objects Well-Defined Boundaries and Cooperation Inheritance Polymorphism Data Access Levels Your Own Classes Program Improvements More Information

In Closing

Reader Feedback
Tell us what you think of this training book and earn two DukeDollars. Very worth reading [Duke] reading Worth reading Not worth

If you have other comments or ideas for future training books, please type them here:

Submit

Reset

[TOP]

Print Button

[ This page was updated: 6-Apr-2000 ]

Products & APIs | Developer Connection | Docs & Training | Online Support Community Discussion | Industry News | Solutions Marketplace | Case Studies Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World FAQ | Feedback | Map | A-Z Index For more information on Java technology and other software from Sun Microsystems, call:

(800) 786-7638

Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.

Sun Microsystems, Inc. Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.

file:///T|/General/Documentation/Java/Basic Java 2/HTML/index.html (3 of 3) [24.07.2000 12:33:21]

The socket associates the server program with a specific hardware port on the machine where it runs so any client program anywhere in the network with a socket associated with that same port can communicate with the server program. A server program typically provides resources to a network of client programs. and the server program responds to the request. A thread is a sequence of instructions that file:///T|/General/Documentation/Java/Basic Java 2/HTML/socket. APIs. A multi-threaded program performs multiple tasks at one time such as fielding simultaneous requests from many client programs. This lesson presents a simple sockets-based program to introduce the concepts of sockets and multi-threaded programming. Client programs send requests to the server program. q What are Sockets and Threads? q q q q q About the Examples Example 1: Server-Side Program Example 1: Client-Side Program Example 2: Multithreaded Server Example More Information What are Sockets and Threads? A socket is a software endpoint that establishes bidirectional communication between a server program and one or more client programs.html (1 of 9) [24. Tech Articles.Java (TM) Language Basics. A multi-threaded server creates a thread for each communication it accepts from a client. Training Online Support Community Discussion News & Events from Everywhere Products from Everywhere How Java Technology is Used Worldwide Print Button Java Programming Language Basics. Documentation Java Developer Connection Tutorials. The RMI example allows multiple client programs to communicate with the same server program without any explicit code to do this because the RMI API is built on sockets and threads. One way to handle requests from more than one client is to make the server program multi-threaded. Lesson 1: Socket Communications Java Technology Home Page A-Z Index Java Developer Connection(SM) Online Training Downloads. Part 1.07. finished with a simple network communications example using the Remote Method Invocation (RMI) application programming interface (API).2000 12:33:27] . Part 2 TM Lesson 1: Socket Communications [<<BACK] [CONTENTS] [NEXT>>] JavaTM Programming Language Basics. Part 2.

07.html (2 of 9) [24. the text is sent to the server program. and continue listening for requests from other clients. Lesson 1: Socket Communications run independently of the program and of any other threads. Example 1 sets up a client and server communication between one server program and one client program. and when you click the Click Me button. start a thread for that communication. The client program expects an echo from the server and prints the echo it receives on its standard output. Lesson 6: File Access and Permissions. When you click the Click Me button. The server echoes the text it receives whether or not you click the Click Me button. Example 1: Client-Side Behavior The client program presents a simple user interface and prompts for text input. About the Examples The examples for this lesson consist of two versions of the client and server program pair adapted from the FileIO. The server program is not multi-threaded and cannot handle requests from more than one client.2000 12:33:27] . Part 2. start the server program first. Using threads. Example 1: Compile and Run To run the example programs. a multi-threaded server program can accept a connection from a client. file:///T|/General/Documentation/Java/Basic Java 2/HTML/socket. Example 1: Server-Side Behavior The server program presents a simple user interface. Example 2 converts the server program to a multi-threaded version so it can handle requests from more than one client.Java (TM) Language Basics.java application presented in Part 1. If you do not. the client program cannot establish the socket connection. the text received from the client is displayed.

println("Accept failed: 4321"). listenSocket Method The listenSocket method creates a ServerSocket object with the port number on which the server program is going to listen for client communications.Java (TM) Language Basics. javac SocketServer. It reads data sent to it and sends that same data back to the server in its actionPerformed method. } Then.java javac SocketClient.exit(-1).getOutputStream(). Part 2. For example. which means the number cannot be reserved or already in use. the server.out. out = new PrintWriter(client. public void listenSocket(){ try{ server = new ServerSocket(4321). System. } Next. the listenSocket method creates a Socket connection for the requesting client. The port number must be an available port.exit(-1). file:///T|/General/Documentation/Java/Basic Java 2/HTML/socket. } catch (IOException e) { System.accept().accept method returns a new Socket object. System. try{ client = server.out.2000 12:33:27] . the listenSocket method creates a BufferedReader object to read the data sent over the socket connection from the client program.java java SocketServer java SocketClient Example 1: Server-Side Program The server program establishes a socket connection on Port 4321 in its listenSocket method.07. This code executes when a client starts up and requests the connection on the host and port where this server program is running.getInputStream())).println("Could not listen on port 4321"). It also creates a PrintWriter object to send the data received from the client back to the server. } catch (IOException e) { System. try{ in = new BufferedReader(new InputStreamReader( client. Lesson 1: Socket Communications Here are the compiler and interpreter commands to compile and run the example. Unix systems reserve ports 1 through 1023 for administrative functions leaving port numbers greater than 1024 available for use.html (3 of 9) [24. When the connection is successfully established.

listenSocket Method The listenSocket method first creates a Socket object with the computer name (kq6py) and port number (4321) where the server program is listening for client connection requests.07.out. //Send data back to client out.out.2000 12:33:27] . Next.exit(-1). System. The actionPerformed method also receives the data back from the server and prints it to the command line.getSource(). while(true){ try{ line = in. This actionPerformed method uses the text stored in the line object to initialize the textArea object so the retrieved text can be displayed to the end user. and sends the data entered by the end user to the server program in its actionPerformed method. it creates a PrintWriter object to send data over the socket connection to the server program.Java (TM) Language Basics. public void listenSocket(){ file:///T|/General/Documentation/Java/Basic Java 2/HTML/socket.println(line). if(source == button){ textArea.readLine(). } catch (IOException e) { System.println("Read failed"). Lesson 1: Socket Communications true). the listenSocket method loops on the input stream to read data as it comes in from the client and writes to the output stream to send the data back. } } Lastly. } } actionPerformed Method The actionPerformed method is called by the Java platform for action events such as button clicks. System.html (4 of 9) [24. } catch (IOException e) { System.setText(line). It also creates a BufferedReader object to read the text sent by the server back to the client. } } Example 1: Client-Side Program The client program establishes a connection to the server program on a particular host and port number in its listenSocket method. Part 2. public void actionPerformed(ActionEvent event) { Object source = event.println("Read failed").exit(-1).

out. out. } catch (IOException e) { System. file:///T|/General/Documentation/Java/Basic Java 2/HTML/socket.println(text). Lastly. in = new BufferedReader(new InputStreamReader( socket.println("No I/O"). 4321). Lesson 1: Socket Communications //Create socket connection try{ socket = new Socket("kq6py". } catch (IOException e){ System. } } Example 2: Multithreaded Server Example The example in its current state works between the server program and one client program only.println(text).println("Unknown host: kq6py"). out = new PrintWriter(socket. textField.getOutputStream().setText(new String("")). This actionPerformed method code gets the text in the Textfield object and passes it to the PrintWriter object. public void actionPerformed(ActionEvent event){ Object source = event. } catch (UnknownHostException e) { System. which then sends it over the socket connection to the server program.println("Text received: " + line).07. System. System.2000 12:33:27] .exit(1). System. To allow multiple client connections. it receives the text sent back to it by the server and prints the text out. out. the server program has to be converted to a multithreaded server program.out.getInputStream())). true). Part 2. if(source == button){ //Send data over socket String text = textField.exit(1).html (5 of 9) [24.getSource(). } //Receive text from server try{ String line = in.out.out. System.getText().readLine().println("Read failed").exit(1). The actionPerformed method then makes the Textfield object blank so it is ready for more end user input. } } actionPerformed Method The actionPerformed method is called by the Java platform for action events such as button clicks.Java (TM) Language Basics.

html (6 of 9) [24. } catch (IOException e) { System.out. In this example the listenSocket method loops on the server. System. System. try{ //server.2000 12:33:27] .println("Could not listen on port 4444"). When running multiple threads. } while(true){ ClientWorker w.accept call waiting for client connections and creates an instance of the ClientWorker class for each client connection it accepts. Lesson 1: Socket Communications First Client Second Client Third Client The multithreaded server program creates a new thread for every client request.accept(). file:///T|/General/Documentation/Java/Basic Java 2/HTML/socket. you have to be sure that one thread cannot interfere with the data in another thread.start().out.accept returns a client connection w = new ClientWorker(server. textArea).exit(-1).exit(-1). The textArea component that displays the text received from the client connection is passed to the ClientWorker instance with the accepted client connection. Thread t = new Thread(w).println("Accept failed: 4444"). t. This way each client has its own connection to the server for passing data back and forth.07. } catch (IOException e) { System.Java (TM) Language Basics. public void listenSocket(){ try{ server = new ServerSocket(4444). Part 2.

Java (TM) Language Basics. three ClientWorker instances are created.println("in or out failed").append(line). this. Lesson 1: Socket Communications } } } The important changes in this version of the server program over the non-threaded server program are the line and client variables are no longer instance variables of the server class. try{ in = new BufferedReader(new InputStreamReader(client. but are handled inside the ClientWorker class. If three clients request connections. In this example. a thread is started for each ClientWorker instance. //Send data back to client out. } while(true){ try{ line = in. true). sends the data it receives back to the client. JTextArea textArea) { this.07. } file:///T|/General/Documentation/Java/Basic Java 2/HTML/socket.textArea = textArea.exit(-1). run.println("Read failed").client = client. Part 2. } public void run(){ String line. System. }catch (IOException e) { System.println(line). which has one method. //Append data to text area textArea. private JTextArea textArea. class ClientWorker implements Runnable { private Socket client. PrintWriter out = null.html (7 of 9) [24. } catch (IOException e) { System.getOutputStream(). The run method executes independently in each thread. BufferedReader in = null.2000 12:33:27] . //Constructor ClientWorker(Socket client.out. loops on the input stream waiting for input from the client.out. out = new PrintWriter(client. The ClientWorker class implements the Runnable interface. the run method creates the input buffer and output writer. and the run method executes for each thread.getInputStream())).exit(-1).readLine(). System. and sets the text in the text area.

html (8 of 9) [24. } } More Information You can find more information on sockets in the All About Sockets section in The Java Tutorial. Multi-threaded programs should close all Files and Sockets they use before exiting so they do not face resource starvation. The call to server. The finalize() method is called by the Java virtual machine (JVM)* before the program exits to give the program a chance to clean up and release resources.Java Store .append(line). System. [TOP] Print Button [ This page was updated: 31-Mar-2000 ] Products & APIs | Developer Connection | Docs & Training | Online Support Community Discussion | Industry News | Solutions Marketplace | Case Studies Glossary .Tutorial . which means its implementation includes code that allows one thread to finish its append operation before another thread can start an append operation.Java (TM) Language Basics.exit(-1).close().append method were not thread safe.println("Could not close socket"). } catch (IOException e) { System.2000 12:33:27] . you would need to wrap the call to textArea.out. Lesson 1: Socket Communications } } } The JTextArea.close() in the finalize() method closes the Socket connection used by each thread in this program.Applets . Part 2.Java in the Real World FAQ | Feedback | Map | A-Z Index file:///T|/General/Documentation/Java/Basic Java 2/HTML/socket. protected void finalize(){ //Objects created in run method are finalized when //program terminates and thread exits try{ server.append method is thread safe. This prevents one thread from overwriting all or part of a string of appended text and corrupting the output.Business & Licensing .append(line) with a call to appendText(line): public synchronized void appendText(line){ textArea.07.Employment . } The synchronized keyword means this thread has a lock on the textArea and no other thread can change the textArea until this thread finishes its append operation. If the JTextArea.append(line) in a synchronized method and replace the run method call to textArea.

Lesson 1: Socket Communications For more information on Java technology and other software from Sun Microsystems. Sun Microsystems.2000 12:33:27] . Privacy Policy.07.Java (TM) Language Basics. Copyright © 1995-2000 Sun Microsystems. file:///T|/General/Documentation/Java/Basic Java 2/HTML/socket. call: (800) 786-7638 Outside the U. Part 2. All Rights Reserved. Inc.html (9 of 9) [24.S. dial your country's AT&T Direct Access Number first. Terms of Use. and Canada. Inc.

html (1 of 13) [24. q About the Example q Fruit Order Client Code r r r r r Instance Variables Constructor Event Handling Cursor Focus Converting Strings to Numbers and Back q q q q Server Program Code View Order Client Code Program Improvements More Information About the Example This is a very simple electronic commerce example for instructional purposes only. APIs. You also learned how to use the Remote Method Invocation (RMI) application programming interface (API) to send data from a client program to a server program on the net where the data can be accessed by other client programs.Java (TM) Language Basics. Part 2 TM Lesson 2: User Interfaces Revisited [<<BACK] [CONTENTS] [NEXT>>] In JavaTM Programming Language Basics. and one server program that makes order information available to clients that view the orders. Lesson 2: User Interfaces Revisited Java Technology Home Page A-Z Index Java Developer Connection(SM) Online Training Downloads.07. Fruit Order Client file:///T|/General/Documentation/Java/Basic Java 2/HTML/ui. Part 2. These changes give you the beginnings of a very simple electronic-commerce application that consists of two types of client programs: one lets end users place purchase orders and the other lets order processors view the orders. one for ordering fruit and another for viewing the order. Part 1.2000 12:33:33] . Lesson 8: Remote Method Invocation. you learned how to use Java Foundation Classes (JFC) Project Swing (Project Swing) components to build a simple user interface with very basic backend functionality. and uses a different layout manager. This lesson takes the RMI application from Part 1. Tech Articles. It consists of three programs: two client programs. Training Online Support Community Discussion News & Events from Everywhere Products from Everywhere How Java Technology is Used Worldwide Print Button Java Programming Language Basics. creates a more involved user interface. Documentation Java Developer Connection Tutorials.

the program gets the order data from the server program and puts it on the screen. In this example. When the end user clicks Purchase. and view order clients call the get methods to retrieve the data. all values entered into the form are sent to the server program.html (2 of 13) [24. the server program has no user interface. The Tab key or mouse moves the cursor to the next field. The end of this lesson asks you to change the code so there is no danger incorrect totals are sent across the net because the end user did not press the Return key. If the Return key is not pressed. After the end user enters the number of each item to order.25 each. The end user must press the Return key for the total to update. Lesson 2: User Interfaces Revisited The FruitClient program presents a user interface and prompts the end user to order apples. peaches. At the bottom. View Order Client The OrderClient program presents a user interface. Fruit order clients call send methods to send data to the server. an incorrect total is sent across the net with the order.2000 12:33:33] . the end user provides a credit card number and customer ID. and pears at $1.07.Java (TM) Language Basics. and when the end user clicks View Order. Part 2. Server Program The RemoteServer program provides remotely accessible send and get methods. he or she presses the Return key to commit the order and update the running total. file:///T|/General/Documentation/Java/Basic Java 2/HTML/ui.

class /home/zelda/public_html/classes cp Send. Lesson 2: User Interfaces Revisited Compile and Run the Example See Part 1. Part 2. but use the source code provided in this lesson.java javac RMIClient1. Use the Part 1. Lesson 8 instructions.class \home\zelda\public_html\classes copy Send. Unix: cd /home/zelda/classes javac Send.class \home\zelda\public_html\classes Start rmi Registry: Unix: cd /home/zelda/public_html/classes unsetenv CLASSPATH rmiregistry & file:///T|/General/Documentation/Java/Basic Java 2/HTML/ui.java rmic -d .class /home/zelda/public_html/classes Win32: cd \home\zelda\classes javac Send.java javac RemoteServer.java javac RemoteServer. RemoteServer cp RemoteServer*. for information on how to run the example.2000 12:33:33] . Lesson 8: Remote Method Invocation.07.html (3 of 13) [24.java javac RMIClient1.java rmic -d . RemoteServer copy RemoteServer*.java javac RMIClient2.java javac RMIClient2.Java (TM) Language Basics. Here is a summarized version of those steps: Compile: These instructions assume development is in the zelda home directory.

server.com\home\zelda\public\html Start RMIClient2: Unix: cd /home/zelda/classes java -Djava.com Win32: cd \home\zelda\classes java -Djava.server.com file:///T|/General/Documentation/Java/Basic Java 2/HTML/ui.eng.hostname=kq6py.policy RMIClient1 kq6py.com -Djava.rmi. Part 2.sun.eng.eng.rmi.rmi.policy RemoteServer Win32: cd \home\zelda\public_html\classes java -Djava.rmi.server.com/~zelda Win32: cd \home\zeldzeldaa\classes java -Djava.sun.policy RemoteServer Start RMIClient1: Unix: cd /home/zelda/classes java -Djava.rmi.security.server.sun.codebase=http://kq6py/~zelda/classes -Djava.eng.07.codebase= http://kq6py/~zelda/classes -Djava.hostname=kq6py.sun.rmi.policy=java.com -Djava.html (4 of 13) [24.server.rmi.hostname=kq6py.security.rmi.sun.policy RMIClient2 kq6py.eng.Java (TM) Language Basics.security.policy=java.codebase= file:c:\home\zelda\public_html\classes -Djava.sun.server.server.codebase= file:c:\home\zelda\public_html\classes -Djava.rmi.eng.rmi.sun.security. Lesson 2: User Interfaces Revisited Win32: cd \home\zelda\public_html\classes set CLASSPATH= start rmiregistry Start Remote Server: Unix: cd /home/zelda/public_html/classes java -Djava.security.codebase= file:c:\home\zelda\classes\ -Djava.policy RMIClient1 kq6py.policy=java.codebase= http://kq6py/~zelda/classes/ -Djava.eng.server.server.2000 12:33:33] .com -Djava.policy=java.policy=java.server.hostname=kq6py.

JTextField creditCard. cardNum. and pears order into the text fields and presses the Return key after each fruit entry. JTextArea items. totalItems.com Fruit Order Client Code The RMIClient1.policy RMIClient2 kq6py. and the underlying total cost and items variables. applechk. custID. user interface components are arranged in a 2-column grid with labels in the left column. When the Return key is pressed. peachchk. On the display. static Send send.sun. cost. int itotal=0.Java (TM) Language Basics.eng. The end user enters his or her apples. double icost=0.java code uses label. peaches. the text field behavior updates the item and cost totals displayed in the text areas.07. and button components to create the user interface for ordering fruit. JLabel JLabel JLabel JLabel col1. they are built in the SwingUI constructor and accessed in the actionPerformed method implementation. reset. pearqnt. Instance Variables These next lines declare the Project Swing component classes the SwingUI class uses. col2. text field. Part 2. file:///T|/General/Documentation/Java/Basic Java 2/HTML/ui. null values are sent over the network. In this example. peachqnt.html (5 of 13) [24. customer.policy=java. JTextField appleqnt. The Reset button behavior clears the display. The Purchase button behavior sends the order data to the server program. totalCost.2000 12:33:33] . and the input and output data fields (text fields and text areas) aligned in the right column. Lesson 2: User Interfaces Revisited -Djava. JButton purchase. text area.security. pearchk. If the Reset button is clicked before the Purchase button. These are instance variables that can be accessed by any method in the instantiated class. JPanel panel.

cardNum = new JLabel(" Credit Card:"). items = new JTextArea(). A panel is a container component that holds other components. an action event occurs that causes the platform to call the FruitClient. //Create labels and text area components totalItems = new JLabel("Total Items:").actionPerformed method where the behaviors for these components are defined.addActionListener(this). Part 2. and as a result. custID = new JLabel(" Customer ID:"). This means when the end user clicks one of the buttons or presses Return in one of the text fields. pearqnt = new JTextField(). and peachQnt text fields are added as action listeners. file:///T|/General/Documentation/Java/Basic Java 2/HTML/ui. //Create labels and text field components applechk = new JLabel(" Apples"). customer = new JTextField(). appleqnt. cost = new JTextArea(). Lesson 2: User Interfaces Revisited Constructor The constructor is fairly long because it creates all the components. pearchk = new JLabel(" Pears").addActionListener(this). peachqnt = new JTextField().07.Java (TM) Language Basics. col2 = new JLabel("Specify Quantity"). peachchk = new JLabel(" Peaches"). purchase. The Reset and Purchase buttons and the appleQnt. appleqnt = new JTextField().addActionListener(this).2000 12:33:33] . //Create buttons and make action listeners purchase = new JButton("Purchase"). peachqnt. creditCard = new JTextField(). pearqnt. a class declares the ActionListener interface and implements the actionPerformed method if it needs to handle action events such as button clicks and text field Returns. totalCost = new JLabel("Total Cost:").html (6 of 13) [24.addActionListener(this). //Create left and right column labels col1 = new JLabel("Select Items"). pearQnt. and places the components in the grid on a panel. As explained in Part1. require you to implement different interfaces and methods. Lesson 4: Building a User Interface. sets the layout to a 2-column grid. Other user interface components generate some different action events.

panel.add(pearchk).add(panel).setLayout(new GridLayout(0.add(totalItems). The example in Part 1. //Create a panel for the components panel = new JPanel(). file:///T|/General/Documentation/Java/Basic Java 2/HTML/ui.Java (TM) Language Basics.2)). A content pane lets different types of components work together in Project Swing.. panel. panel.add(cardNum).add(creditCard). //Set panel layout to 2-column grid //on a white background panel. panel. panel.white). In the next lines. The layout manager determines how user interface components are arranged on the panel.add(pearqnt). panel. Lesson 2: User Interfaces Revisited reset = new JButton("Reset"). This example uses the GridLayout layout manager.add(peachchk). panel.addActionListener(this).add(applechk). which arranges components in a grid or the number of rows and columns you specify.add(cost). Lesson 4: Building a User Interface. The layout manager and color are set on the panel. panel. a JPanel component is created and added to the top-level frame.add(peachqnt).add(customer). The example uses a 2-column grid with an unlimited number of rows as indicated by the zero (unlimited rows) and two (two columns) in the statement panel.add(col2). Part 2. used the BorderLayout layout manager. panel. reset.setLayout(new GridLayout(0.add(items).2000 12:33:33] .add(totalCost).add(col1). panel.07. panel. and the panel is added to the content pane with a call to the getContentPane method of the JFrame class. and the layout manager and background color for the panel are specified. panel.2)). //Add components to panel columns //going left to right and top to bottom getContentPane(). panel.html (7 of 13) [24.setBackground(Color.add(custID). panel. panel. panel.add(appleqnt). panel.

using the number to calculate the cost. and sending that data to the server program.getText(). pears = pearqnt. adding the number to the items total.Java (TM) Language Basics. peachQnt.sendAppleQnt(apples).getText(). and adding the cost for pears to the total cost.sendTotalItems(itotal). try{ send. send.println("Cannot send data to server").sendTotalCost(icost).07.sendCustID(custID). custID = customer. Rather than show the entire actionPerformed method here. Lesson 2: User Interfaces Revisited panel. if(source == purchase){ cardnum = creditCard. or pearQnt field. Two interesting things in this code involve managing the cursor focus and converting strings to numbers for the calculations. } catch (Exception e) { System.getText(). send. The send variable is declared static and global in the FruitClient program so the static main method can instantiate it. send.sendCreditCard(cardnum). Purchase Button: The Purchase button behavior involves retrieving data from the text fields and text areas.out.add(purchase). Part 2.sendPeachQnt(peaches). The send variable is an instance of the Send interface. } } pearQnt Text Field: The pearQnt text field behavior involves retrieving the number of pears the end user wants to order.2000 12:33:33] .sendPearQnt(pears). Both topics are covered below.getText().getText(). this section describes the purchase button and pearQnt text field behaviors only.add(reset). send. Event Handling The actionPerformed method provides behavior for each of the following possible application events: q The mouse is clicked on the Purchase or Reset button. which declares the remote server methods for sending and getting data. The Reset button is similar to the purchase button. panel. apples = appleqnt. and to make it accessible to the actionPerformed method. q The Return key is pressed inside the appleQnt. The server program is available to the FruitClient program through its Send interface. This instance is created in the FruitClient program's main method. send. and the other text fields are similar to pearQnt.html (8 of 13) [24. send. peaches = peachqnt. file:///T|/General/Documentation/Java/Basic Java 2/HTML/ui.

and pearQnt text fields have to be converted to their number equivalents. the string values retrieved from the appleQnt. the end user pressed Return file:///T|/General/Documentation/Java/Basic Java 2/HTML/ui. pearqnt. itotal += pearsNo. pearqnt.2000 12:33:33] . Because the end user does not interact with the text areas. Converting Strings to Numbers and Back To calculate the items ordered and their cost. pearchk = new JLabel(" Pears"). peachqnt = new JTextField(). If the length is not greater than zero. pearqnt = new JTextField(). creditCard = new JTextField(). } else { itotal += 0. Lesson 2: User Interfaces Revisited if(source == pearqnt){ number = pearqnt.length() > 0){ pearsNo = Integer. The default Tab key movement steps through all user interface components including the text areas. customer = new JTextField().addActionListener(this).addActionListener(this). the string length is checked. Part 2.addActionListener(this).valueOf(number). peachqnt. The example program includes a call in its constructor to pearqnt. pearqnt.Java (TM) Language Basics. The string value is returned in the number variable.setNextFocusableComponent(creditCard).setNextFocusableComponent to make the cursor move from the pearqnt text field to the creditcard text field bypassing the total cost and total items text areas when the Tab key is pressed. custID = new JLabel(" Customer ID:"). To be sure the user actually entered a value.setNextFocusableComponent(creditCard). if(number. //Make cursor go to creditCard component pearqnt.getText(). applechk = new JLabel(" Apples"). peachchk = new JLabel(" Peaches").setNextFocusableComponent(creditCard). peachQnt. appleqnt = new JTextField(). cardNum = new JLabel(" Credit Card:"). there is no reason for the cursor to go there. } } Cursor Focus End users can use the Tab key to move the cursor from one component to another within the user interface.intValue(). appleqnt.html (9 of 13) [24.07.

the int and double data types are not classes. This string is passed to the call to this. Part 2. They are primitive data types. all data types used in the examples have been classes. For example. The int data type contains a single whole 32-bit integer value that can be positive or negative. You can use the standard arithmetic operators (+. To display the total items. not only contains a whole 32-bit integer value that can be positive or negative. this. a java. you have to reference it as this. this. The Integer class.lang.setText(text). Adding zero is not really necessary. the Integer. Lesson 2: User Interfaces Revisited without entering a value.Integer object is created from the itotal integer variable. Next.2000 12:33:33] . *.25). an instance of the java.Java (TM) Language Basics.intValue method lets you convert an Integer to an int to perform arithmetic operations. If the length is greater than zero. In this case. Until now. } else { itotal += 0. text2 = cost.items. text = num. but provides methods for working on the value.intValue() method is called to produce the integer (int) equivalent of the string value so it can be added to the items total kept in the itotal integer variable. if(number. but does make the code more understandable for someone reading it.lang. the totals have to be converted back to strings.setText(text2).toString(). cost = new Double(icost). The double data type contains a 64-bit double-precision floating file:///T|/General/Documentation/Java/Basic Java 2/HTML/ui.cost. To reference the global text area and not the local Double by the same name.length() > 0){ pearsNo = Integer. itotal += pearsNo. -.cost.html (10 of 13) [24.toString method is called to produce the String equivalent of the integer (int).cost because the actionPerformed method also has a cost variable of type Double. and /) to perform arithmetic operations on the integer.Integer class is created from the string.cost. the Integer. num = new Integer(itotal). The code at the end of the actionPerformed method shown below does this.toString().intValue().setText(text2) to update the Total Cost field in the display.07.valueOf(number). } To display the running item and cost totals in their respective text areas. the else statement adds zero to the running total and the cursor focus is set for the creditCard text field. icost = (itotal * 1. But. The Integer. Note: The cost text area variable is referenced as this.

} q public double getTotalCost(){return cost.} q public String getPearQnt(){return pears. Server Program Code The server program consists of the RemoteServer. this section highlights two parts of the actionPerformed method behavior for viewing an order.} q public String getAppleQnt(){return apples.} q public void sendAppleQnt(String apps){apples = apps.} q public String getPeachQnt(){return peaches. The first part retrieves the credit card number. Lesson 2: User Interfaces Revisited point value. the Double. Lesson 8: Remote Method Invocation with the only difference being in this lesson there are many more sendXXX and getXXX methods to declare and implement. No special handling is needed for large amounts of data or special considerations for different data types. } q public void sendTotalItems(int itm){items = itm.} q public void sendPearQnt(String prs){pears = prs. which can sometimes be issues when using socket communications.Java (TM) Language Basics. and the file:///T|/General/Documentation/Java/Basic Java 2/HTML/ui.2000 12:33:33] .java class so rather than repeat much of what you have read above. Here is the list: q public void sendCreditCard(String creditcard){cardnum = creditcard.} q public void sendTotalCost(double cst){cost = cst.} q public void sendPeachQnt(String pchs){ peaches = pchs.java interface. for example.} q public void sendCustID(String cust){custID = cust. View Order Client Code The OrderClient. The Double class not only contains a 64-bit double-precision floating point value. The code is very similar to the FruitOrder. These classes are described in Part 1.html (11 of 13) [24.doubleValue method lets you convert a Double to a double to perform arithmetic operations.} The important thing to note is data of any type and size can be easily passed from one client through the server to another client using the RMI API. but provides methods for working on the value. Part 2.07.} q public String getCreditCard(){return cardnum.} q public int getTotalItems(){return items.java class uses text areas and buttons to display the order information.java class that implements the methods declared in the Send.} q public String getCustID(){return custID.

setText(text).println("Cannot send data to server"). text = send. itms = new Integer(items). peachesNo. The second part retrieves the cost and item totals.getCreditCard().Double object.getPeachQnt(). Finally. icost.setText(text).setText(i). text = send. The first one involves the need to press the Return key for calculations to happen. text = send. peaches. pearsNo.getTotalItems(). applesNo. itotal. i = itms. and pears ordered from the server and sets those values in the corresponding text areas.getPearQnt().Integer object. which are double and integer.setText(text). and file:///T|/General/Documentation/Java/Basic Java 2/HTML/ui.2000 12:33:34] . creditNo. customerNo. if(source == view){ try{ //Retrieve and display text text = send. //Convert Numbers to Strings cost = send. price = new Double(cost). } } Program Improvements The example program as it is currently written has two major design flaws in the fruit order client. respectively. peaches.setText(text).toString(). unit = price.07. the strings can be used to set the values for the corresponding text areas.html (12 of 13) [24.getCustID().setText(text).out.getAppleQnt(). } catch (Exception e) { System. items = send.getTotalCost(). Lesson 2: User Interfaces Revisited number of apples. Part 2. and the total items to a java.Java (TM) Language Basics. and the second involves handling the error condition if the end user enters a character that is not a number when ordering apples. It then converts the total cost to a java.lang.setText(unit). and calls the toString method on each to get the string equivalents.toString(). text = send.lang.

try and catch blocks were first introduced in Part 1. So. call: (800) 786-7638 Outside the U.lang.S. Give it a try before taking a look. All Rights Reserved.Applets . The error you need to catch is java. Inc. in this particular application relying on the Return key action event is not good design. Copyright © 1995-2000 Sun Microsystems. or pears the program will present a stack trace indicating an illegal number format. and Canada.07. peaches.Java (TM) Language Basics. peaches. Inc. no calculation is made.2000 12:33:34] . file:///T|/General/Documentation/Java/Basic Java 2/HTML/ui. Give it a try before taking a look at the solution. rather than produce a stack trace. Calculations and Pressing Return: If the end user enters a value for apples. Sun Microsystems. *As used on this web site.NumberFormatException.Java in the Real World FAQ | Feedback | Map | A-Z Index For more information on Java technology and other software from Sun Microsystems.Java Store .Employment . The Variables and Data Types trail in The Java Tutorial provides more information on primitive data types. A good program will catch and handle the error. Non-Number Errors: If the end user enters a non-number value for apples. More Information You can find more information on event listening in the Writing Event Listeners lesson in The Java Tutorial.Business & Licensing . See The JFC Swing Tutorial: A Guide to Constructing GUIs for more information on Project Swing. the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform. This means when the end user clicks the Purchase key. the order is sent. [TOP] Print Button [ This page was updated: 31-Mar-2000 ] Products & APIs | Developer Connection | Docs & Training | Online Support Community Discussion | Industry News | Solutions Marketplace | Case Studies Glossary . dial your country's AT&T Direct Access Number first. Modify the actionPerformed method so this does not happen. but the item and cost totals will be incorrect.Tutorial . Hint: You need to figure out which part of the code throws the error and enclose it in a try and catch block. Terms of Use. Privacy Policy. or pears and moves to the next field without pressing the Return key.html (13 of 13) [24. Part 2. Lesson 6: File Access and Permissions. Lesson 2: User Interfaces Revisited pears. Here is one possible solution.

This lesson adapts the Part 2. and decrypt it on the other side. q q q About the Example Running the Example Pseudo Code r r r r Server Generating the Public and Private Key Sealing the Symmetric Key Encrypting the Symmetric Key with the RSA Algorithm q More Information About the Example To safely send the credit card number over the net. Part 2 TM Lesson 3: Cryptography [<<BACK] [CONTENTS] [NEXT>>] Many people are protective of their credit card numbers. Note: Because cryptography software is not exportable outside the United States and Canada. and uses the session key with the cipher to encrypt the credit card file:///T|/General/Documentation/Java/Basic Java 2/HTML/crypto. the example program gets the plain text credit card number entered by the end user and passes the credit card number to its encrypt method.html (1 of 7) [24.07. The encrypt method creates a cipher and session key. and for good reason. Only programs with the key to turn the cipher text back to original text can decrypt the protected information. A stolen credit card number with other personal information can give a thief all he or she needs to create serious mayhem in someone's life. One way to keep credit card and other proprietary information secure when sending it over the net is to encrypt it. Tech Articles. Documentation Java Developer Connection Tutorials.Java (TM) Language Basics. APIs. the example in this lesson is in pseudo code rather than source code. Lesson 3: Cryptography Java Technology Home Page A-Z Index Java Developer Connection(SM) Online Training Downloads. Lesson 2: User Interfaces Revisited example to encrypt the credit card number before sending it over the net. Training Online Support Community Discussion News & Events from Everywhere Products from Everywhere How Java Technology is Used Worldwide Print Button Java Programming Language Basics. Encryption is the process of applying a key to plain text that transforms that plain text into unintelligible (cipher) text.2000 12:33:39] . Part 2.

In the example. the public key is made readily available to any client program that requests it. Order processing clients get the encrypted session key and credit card number.Java (TM) Language Basics. This type of cryptography is called asymmetric key encryption. and use the session key to decrypt the credit card number.html (2 of 7) [24.2000 12:33:39] . The credit card number is encrypted and decrypted with the same session key.07. This type of cryptography is called symmetric key encryption. and in our example. it is encrypted with or wrapped under the public key of the recipient. The file with the private key must be kept in a very secure place. Lesson 3: Cryptography number. The server program loads the public key from the public key file. To protect the session key. Because the session key is sent over the net. use the private key to decrypt the session key. A session key is a secret key that is generated new each time the Purchase button is clicked. Changing the session key protects against an unauthorized program getting the key and decrypting hundreds and thousands of credit card numbers with it. requires the session key and encrypted credit card number be sent over the ret to the receiving program. Many companies keep the private key file on an external storage medium such as tape or disk to prevent an unauthorized person or program from breaking into the system and getting the private key. it too should be protected against unauthorized access. can only be decrypted with the private key corresponding to the public key that originally encrypted it. he or she would have to recover the session key with the intended recipient's private key to be able to decrypt the credit card number with the session key. and the private key is kept secret and made available to specific. As shown in the diagram. Anything encrypted with a public key. this example uses a separate program to generate the public and private key pair. file:///T|/General/Documentation/Java/Basic Java 2/HTML/crypto. Even if an unauthorized program gets the wrapped session key and credit card number. The public key is stored in one file. Part 2. and the private key is stored in another. load the private key. trusted clients only. and makes it available to order clients for encrypting the session key.

Copy the JAR file to the jdk1.SunJCE You also need to install a package with an asymmetric algorithm such as the Rivest.2/lib/ext directory with the other JAR files. Pseudo Code A cipher object is used in the encryption and decryption process. you can download the javax.Sun security.provider.security.3= and put it in the jdk1.07.2/lib/security/java. Shamir. Part 2.2 installation. A cryptographic service provider is a package or set of packages that supplies a concrete implementation of a cryptographic algorithm.2/jre/lib/ext or jre1.security file: security. Lesson 3: Cryptography Running the Example If you are within the United States or Canada.1=sun.2/jre/lib/security/java.security as security. It contains documentation and a JavaTM Archive (JAR) file with the cryptographic APIs and a cryptographic service provider.2=com.provider.Java (TM) Language Basics.2/jre/lib/ext directory of your Java 2 SDK. Standard Edition. installation or to the jre1.2/jre/lib/security/java. and Adleman (RSA) Asymmetric-Cipher algorithm. Compile and run the example as usual.security or jre1.crypto package from the Products & APIs page. The asymmetric algorithm is needed to create the asymmetric cipher for the public and private key encryption.2/lib/security directory of your Java Runtime Environment (JRE) 1.2000 12:33:39] . The cipher object is created with a specific cryptographic algorithm file:///T|/General/Documentation/Java/Basic Java 2/HTML/crypto.crypto.sun.provider. Using the documentation in the download.security or jre1.2/lib/security/java. Make sure you have the following entries in the jdk1.html (3 of 7) [24.provider.provider. Add the asymmetric algorithm package to jdk1. convert the pseudo code to source code.

Java (TM) Language Basics. and Adleman (RSA) Asymmetric-Cipher algorithm.2000 12:33:39] . In pseudo code. Generate public and private key pair using asymmetric algorithm Store private Key in very safe place file:///T|/General/Documentation/Java/Basic Java 2/HTML/crypto. the key is either the public or private key. but presents a problem when you use the RSA key because the RSA algorithm imposes a size restriction (discussed below) on the object being encrypted and sealing makes the object too large for RSA encryption. Symmetric key encryption uses a symmetric algorithm such as Data Encryption Standard (DES). The SunJCE provider that comes standard with JCE 1.crypto package defines the framework for both symmetric and asymmetric encryption into which concrete cipher implementations can be plugged. It also defines a method to return the public key when a client requests it.html (4 of 7) [24. and in the case of asymmetric encryption. The javax.07. In the case of symmetric encryption. it is initialized for encryption or decryption with a key. you need to install a different provider. The pseudo code shows two ways to do the asymmetric encryption of the session key. The other way uses another asymmetric algorithm to seal (encrypt) the symmetric key. For an implementation of an asymmetric encryption algorithm such as RSA. Shamir. The public key is read from its file when a client calls the method to get the public key. the key is a secret key. two types of encryption are used: symmetric and asymmetric. Server The Send interface declares and the RemoteServer class implements methods to handle the encrypted credit card number and the encrypted secret key. Lesson 3: Cryptography depending on the type of encryption in use. The asymmetric key encryption uses an asymmetric algorithm such as Rives. The private key is read from its file when RMIClient2 needs it to decrypt the secret key. Part 2. After the cipher is created with the correct symmetric or asymmetric algorithm. In this example.2 supplies only implementations of symmetric encryption algorithms such as DES. this is what the server interface and class need to declare and implement: A A A A A method method method method method to to to to to get the public key send the encryped credit card number get the encrypted credit card number send the encrypted symmetric key get the encrypted symmetric key Generating the Public and Private Key Pair You need a program to generate a public and private key pair and store them to separate files. Sealing is the preferred way. One way uses an RSA key to encrypt the symmetric key.

and send the encrypted credit card number and sealed key to the server. and the sealing process makes the session key too large to use with the RSA algorithm. So. you cannot use the keys to encrypt more than 53 bytes (53 = 64 . So. Here is the pseudo code to do it: public byte[] decrypt(encrypted key. The RSA asymmetric algorithm cannot be used because it has the size restrictions described in the next section.Java (TM) Language Basics. Here is the pseudo code to do it: private void encrypt(credit card number){ Create cipher for symmetric key encryption (DES) Create a key generator Create a secret (session) key with key generator Initialize cipher for encryption with session key Encrypt credit card number with cipher Get public key from server Create cipher for asymmetric encryption (do not use RSA) Initialize cipher for encryption with public key Seal session key using asymmetric Cipher Send encrypted credit card number and sealed session key to server } RMIClient2Sealed.java: The RMIClient2. if you generate an RSA key pair with a key size of 512 bits. if you have a session key that is only 8 bytes long.2000 12:33:39] . The PKCS RSA encryption padding scheme needs 11 spare bytes to work. seal the symmetric key. sealing file:///T|/General/Documentation/Java/Basic Java 2/HTML/crypto. RMIClient1Sealed.html (5 of 7) [24. RSA encryption uses the PKCS#1 standard with PKCS#1 block type 2 padding. Lesson 3: Cryptography Store public key in accessible place Sealing the Symmetric Key Sealing the symmetric key involves creating a sealed object that uses an asymmetric cipher to seal (encrypt) the session key.11).07.java code has a decrypt method to unseal the symmetric key and decrypt the credit card number. Part 2.java code has an encrypt method to encrypt the credit card number. encrypted credit card number){ Get private key from file Create asymmetric cipher (do not use RSA) Initialize cipher for decryption with private key Unseal wrapped session key using asymmetric cipher Create symmetric cipher Initialize cipher for decryption with session key Decrypt credit card number with symmetric cipher } Encrypting the Symmetric Key with the RSA Algorithm The RSA algorithm imposes size restrictions on the object being encrypted.java: The RMIClient1.

and send the encrypted credit card number and sealed session key to the server. or by using a search engine and searching on RSA Cryptography. and the result is a javax.crypto.07. the class signature.html (6 of 7) [24.java: The RMIClient2. the object to be sealed (the session key. or symmetric key encryption. Serialization adds more information to the session key such as the class of the session key. Here is the pseudo code to do it: private void encrypt(credit card number){ Create cipher for symmetric key encryption (DES) Create a key generator Create a secret (session) key with key generator Initialize cipher for encryption with session key Encrypt credit card number with cipher Get public key from server Create cipher for asymmetric encryption (RSA) Initialize cipher for encryption with public key Encrypt session key Send encrypted credit card number and session key to server } RMIClient2.java code has an encrypt method to encrypt the credit card number. RMIClient1. asymmetric key encryption. and then the serialized contents are encrypted.IllegalBlockSizeException run time error.java code has a decrypt method to unseal (decrypt) the symmetric key and decrypt the credit card number.java: The RMIClient1. which is way over the size restriction imposed by the RSA algorithm. Here is the pseudo code to do it: public String decrypt(encrypted key. Lesson 3: Cryptography expands it to 3644 bytes. The additional information makes the session key too large to be encrypted with an RSA key.2000 12:33:39] . Part 2. and any objects referenced by the session key.Java (TM) Language Basics. In the process of sealing. in this case) is first serialized. [TOP] file:///T|/General/Documentation/Java/Basic Java 2/HTML/crypto. encrypted credit card number){ Decrypt credit card number Get private key from file Create asymmetric cipher (RSA) Initialize cipher for decryption with private key Decrypt symmetric key Instantiate symmetric key Create symmetric cipher Initialize Cipher for decryption with session key Decrypt credit card number with symmetric Cipher } More Information You can find more information on key encryption on the Security Dynamics Web site (for RSA encryption). seal (encrypt) the session key.

Terms of Use. file:///T|/General/Documentation/Java/Basic Java 2/HTML/crypto.Java (TM) Language Basics. Lesson 3: Cryptography Print Button [ This page was updated: 31-Mar-2000 ] Products & APIs | Developer Connection | Docs & Training | Online Support Community Discussion | Industry News | Solutions Marketplace | Case Studies Glossary .Tutorial .Java in the Real World FAQ | Feedback | Map | A-Z Index For more information on Java technology and other software from Sun Microsystems.2000 12:33:39] .Employment . All Rights Reserved. and Canada.Applets . Copyright © 1995-2000 Sun Microsystems.07. Privacy Policy. call: (800) 786-7638 Outside the U.html (7 of 7) [24.S. Inc.Java Store . Part 2.Business & Licensing . dial your country's AT&T Direct Access Number first. Inc. Sun Microsystems.

APIs.html (1 of 5) [24.Java (TM) Language Basics.*. file:///T|/General/Documentation/Java/Basic Java 2/HTML/serial. and written to and read from a file as a single unit. Object serialization transforms an object's data to a bytestream that represents the state of the data. and all orders are processed in the order they are received by the server. pears.io. Training Online Support Community Discussion News & Events from Everywhere Products from Everywhere How Java Technology is Used Worldwide Print Button Java Programming Language Basics. class DataOrder implements Serializable{ String apples. import java.07. peaches. Documentation Java Developer Connection Tutorials. Lesson 4: Serialization Java Technology Home Page A-Z Index Java Developer Connection(SM) Online Training Downloads. int itotal. It has no methods. Wrapping the Data The DataOrder. Part 2 TM Lesson 4: Serialization [<<BACK] [CONTENTS] [NEXT>>] One big problem with the example program in its current form is the fact that sending clients can overwrite each other's data before receiving clients have a chance to get and process it. The serialized form of the data contains enough information to recreate the object with its data in a similar state to what it was when saved. Part 2. q About the Example q q q q q Wrapping the Data Sending Data Server Program Receiving Data More Information About the Example The example adapts the Part 2. This lesson adapts the server code to ensure all orders are processed (nothing is overwritten). cardnum. double icost. Lesson 2: User Interfaces Revisited example to wrap the fruit order data into a single data object and send the data object over the network to the server. custID.java class is very simple. It implements the Serializable interface so its data can be serialized. Tech Articles. This is more efficient than sending each unit of data separately. It defines the fields that wrap and store the fruit order data.2000 12:33:42] .

public void actionPerformed(ActionEvent event){ Object source = event. String number.lang. num.items. text2.setText(text2).getSource().setText(text).getText(). } } else { order.icost = (order. this.setText("Invalid Value"). text = num.cardnum = creditCard.cost.apples).peaches = peachqnt.intValue().2000 12:33:42] .icost field. this. pearsNo. the total cost is calculated and displayed in the user interface using the order. DataOrder order = new DataOrder(). Part 2.25).getText(). cost = new Double(order. Integer applesNo.pears = pearqnt. text2 = cost.getText().html (2 of 5) [24.sendOrder(order).getText().apples. order.itotal * 1. try{ send.custID = customer. order. Lesson 4: Serialization } Sending Data The RMIClient1.itotal).valueOf(order.length() > 0){ try{ applesNo = Integer. Double cost. } catch (Exception e) { file:///T|/General/Documentation/Java/Basic Java 2/HTML/serial.getText().actionPerformed method creates an instance of the DataOrder class and initializes its fields with order data retrieved from the user interface text fields and areas. order.Java (TM) Language Basics. num = new Integer(order. order. The RMIClient1.NumberFormatException e) { appleqnt. } catch (java. order.itotal field and displayed in the user interface.apples = appleqnt.07.itotal += 0.java program is modified to use the DataOrder class to send the order data over the net. } The total number of items is retrieved from the order. if(source == purchase){ order.icost field. if(order.toString(). Similarly.itotal += applesNo. order. text.toString(). peachesNo.icost). The total number of items is calculated using the order.

java The RemoteServer. Part 2. The first order received is stored in a file named 1.Java (TM) Language Basics.java public void sendOrder(DataOrder order){ value += 1. the order object is sent over the net to the server program. This is the serialized output stream to which the order object is written in the last line of the try block.writeObject(order).rmi. and stores each order in a separate file where the file name is a number. the value variable is incremented by 1 each time the sendOrder method is called. orders = num. oos. converted to a String. public DataOrder getOrder() throws RemoteException.rmi. RemoteServer.java classes are much simpler in this lesson.java and RemoteServer.Remote. They have one getXXX method that returns an instance of DataOrder. import java.2000 12:33:42] . Objects are serialized by creating a serialized output stream and writing the object to the output stream.RemoteException.07. and used for the file name in the serialization process. num = new Integer(value).out. and so forth. and one setXXX method that accepts an instance of DataOrder. public interface Send extends Remote { public void sendOrder(DataOrder order) throws RemoteException. The next line creates an ObjectOutputFileStream from the file output stream. file:///T|/General/Documentation/Java/Basic Java 2/HTML/serial.sendOrder method accepts a DataOrder instance as input. } RemoteServer. the second order is stored in a file named 2. Send. ObjectOutputStream oos = new ObjectOutputStream(fos).println("Cannot send data to server").toString(). try{ FileOutputStream fos = new FileOutputStream(orders). In the code.html (3 of 5) [24. To keep track of the file names. } After the totals are calculated. the first line in the try block creates a FileOutputStream with the file name to which the serialized object is to be written.java import java. Server Program The Send. Lesson 4: Serialization System.

IOException e){ System. If it is equal to zero.07. if(source == view){ try{ file:///T|/General/Documentation/Java/Basic Java 2/HTML/serial.toString()).println("No Orders To Process").toString()).ClassNotFoundException e){ System. }catch (java.toString()).toString()).io.out.io. } } The RemoteServer. } if(value > get){ get += 1. and if it is greater than the value in the get variable. Part 2.out. num = new Integer(get).out.out.println(e. try{ FileInputStream fis = new FileInputStream(orders).lang.2000 12:33:42] .io.toString().getOrder method does what the sendOrder method does in reverse using the get variable to keep track of which orders have been viewed.println("No Orders To Process"). }catch (java. public DataOrder getOrder(){ DataOrder order = null. }catch (java.out. there are no orders to get from a file and view. } return order.println(e.println(e. } }else{ System.html (4 of 5) [24.Java (TM) Language Basics.out. the get variable is incremented by 1. As each order is viewed. this method checks the value variable. But first. there is at least one order to get from a file and view. } Receiving Data The RMIClient2.println(e.actionPerformed method gets an order object and references its fields to display data in the user interface.println(e.FileNotFoundException e){ System.toString()). Lesson 4: Serialization }catch (java.io. ObjectInputStream ois = new ObjectInputStream(fis).FileNotFoundException e){ System. orders = num. }catch (java. order = (DataOrder)ois.IOException e){ System.readObject().out. if(value == 0){ System.

and Canada.cardnum). creditNo.out. itms = new Integer(items).07.getOrder(). cost = order.apples).Applets .Java (TM) Language Basics.2000 12:33:42] .toString().setText(order. Inc.S. } catch (Exception e) { System.println("Cannot send data to server").setText(order. items = order.Java in the Real World FAQ | Feedback | Map | A-Z Index For more information on Java technology and other software from Sun Microsystems. file:///T|/General/Documentation/Java/Basic Java 2/HTML/serial.toString(). price = new Double(cost).setText(unit). i = itms.peaches).setText(i). Inc. peachesNo. unit = price. customerNo. [TOP] Print Button [ This page was updated: 31-Mar-2000 ] Products & APIs | Developer Connection | Docs & Training | Online Support Community Discussion | Industry News | Solutions Marketplace | Case Studies Glossary .html (5 of 5) [24. call: (800) 786-7638 Outside the U.icost. Terms of Use.setText(order. } } More Information You can find more information on serialization in the Reading and Writing (but no 'rithmetic) lesson in The JavaTM Tutorial.Business & Licensing .custID). Privacy Policy. applesNo.setText(order. itotal. All Rights Reserved.pears). Sun Microsystems. Part 2.itotal.Java Store . pearsNo. dial your country's AT&T Direct Access Number first. Copyright © 1995-2000 Sun Microsystems. Lesson 4: Serialization order = send.Employment .setText(order. icost.Tutorial .

You could. HashSet.07. but can contain objects of different types too. an element of type String containing the value 1 and an element of type Integer containing the value 1 are not duplicate. This lesson focuses on the List and Set collections.Java (TM) Language Basics. Part 2. Duplicate elements have the same data type and value.util. and Double if it makes sense in your application. whereas. You can see that file:///T|/General/Documentation/Java/Basic Java 2/HTML/collec. but List implementations do. For example. Lesson 2: User Interfaces Revisited to use the Collections application programming interface (API) to maintain and print a list of unique customer IDs.html (1 of 3) [24. q About Collections q q q Creating a Set Printing More Information About Collections The Collection classes available to use in programs implement Collection interfaces. Set. a customer ID. The customer IDs are all objects of type String and represent the same type of information. and TreeSet.HashSet on the left. Set The API provides two general-purpose Set implementations. implementations do not permit duplicate elements. APIs. two customer IDs of type String containing the value Zelda are duplicate. This diagram shows the Collection interfaces on the right and the class hierarchy for the java.2000 12:33:44] . Part 2 TM Lesson 5: Collections [<<BACK] [CONTENTS] [NEXT>>] A collection is an object that contains other objects and provides methods for working on the objects it contains. have a collection object that contains objects of type String. Tech Articles. A collection can consist of the same types of objects. Training Online Support Community Discussion News & Events from Everywhere Products from Everywhere How Java Technology is Used Worldwide Print Button Java Programming Language Basics. Lesson 5: Collections Java Technology Home Page A-Z Index Java Developer Connection(SM) Online Training Downloads. and Map. Integer. Documentation Java Developer Connection Tutorials. however. which stores its elements in a balanced binary tree called a red-black tree. Interfaces are abstract data types that let collections be manipulated independently of their representation details. The example for this lesson uses the HashSet implementation because it currently has the best performance. which stores its elements in a hash table. This lesson adapts the RMIClient2 program from Part 2. There are three primary types of collection interfaces: List.

Elements are printed in the order they occur in the set.2000 12:33:44] . Creating a Set This example adapts the RMIClient2. The collection object is a Set so if the same customer enters multiple orders. an object of type Iterator is returned from the file:///T|/General/Documentation/Java/Basic Java 2/HTML/collec.actionPerformed method calls the addCustomer method to add a customer ID to the set when the order processor clicks the View button. If the program tries to add an element that is the same as an element already in the set. Part 2.Java (TM) Language Basics. Lesson 5: Collections the HashSet class implements the Set interface. System. but that order is not necessarily the same as the order in which the elements were placed in the set. there is only one element for that customer in the list of customer IDs. } Printing The print method is called from the RMIClient2.println("Customer ID added").07.actionPerformed method when the order processor clicks the View button.html (2 of 3) [24.out. The print method prints the elements currently in the set to the command line. No error is thrown and there is nothing you have to do in your code. //Create list of customer IDs public void addCustomer(String custID){ s. To traverse the set. The RMIClient2. The addCustomer method shown below adds the customer ID to the set and prints a notice that the customer ID has been added.java class to collect customer IDs in a Set and print the list of customer IDs whenever the View button is clicked. Note: A HashSet does not guarantee the order of the elements in the set.add(custID). the second element is simply not added.

println(it.Java in the Real World FAQ | Feedback | Map | A-Z Index For more information on Java technology and other software from Sun Microsystems. and a remove method that lets you remove an element.out.2000 12:33:44] .size()!=0){ Iterator it = s. Part 2.html (3 of 3) [24. Inc.hasNext()){ System.Java Store . Inc. In the iterator approach. Copyright © 1995-2000 Sun Microsystems. Privacy Policy. file:///T|/General/Documentation/Java/Basic Java 2/HTML/collec. } //Call System.S.07.println(s).println("No customer IDs available"). while(it. }else{ System.iterator().out.Java (TM) Language Basics. Sun Microsystems.Business & Licensing .Employment . Lesson 5: Collections set. The first way uses an iterator and the second way simply calls System. All Rights Reserved. call: (800) 786-7638 Outside the U. The Iterator object has a hasNext method that lets you test if there is another element in the set. The example print method shows two ways to print the set. dial your country's AT&T Direct Access Number first. the element returned by the next method is printed to the command line until there are no more elements in the set. a next that lets you move over the elements in the set.println on the set. and Canada. [TOP] Print Button [ This page was updated: 31-Mar-2000 ] Products & APIs | Developer Connection | Docs & Training | Online Support Community Discussion | Industry News | Solutions Marketplace | Case Studies Glossary . //Print customer IDs public void print(){ //Iterator approach if(s.Tutorial . } } More Information You can find more information on Collections in the Collections trail in The JavaTM Tutorial.out.out.next()). Terms of Use.out.println on the set System.Applets .

The JavaTM 2 platform provides internationalization features that let you separate culturally dependent data from the application (internationalization) and adapt it to as many cultures as needed (localization).07. Tech Articles. Lesson 5: Collections. are doing business around the world using many different languages. and left column labels) Buttons (Purchase. q Identify Culturally Dependent Data q q q q q q Create Keyword and Value Pair Files Internationalize Application Text Internationalize Numbers Compile and Run the Application Program Improvements More Information Identify Culturally Dependent Data The first thing you need to do is identify the culturally dependent data in your application.html (1 of 13) [24. Documentation Java Developer Connection Tutorials. so it follows that adapting an application to a local language adds to profitability through better communication and increased satisfaction. internationalizes them and adapts the text to France. Text is the most obvious and pervasive example of culturally dependent data.java and RMIClient2. Effective communication is always good business. Part 2. Part 2 TM Lesson 6: Internationalization [<<BACK] [CONTENTS] [NEXT>>] More and more companies. sounds. View) file:///T|/General/Documentation/Java/Basic Java 2/HTML/int.Java(TM) Language Basics. times. large and small. and dates must be considered too. Reset. but other things like number formats.java classes have the following culturally-dependent data visible to the end user: q q Titles and labels (window titles. column heads. Culturally-dependent data is any data that varies from one culture or country to another. and the United States. Lesson 6: Internationalization Java Technology Home Page A-Z Index Java Developer Connection(SM) Online Training Downloads. This lesson takes the two client programs from Part 2.2000 12:33:51] . Germany. Training Online Support Community Discussion News & Events from Everywhere Products from Everywhere How Java Technology is Used Worldwide Print Button Java Programming Language Basics. APIs. The RMIClient1.

util. it is English.out.NoSuchElementException{ if(s!=null){ Iterator it = s. In this case. The only visible culturally-dependent data in the server program is the error message text.iterator(). as demonstrated by the print method below. Part 2. } } }else{ System.hasNext()){ try{ String customer = (String)it.NoSuchElementException e){ System. The server program runs in one place and the assumption is that it is not seen by anyone other than the system administrator who understands the language in which the error messages is hard coded.println(customer). while(it. Lesson 6: Internationalization q q Numbers (values for item and cost totals) Error messages Although the application has a server program. All error messages in RMIClient1 and RMIClient2 are handled in try and catch blocks.println("No customer IDs available"). public void print(){ if(s!=null){ Iterator it = s. file:///T|/General/Documentation/Java/Basic Java 2/HTML/int. System.html (2 of 13) [24.next(). public void print() throws java. but this way you cannot access the error message text thrown when the method tries to access unavailable data in the set.2000 12:33:51] .next(). while(it.out. In this example.07.iterator(). }catch (java.hasNext()){ String customer = (String)it. The point here is it is always better to use try and catch blocks wherever possible if there is any chance the application will be internationalized so you can localize the error message text.out. the server program is not being internationalized and localized. } } The print method could have been coded to declare the exception in its throws clause as shown below.println("No data available"). the system-provided text for this error message is sent to the command line regardless of the locale in use for the application. This way you have access to the error text No data available for translation into another language.util.Java(TM) Language Basics.

Total Cost. number. button.java. No customer IDs available. Specify Quantity Buttons: Reset. there are three properties files.out. and error text visible to the user. and you need one file for each language you intend to use.println(customer). you can map the keyword purchase to Kaufen in the German file. subject to internationalization and localization. In your application. Keyword and value pairs are stored in files called properties files because they store information about the programs properties or characteristics. Property files are plain-text format.out. and German translations. Total Items. View. and therefore. This is done with keyword and value pair files. } } Here is a list of the title. Because this application currently uses hard-coded English text. Purchase Number Values: Value for total items. Cannot look up remote server object. Cannot send data to server. The keywords are referenced from the application instead of the hard-coded text and used to load the appropriate text from the file for the language in use. you reference the keyword purchase and indicate the language to use. Lesson 6: Internationalization System. French. For example.java and RMIClient2. q q q q q Labels: Apples. one each for the English.2000 12:33:51] . These are the names of the properties files for the German (de_DE). In this example. Value for total cost Errors: Invalid Value.println("No customer IDs available"). Credit Card. Select Items. Cannot access data in server Create Keyword and Value Pair Files Because all text visible to the user will be moved out of the application and translated. The language and country are both included because the same language can vary between countries. Pears. file:///T|/General/Documentation/Java/Basic Java 2/HTML/int. The properties files follow a naming convention so the application can locate and load the correct file at run time. No data available.25 Each. your application needs a way to access the translated text during execution. and Purchase in the United States English file.07. Achetez in the French file. For example. This data was taken from both RMIClient1. label. Peaches. Part 2. The naming convention uses language and country codes which you should make part of the file name. the easiest way to begin the internationalization process is to use the hard-coded text to set up the key and value pairs for the English properties file. where this is a file for each language. } }else{ System.Java(TM) Language Basics. Customer ID Titles: Fruit $1.html (3 of 13) [24. and Swiss German and Austrian German both differ from each other and from the German spoken in Germany. United States English and Australian English are a little different.

Lesson 6: Internationalization French (fr_FR).properties q MessagesBundle_en_US.Java(TM) Language Basics.html (4 of 13) [24. France. and the United States: q MessagesBundle_de_DE. Keep a copy for yourself because you will need the keywords to internationalize your application text. MessagesBundle_en_US. FR. and English lanuages. The properites file with the German translations produces this user interface for the fruit order client: file:///T|/General/Documentation/Java/Basic Java 2/HTML/int.properties q MessagesBundle_fr_FR. fr. Part 2.07. French. you can hand it off to your French and German translators and ask them to provide the French and German equivalents for the text to the right of th equals (=) sign.properties apples=Apples: peaches=Peaches: pears=Pears: items=Total Items: cost=Total Cost: card=Credit Card: customer=Customer ID: title=Fruit 1. and en indicate the German (Deutsche). and DE. Keywords appear to the left of the equals (=) sign.2000 12:33:51] . and text values appear to the right. and US indicate Germany (Deutschland).properties Here is the English language properties file. and American English (en_US) translations where de.25 Each 1col=Select Items 2col=Specify Quantity reset=Reset view=View purchase=Purchase invalid=Invalid Value send=Cannot send data to server nolookup=Cannot look up remote server object nodata=No data available noID=No customer IDs available noserver=Cannot access data in server With this file complete.

Part 2.Java(TM) Language Basics. The RMIClient2.2000 12:33:51] . this program needs the following instance variable declarations for the internationalization process: //Initialized in main method static String language.java code is almost identical so you can apply the same steps to that program on your own. file:///T|/General/Documentation/Java/Basic Java 2/HTML/int. Lesson 6: Internationalization The properties file with the French translations produces this user interface for the fruit order client: Internationalize Application Text This section walks through internationalizing the RMIClient1.util.html (5 of 13) [24.07.java program. country.* package where the internationalization classes are. Instance Variables In addition to adding an import statement for the java.

main Method The program is designed so the user specifies the language to use at the command line. but in most cases.policy=java.eng. As an example.security.codebase= http://kq6py/~zelda/classes/ -Djava. This code expects 3 command line arguments when the end user wants a language other than English.rmi. java -Djava. and the second parameter is the Locale object that tells the ResourceBundle which translation to use. Specifying the language at the command line means once the application is internationalized.server. the country and language are assumed to be United States English.07. file:///T|/General/Documentation/Java/Basic Java 2/HTML/int. It takes two parameters: the first parameter "MessagesBundle" is the prefix of the family of translation files this aplication uses.html (6 of 13) [24. Everything goes on one line.Java(TM) Language Basics. the first change to the main method is to add the code to check the command line parameters. this code creates a ResourceBundle variable to access the MessagesBundle_de_DE. So. Part 2. The messages object provides access to the translated text for the language in use. the program will use one language and not rely on command-line arguments to set the country and language.com de DE And here is the main method code. The first argument is the name of the machine on which the program is running. //Initialized in actionPerformed method NumberFormat numFormat.policy RMIClient1 kq6py. and the messages instance variable is initialized from the currentLocale. you can easily change the language without any recompilation. If the program is invoked with 1 command line argument (the machine name only). Lesson 6: Internationalization Locale currentLocale. The currentLocale instance variable is initialized from the language and country information passed in at the command line.properties file. The other two arguments specify the language and country codes. The String[] args parameter to the main method contains arguments passed to the program from the command line.sun. static ResourceBundle messages. This value is passed to the program when it starts and is needed because this is a networked program using the Remote Method Invocation (RMI) API. If the application is invoked with de DE command line parameters.2000 12:33:51] . here is how the program is started with command line arguments to specify the machine name and German language (de DE). Note: This style of programming makes it possible for the same user to run the program in different languages.

println(messages. Lesson 6: Internationalization public static void main(String[] args){ //Check for language and country codes if(args. if(System.out.RemoteException e){ System. WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.getSecurityManager() == null) { System.length != 3) { language = new String("en").getString( "nolookup")).println(messages.getString( "nolookup")). and passing it the keyword that maps to the applicable error text.getBundle("MessagesBundle". country = new String(args[2]).setVisible(true). } catch(java.MalformedURLException e) { System.out. currentLocale).pack(). System.addWindowListener(l). } } The applicable error text is accessed by calling the getString method on the ResourceBundle. } }.out.07.getString( "nolookup")). }else{ language = new String(args[1]).html (7 of 13) [24. System. file:///T|/General/Documentation/Java/Basic Java 2/HTML/int. } catch(java.rmi. frame.println("English").println(messages. //Create the RMIClient1 object RMIClient1 frame = new RMIClient1(). frame. messages = ResourceBundle. country = new String ("US"). country).net.rmi.NotBoundException e) { System.exit(0). send = ((Send) Naming.2000 12:33:52] .Java(TM) Language Basics.out. Part 2. frame.out.println(language + country).setSecurityManager( new RMISecurityManager()). } catch (java.lookup(name)). } try { String name = "//" + args[0] + "/Send". } //Create locale and resource bundle currentLocale = new Locale(language.

getString( "nolookup")). User interface objects that display text.getString( "nolookup")).Java(TM) Language Basics. } catch (java. Part 2. or you will get a runtime error indicating the resource is unavailable. the Invalid Value error is caught and translated: if(order.getString("2col"))..addActionListener(this). and passing it the keyword that maps to the title text.getString("1col")).getString( "purchase")).valueOf(order. //Create buttons and make action listeners purchase = new JButton(messages. The next thing the constructor does is use the args parameter to look up the remote server object.println(messages.out.RemoteException e){ System.MalformedURLException e) { System.. } catch(java. such as JLabel and JButton.net. col2 = new JLabel(messages. the catch statements get the applicable error text from the ResourceBundle and print it to the command line.html (8 of 13) [24.rmi.getString( "nolookup")). are created in the same way: //Create left and right column labels col1 = new JLabel(messages.getString("title")).getString("reset")). If there are any errors in this process. actionPerformed Method In the actionPerformed method. reset.apples.println(messages.lookup(name)). .out.07.rmi. reset = new JButton(messages. file:///T|/General/Documentation/Java/Basic Java 2/HTML/int.2000 12:33:52] .addActionListener(this). RMIClient1(){ //Set window title setTitle(messages.NotBoundException e) { System.length() > 0){ //Catch invalid number error try{ applesNo = Integer. You must pass the keyword exactly as it appears in the translation file. send = ((Send) Naming.apples). Lesson 6: Internationalization try { String name = "//" + args[0] + "/Send". } catch(java. purchase. } Constructor The window title is set by calling the getString method on the ResourceBundle.out.println(messages.

cost.setText(text).itotal * 1.icost = (order. try{ send. double. Compile These instructions assume development is in the zelda home directory.itotal += applesNo. } The actionPerformed method calculates item and cost totals. //Display running total text = numFormat. or Double.25).setText(messages.itotal += 0.items.07. } catch (java.intValue().format(order. The information in the currentLocale tells the NumberFormat object what number format to use. //Create number formatter numFormat = NumberFormat.rmi. file:///T|/General/Documentation/Java/Basic Java 2/HTML/int. translates them to the correct format for the language currently in use. and displays them in the user interface.format(order.NumberFormatException e){ appleqnt.Java(TM) Language Basics. Once you have a NumberFormat object.RemoteException e) { System.html (9 of 13) [24. all you do is pass in the value you want translated. this. The value can be passed in as any data type used for numbers such as int. a NumberFormat object is created from the currentLocale.out.getString("invalid")). No code such as to convert an Integer to an int and back again is needed.sendOrder(order).getNumberInstance( currentLocale).itotal). } } else { order. text2 = numFormat. Integer.2000 12:33:52] . this.getString("send")). and you receive a String that contains the number in the correct format.lang. To do this. //Calculate and display running cost order. } Compile and Run the Application Here are the summarized steps for compiling and running the example program.setText(text2). Internationalize Numbers A NumberFormat object is used to translate numbers to the correct format for the language currently in use. }catch(java. Lesson 6: Internationalization order. you need to include language and country codes if you want a language other than United States English. The important thing to note is that when you start the client programs.icost). Part 2.println(messages.

policy RemoteServer Win32: cd \home\zelda\public_html\classes java -Djava.sun.Java(TM) Language Basics.hostname=kq6py.java javac RemoteServer.rmi.rmi.java javac RMIClient2. Part 2.class \home\zelda\public_html\classes copy DataOrder.server.class /home/zelda/public_html/classes cp DataOrder.eng. Lesson 6: Internationalization Unix: cd /home/zelda/classes javac Send.java javac RMIClient1.server.policy=java.rmi.codebase= http://kq6py/~zelda/classes -Dtava.rmi. RemoteServer copy RemoteServer*.security.class /home/zelda/public_html/classes cp Send.policy=java.class /home/zelda/public_html/classes Win32: cd \home\zelda\classes javac Send.java rmic -d .server.html (10 of 13) [24.codebase= file:c:\home\zelda\public_html\classes -Djava.java javac RMIClient1.security.com -Djava.java rmic -d .java javac RMIClient2.hostname=kq6py.java javac RemoteServer.server. RemoteServer cp RemoteServer*.com -Djava.policy RemoteServer file:///T|/General/Documentation/Java/Basic Java 2/HTML/int.sun.class \home\zelda\public_html\classes copy Send.07.2000 12:33:52] .eng.class \home\zelda\public_html\classes Start rmi Registry Unix: cd /home/zelda/public_html/classes unsetenv CLASSPATH rmiregistry & Win32: cd \home\zelda\public_html\classes set CLASSPATH= start rmiregistry Start the Server Unix: cd /home/zelda/public_html/classes java -Djava.

server. file:///T|/General/Documentation/Java/Basic Java 2/HTML/int. Unix: cd /home/zelda/classes java -Djava.codebase= file:c:\home\zelda\public_html\classes -Djava.policy RMIClient2 kq6py.server.eng.security. Lesson 6: Internationalization Start RMIClient1 in German Note the addition of de DE for the German language and country at the end of the line.policy=java.07. Part 2.policy=java.rmi.rmi.com -Djava. order processing staff run RMIClient2 as applications from their local machines.rmi.eng. Unix: cd /home/zelda/classes java -Djava.2000 12:33:52] .rmi.com -Djava.hostname=kq6py.codebase= http://kq6py/~zelda/classes/ -Djava.security.policy RMIClient1 kq6py.sun. The translation files would be loaded by the applet from the same directory from which the browser loads the applet class.Java(TM) Language Basics.eng.server.eng.sun.sun.com fr FR Win32: cd \home\zelda\classes java -Djava.policy RMIClient1 kq6py.sun.com de DE Win32: cd \home\zelda\classes java -Djava.hostname=kq6py.eng.server.com/home/zelda/public_html fr FR Program Improvements A real-world scenario for an ordering application like this might be that RMIClient1 is an applet embedded in a web page. When orders are submitted.codebase= http://kq6py/~zelda/classes -Djava.security.html (11 of 13) [24.security.eng.server. an interesting exercise is to convert RMIClient1.sun.java to its applet equivalent.policy=java.com de DE Start RMIClient2 in French Note the addition of fr FR for the French language and country at the end of the line.rmi.codebase= file:c:\home\zelda\classes\ -Djava.policy RMIClient2 kq6py.server.sun. So.policy=java.rmi.

Lesson 6: Internationalization One way is to have a separate applet for each language with the language and country codes hard coded.util.getString(Compiled Code) at RMIClient1.getObject(Compiled Code) at java.Java(TM) Language Basics. the browser must be enabled for the Java 2 Platform.<init>(Compiled Code) at RMIClient1. To use applet viewer.util. You might also want to adapt the client programs to catch and handle the error thrown when an incorrect keyword is used.html (12 of 13) [24.main(Compiled Code) More Information You can find more information on Internationalization in the Internationalization trail in The Java Tutorial. Your web page can let them choose the language by clicking a link that launches the appropriate applet. Here are the source code files for the English. you have to use appletviewer to run the applet or install Java Plug-in.html Another improvement to the program as it currently stands would be enhancing the error message text. appletviewer rmiFrench. file:///T|/General/Documentation/Java/Basic Java 2/HTML/int. French. Here is the HTML code to load the French applet on a Web page.util.html is the HTML file for the French applet. Part 2.ResourceBundle. If your browser is not enabled for the Java 2 Platform. Java Plug-in lets you run applets on web pages under the 1. and German applets. type the following where rmiFrench. You can locate the errors in the Java API docs and use the information there to make the error message text more user friendly by providing more specific information.2 version of the Java1 virtual machine (VM) instead of the web browser's default Java VM. Here are the error and stack trace provided by the system when this type of error occurs: Exception in thread "main" java.MissingResourceException: Can't find resource at java. You can find more informationon applets in the Writing Applets trail in The Java Tutorial.ResourceBundle.2000 12:33:52] . <HTML> <BODY> <APPLET CODE=RMIFrenchApp.class WIDTH=300 HEIGHT=300> </APPLET> </BODY> </HTML> Note: To run an applet written with JavaTM 2 APIs in a browser.07.

Lesson 6: Internationalization _______ 1 As used on this web site.Business & Licensing . Inc. dial your country's AT&T Direct Access Number first.html (13 of 13) [24. Sun Microsystems. Terms of Use.Java Store . Part 2. file:///T|/General/Documentation/Java/Basic Java 2/HTML/int.2000 12:33:52] .Tutorial .07. Copyright © 1995-2000 Sun Microsystems. Privacy Policy.Java in the Real World FAQ | Feedback | Map | A-Z Index For more information on Java technology and other software from Sun Microsystems. Inc. All Rights Reserved.Java(TM) Language Basics.S.Applets . the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform [TOP] Print Button [ This page was updated: 3-Apr-2000 ] Products & APIs | Developer Connection | Docs & Training | Online Support Community Discussion | Industry News | Solutions Marketplace | Case Studies Glossary . and Canada.Employment . call: (800) 786-7638 Outside the U.

html (1 of 9) [24. Lesson 6: Internationalization into packages and deploy the executable and other related files to production using JAR file format. and server files. Documentation Java Developer Connection Tutorials. Part 2.07. Packages make it easier to locate and use the class files and help you control access to class data at run time. and in development. which is the same as the directory name where they reside. Although these three sets of classes are related to each other. Tech Articles. JAR file format is a compression and file packaging format and tool for bundling executable files with any other related application files so they can be deployed as one unit. view order client. This lesson shows you how to organize the program files from Part 2. and add a line to the top of each class file that declares the package name. you would use packages from the beginning of development. give the directory a name that relates to the purpose of the classes. Training Online Support Community Discussion News & Events from Everywhere Products from Everywhere How Java Technology is Used Worldwide Print Button Java Programming Language Basics. All you do is put related class files in the same directory. file:///T|/General/Documentation/Java/Basic Java 2/HTML/jar. use the JavaTM Archive file format to deploy the application. you have used classes from the Java API library by importing the package containing the class or classes you need. q Setting up Class Packages r r r r r q Create the Directories Declare the Packages Make Classes and Fields Accessible Change Client Code to Find the Properties File Compile and Run the Example Server Set of Files Fruit Order Client Set of Files View Order Client Set of Files More Information Using JAR Files to Deploy r r r r Setting up Class Packages It is easy to organize class files into packages. Part 2 TM Lesson 7: Packages and JavaTM Archive File Format [<<BACK] [CONTENTS] [NEXT>>] Until now. debugged. A package is a convenient way to organize groups of related classes. Lesson 7: Packages and Java Archive (JAR) Java Technology Home Page A-Z Index Java Developer Connection(SM) Online Training Downloads. Lesson 6: Internationalization can be divided into three groups of files: fruit order client. they have different functions and are to be deployed separately. For example.Java (TM) Language Basics. and ready for deployment. Normally. the class and other related files for the program files from Part 2. When your application is fully tested. APIs. you should organize your application files into packages too.2000 12:34:01] .

net.properties r java.html r java. file:///T|/General/Documentation/Java/Basic Java 2/HTML/jar.Color.properties r MessagesBundle_en_US.java r RMIFrenchApp.properties r index. import java.*.*. the fruit order (client1 and view order (client2) client class files need an import statement for the server package because they have to access the remote server object at runtime.Java (TM) Language Basics.java r RMIGermanApp. import java.properties r MessagesBundle_en_US.policy q client2 r RMIClient2. the package declaration and import statements for the RMIClient2. import java.java r MessagesBundle_de_DE.io. java.html r rmiFapp.properties r MessagesBundle_fr_FR.swing. Part 2.java r MessagesBundle_de_DE.GridLayout.java r java.java r RemoteServer.awt. Lesson 7: Packages and Java Archive (JAR) Create the Directories To organize the internationalization program into three packages. Also.awt. java.2000 12:34:01] . import java.awt.*.*.html r rmiGapp.policy q server r DataOrder.java file needs a package delcaration at the top that reflects the name of the directory.07.html (2 of 9) [24.java class file look like this: //package declaration package client2.*.properties r MessagesBundle_fr_FR.java r Send.html r rmiEapp.*. As an example.rmi.server. import import import import java. javax.rmi.policy Declare the Packages Each *. you could create the following three directories and move the listed source files into them: q client1 r RMIEnglishApp.event.

If you do not specify public. The code that creates the messages variable needs to include the directory (package name) as follows: messages = ResourceBundle. Here is the new DataOrder class. Fields and methods without an access specifier such as public can only be accessed by objects created from classes in the same package. //Make class public public class DataOrder implements Serializable{ //Make fields public public String apples. import java.io. custID. The RemoteServer class and Send interface need to be public classes. you have to make one small change to the client source code. Compile and Run the Example Compiling and running the example organized into packages is a little different from compiling and running the example in previous lessons. a class can only be instantiated by an object created from a class in the same package. the properties files (Messages_*) are stored in the directories with the client source files. the fields of the DataOrder class have to be public too. you have to declare the server classes in the server directory public so they can be instantiated by client programs. which are created from classes in the client1 and client2 directories. //Import server package import server. you have to execute the compiler and interpreter commands from one directory above the package directories. } Change Client Code to Find the Properties Files In the example. Make Classes and Fields Accessible With class files organized into packages.07. public double icost.separatorChar + "MessagesBundle". This makes it easier to package and deploy the files later. public int itotal.*. So the programs can field the properties files. import java. package server.html (3 of 9) [24. pears. Part 2. currentLocale).*. cardnum.getBundle( "client2" + File.*.text.util.2000 12:34:01] . So client programs can access the fruit order data. Lesson 7: Packages and Java Archive (JAR) import java. you have to file:///T|/General/Documentation/Java/Basic Java 2/HTML/jar. First.*. peaches. and second.Java (TM) Language Basics. but their fields do not need to be public because the do not have public data.

class /home/zelda/public_html/classes cp server/DataOrder. Start rmi Registry: Unix: cd /home/zelda/public_html/classes unsetenv CLASSPATH rmiregistry & Win32: cd \home\zelda\public_html\classes set CLASSPATH= start rmiregistry file:///T|/General/Documentation/Java/Basic Java 2/HTML/jar.class /home/zelda/public_html/classes cp server/Send.java javac client2/RMIClient2.Java (TM) Language Basics.java javac server\RemoteServer.java rmic -d .java javac client2\RMIClient2.java javac client1/RMIEnglishApp.class \home\zelda\public_html\classes copy server\Send. Part 2.java javac client1\RMIFrenchApp. server.class \home\zelda\public_html\classes Note: The rmic -d . Lesson 7: Packages and Java Archive (JAR) specify the package directories to the compiler and interpreter commands.RemoteServer copy server\RemoteServer*. Compile These instructions assume development occurs in the zelda home directory.07.java javac server/RemoteServer.RemoteServer line uses server.class /home/zelda/public_html/classes Win32: cd \home\zelda\classes javac server\Send.java javac client1/RMIGermanApp.RemoteServer cp server/RemoteServer*. server.java javac client1\RMIGermanApp.2000 12:34:01] .java javac client1/RMIFrenchApp. server. Unix: cd /home/zelda/classes javac server/Send.html (4 of 9) [24.class \home\zelda\public_html\classes copy server\DataOrder.java javac client1\RMIEnglishApp.RemoteServer instead of server/RemoteServer so the _stub and _skel classes are generated properly with the package.java rmic -d .

security.sun. Lesson 7: Packages and Java Archive (JAR) Start the Server Unix: cd /home/zelda/public_html/classes java -Djava.rmi.policy=client2/java.rmi.sun.class WIDTH=300 HEIGHT=300> </APPLET> </BODY> </HTML> To run the applet with appletviewer.policy=client2\java.codebase= file:c:\home\zelda\public_html\classes -Djava.codebase= http://kq6py/~zelda/classes -Djava.eng.policy= server\java.com fr FR Win32: cd \home\zelda\classes java -Djava.2000 12:34:01] .codebase= http://kq6py/~zelda/classes -Djava.hostname=kq6py.sun.rmi.server.eng.07.rmi.hostname=kq6py.Java (TM) Language Basics.server.sun.eng.com -Djava.policy server\RemoteServer Start RMIGermanApp Here is the HTML code to load the German applet.rmi.policy client2/RMIClient2 kq6py.server. invoke the HTML file from the directory just above client1 as follows: cd /home/zelda/classes appletviewer rmiGapp.rmi.hostname=kq6py. Part 2.policy= server/java.security.eng.policy server/RemoteServer Win32: cd \home\zelda\public_html\classes java -Djava.server.com -Djava.class).security. Note the directory/package name prefixed to the applet class name (client1/RMIGermanApp.server.server.server.com -Djava.sun.security.rmi.server.eng.sun.eng.html (5 of 9) [24.com fr FR file:///T|/General/Documentation/Java/Basic Java 2/HTML/jar. <HTML> <BODY> <APPLET CODE=client1/RMIGermanApp.html Start RMIClient2 in French Unix: cd /home/zelda/classes java -Djava.codebase= file:c:\home\zelda\public_html\classes -Djava.com -Djava.policy client2\RMIClient2 kq6py.rmi.hostname=kq6py.

class q RemoteServer_stub. type the following command on one line..class java.class q DataOrder.policy jar is the jar command. Browsers can easily download applets bundled into JAR files.2000 12:34:01] . kq6py% jar Usage: jar {ctxu}[vfm0M] [jar-file] [manifest-file] [-C dir] files . jar cf server. This command is executed in the same directory with the files. The new JAR file is placed in the current directory.class DataOrder. and decompress and unpack files from.class Send. JAR files make it easy to deploy programs that consist of many files.html (6 of 9) [24. and the download goes much more quickly than if the applet and its related files were not bundled into a JAR file. Options: -c create new archive -t list table of contents for archive -x extract named (or all) files from archive -u update existing archive -v generate verbose output on standard output -f specify archive file name -m include manifest information from specified file:///T|/General/Documentation/Java/Basic Java 2/HTML/jar.class RemoteServer_stub. one JAR file for each client program. the JAR file.class q RemoteServer_skel. Part 2. If you execute the command from a directory other than where the files are.Java (TM) Language Basics. Server Set of Files Here are the server files: q RemoteServer..class q Send.07. You can see from the help screen that the cf options to the jar command mean create a new JAR file named server.class RemoteServer_skel. and one JAR file for the server program.policy Compress and Pack Server Files To compress and pack the server files into one JAR file. the best way to deploy the two client and server files is to bundle the executables and other related application files into three separate JAR files.jar and put the list of files that follows into it.jar RemoteServer. Lesson 7: Packages and Java Archive (JAR) Using JAR Files to Deploy After testing and debugging. If you type jar with no options. JAR files use the ZIP file format to compress and pack files into. you get the following help screen. you have to specify the full pathname.class q java.

web pages. they need to be in a directory accessible by the web server. all you have to do is move the server.class q RMIFrenchApp.html (top-level web page where user chooses language) q rmiEapp. Example 1: to archive two class files into an archive called classes. Lesson 7: Packages and Java Archive (JAR) manifest file -0 store only.html (second-level web page for German) q MessagesBundle_de_DE. The following command means extract (x) all files from the server. The manifest file name and the archive file name needs to be specified in the same order the 'm' and 'f' flags are specified. jar xf server.jar RMIEnglishApp.properties q MessagesBundle_fr_FR.class q RMIGermanApp. q RMIEnglishApp.properties q MessagesBundle_en_US.jar file (f). and the policy file.policy Compress and Pack Files jar cf applet.html (7 of 9) [24. Because they live on the web.html (second-level web page for French) q rmiGapp.jar: jar cvf classes. Decompress and Unpack Server Files After moving the JAR file to its final location.jar mymanifest -C foo/ . The easiest way to deploy these files is to bundle them all into a JAR file and copy them to their location. translation files.07.jar file to a publicly accessible directory on the server where they are to execute.class file:///T|/General/Documentation/Java/Basic Java 2/HTML/jar.jar': jar cvfm classes.class Example 2: use an existing manifest file 'mymanifest' and archive all the files in the foo/ directory into 'classes.class RMIFrenchApp.html (second-level web page for English) q rmiFapp. the compressed and packed files need to be decompressed and unpacked so you can start the server. use no ZIP compression -M Do not create a manifest file for the entries -C change to the specified directory and include the following file If any file is a directory then it is processed recursively.properties q java. To deploy the server files.Java (TM) Language Basics.2000 12:34:01] . Part 2.jar Foo.class q index.class Bar.jar Fruit Order Set of Files The fruit order set of files (below) consists of applet classes.

Java (TM) Language Basics, Part 2, Lesson 7: Packages and Java Archive (JAR)

RMIGermanApp.class index.html rmiEapp.html rmiFapp.html rmiGapp.html MessagesBundle_de_DE.properties MessagesBundle_en_US.properties MessagesBundle_fr_FR.properties java.policy To deploy the fruit order client files, copy the applet.jar file to its final location. Decompress and Unpack Files An applet in a JAR file can be invoked from an HTML file without being unpacked. All you do is specify the ARCHIVE option to the APPLET tag in your web page, which tells appletviewer the name of the JAR file containing the class file. Be sure to include the package directory when you specify the applet class to the CODE option. You can leave the translation files and policy file in the JAR file. When using appletviewer, the applet invoked from the JAR file will find them in the JAR file. <HTML> <BODY> <APPLET CODE=client1/RMIFrenchApp.class ARCHIVE="applet.jar" WIDTH=300 HEIGHT=300> </APPLET> </BODY> </HTML> However, you do need to unpack the web pages so you can move them to their final location. The following command does this. Everything goes on one line. jar xv applet.jar index.html rmiEapp.html rmiFapp.html rmiGapp.html Note: To run the HTML files from a browser, you need to unpack the JAR file, copy the java.policy file to your home directory and make sure it has the right name (.java.policy for Unix and java.policy for Windows), and install Java Plug-In.

View Order Set of Files
The view order set of files (below) consists of the application class file and the policy file. q RMIClient2.class q java.policy Compress and Pack Files

file:///T|/General/Documentation/Java/Basic Java 2/HTML/jar.html (8 of 9) [24.07.2000 12:34:01]

Java (TM) Language Basics, Part 2, Lesson 7: Packages and Java Archive (JAR)

jar cf vieworder.jar RMIClient2.class java.policy To deploy the view order client files, copy the vieworder.jar file to its final location. Decompress and Unpack Files jar xf vieworder.jar

More Information
You can find more information on packages in the Creating and Using Packages lesson in The Java Tutorial. You can find more information on these and other JAR file format topics in the JAR File Format trail in The Java Tutorial.
[TOP]

Print Button

[ This page was updated: 31-Mar-2000 ]

Products & APIs | Developer Connection | Docs & Training | Online Support Community Discussion | Industry News | Solutions Marketplace | Case Studies Glossary - Applets - Tutorial - Employment - Business & Licensing - Java Store - Java in the Real World FAQ | Feedback | Map | A-Z Index For more information on Java technology and other software from Sun Microsystems, call:

(800) 786-7638

Outside the U.S. and Canada, dial your country's AT&T Direct Access Number first.

Sun Microsystems, Inc. Copyright © 1995-2000 Sun Microsystems, Inc.
All Rights Reserved. Terms of Use. Privacy Policy.

file:///T|/General/Documentation/Java/Basic Java 2/HTML/jar.html (9 of 9) [24.07.2000 12:34:01]

Java (TM) Language Basics, Part 2, Lesson 8: Object-Oriented Programming

Java Technology Home Page

A-Z Index Java Developer Connection(SM)

Online Training

Downloads, APIs, Documentation Java Developer Connection Tutorials, Tech Articles, Training Online Support Community Discussion News & Events from Everywhere Products from Everywhere How Java Technology is Used Worldwide Print Button

Java Programming Language Basics, Part 2
TM

Lesson 8: Object-Oriented Programming
[<<BACK] [CONTENTS] [NEXT>>]

You have probably heard a lot of talk about object-oriented programming. And, if the JavaTM programming language is your first experience with an object-oriented language, you are probably wondering what all the talk is about. You already know a little about object-oriented programming because after working the example programs in Java Programming Language Basics, Part 1 and Part 2, you are somewhat familiar with the object-oriented concepts of class, object, instance, and inheritance plus the access levels public and private. But mostly, you have been doing object-oriented programming without really thinking about it. And that is one of the great things about the Java programming language. It is inherently object oriented. To help you gain a deeper understanding of object-oriented programming and its benefits, this lesson presents a very brief overview of object-oriented concepts and terminology as they relate to some of the example code presented in this tutorial. q Object-Oriented Programming Defined
q q q q q q q q q

Classes Objects Well-Defined Boundaries and Cooperation Inheritance Polymorphism Data Access Levels Your Own Classes Program Improvements More Information

Object-Oriented Programming Defined
Object-oriented programming is a method of programming based on a hierarchy of classes, and well-defined and cooperating objects.

file:///T|/General/Documentation/Java/Basic Java 2/HTML/oo.html (1 of 10) [24.07.2000 12:34:11]

but in the Java language. The ExampleProgram class from the simple program in the first lesson of Part 1 is a programmer-written class that uses the java. String text2 = text.concat( "that uses classes and objects").2000 12:34:11] .System class used in the example defines such things as standard input. the java.println(text2). class ExampleProgram { public static void main(String[] args){ System. class ExampleProgram { public static void main(String[] args){ String text = new String("I'm a simple Program ").println(text). you can call a method such as the String. and error streams. Part 2. the Java platform creates a String object from the character string passed to the System. In the example. all program data is wrapped in a class. output. } } The output looks like this: I'm a simple Program I'm a simple Program that uses classes and objects Objects An instance is an executable copy of a class.out.concat method that adds text to the original string.out.out. If you want access to the String methods.println call. There can be any number of objects of a given file:///T|/General/Documentation/Java/Basic Java 2/HTML/oo.System class from the Java platform API libraries to print a character string to the command line. Lesson 8: Object-Oriented Programming Classes A class is a structure that defines the data and the methods to work on that data.lang. a character string can be used anywhere a method expects to receive a String object. System. you can rewrite the example program to create a String object as follows.String class defines character strings. whether it is a class you write or a class you use from the Java platform API libraries. Another name for instance is object. This way. The java.07. During execution.lang.out.println("I'm a simple Program").html (2 of 10) [24. you do not see an explicit use of the String class. } } Classes in the Java platform API libraries define a set of objects that share a common structure and behavior.Java (TM) Language Basics. System. and access to system properties. When you write programs in the Java language. In contrast.lang. but your program cannot call any of the String class methods because it did not instantiate the String object.

String.java class in memory as well.2000 12:34:11] . The System class is never instantiated by the ExampleProgram class because it contains only static variables and methods. but it is instantiated behind the scenes by the JavaTM virtual machine1 (VM). This section changes the example program to display the concatenated character string in a JLabel component in a user interface to further illustrate the concepts of well-defined class boundaries and object cooperation. the java. The program code to place the text in a label to display it in a user interface uses a number of cooperating classes. cannot be instantiated by a program.html (3 of 10) [24. String. and StringBuffer objects cooperated to print a concatenated character string to the command line.lang.Java (TM) Language Basics. Well-Defined Boundaries and Cooperation Class definitions must allow objects to cooperate during execution. four different String objects are created for the concatenation operation. Also. because String objects cannot be edited. and therefore. Lesson 8: Object-Oriented Programming class in memory at any one time. text object. Part 2.07. Each class has its file:///T|/General/Documentation/Java/Basic Java 2/HTML/oo. In the previous section. text2 object. there is an instance of the ExampleProgram. you saw how the System.concat method. In the last example. Besides the String object.concat method converts the String objects to StringBuffer (editable) string objects to do the concatenation. and a String object created behind the scenes from the " that uses classes and objects" character string passed to the String.

awt. class ExampleProgram extends JFrame { public ExampleProgram(){ String text = new String("I'm a simple Program ").add(panel). getContentPane(). import javax. frame.addWindowListener(l). q ExampleProgram defines the program data and methods to work on that data. q JLabel defines a user interface component to display static text. panel.awt. q JFrame defines the top-level window including the window title and frame menu. and where appropriate.2000 12:34:11] .html (4 of 10) [24. q String defines a character string to create the label. Part 2. While each class has its own specific purpose. and uses the default layout manager (java.awt.setTitle("Fruit $1.*.Color. JPanel panel = new JPanel(). WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System. import java.setBackground(Color. contains the label.add(label). String text2 = text.*. q WindowEvent defines behavior for (works with) the Close option on the frame menu. } }.FlowLayout) to position the label on the display. import java. the classes are defined to work with objects of another class.event. } public static void main(String[] args){ ExampleProgram frame = new ExampleProgram(). panel.concat( "that uses classes and objects"). q JPanel defines the background color. frame. Lesson 8: Object-Oriented Programming own function and purpose as summarized below.swing. JLabel label = new JLabel(text2).07. they all work together to create the simple user interface you see here. file:///T|/General/Documentation/Java/Basic Java 2/HTML/oo.exit(0). frame.white).25 Each").pack().Java (TM) Language Basics.

Container.Object. Part 2.Java (TM) Language Basics. The java. Inheritance defines relationships among classes in an object-oriented language.Object and implement its methods. java. all classes descend from java.awt.awt.Object methods are also shown because they are inherited and implemented by all of its subclasses. which finally inherits from java. which inherits fields and methods from java.lang.Component. and each subclass adds its own fields and methods as needed. each class adds its own set of class-specific fields and methods to what it inherits from its superclass or superclasses.07.awt.Object for the classes in the user interface example above.html (5 of 10) [24.awt.2000 12:34:11] .lang.Frame. which inherits fields and methods from java. Lesson 8: Object-Oriented Programming frame.Object defines the core set of behaviors that all classes have in common.lang.setVisible(true). file:///T|/General/Documentation/Java/Basic Java 2/HTML/oo.lang.JFrame class inherits fields and methods from java. The java. As you move down the hierarchy. } } Inheritance One object-oriented concept that helps objects work together is inheritance. In the Java programming language.swing. The following diagram shows the class hierarchy as it descends from java. which is every class in the Java API libraries.lang.

Set s = new HashSet(). You saw an example of polymorphism in Part 2. Data Access Levels Another way classes work together is through access level controls. String custID = "munchkin". s. it can accept any component object. You get even more cooperation and efficiency when the objects are united by a common superclass. Integer creditCard = new Integer(25). Classes By default. Lesson 5: Collections where a collection object can contain any type of object as long as it descends from java.lang. Lesson 8: Object-Oriented Programming Polymorphism Another way objects work together is to define methods that take other objects as parameters.07.Object as a parameter. and their fields and methods have access levels to specify how they can be used by other objects during execution. Classes.lang. there are times when you will want to explicitly control access.Object. it can accept any object in the entire Java platform.Component as a parameter. s. the default access level is in effect. This form of cooperation is called polymorphism. All classes in the Java programming language have an inheritance relationship. It is repeated here to show you that Set collection can add a String object and an Integer object to the Set because the Set. If you define a method that takes a java.add(custID). While cooperation among objects is desirable.html (6 of 10) [24. For example.lang. and specifying access levels is the way to gain that control. When you do not specify an access level. if you define a method that takes a java.add(creditCard).Object class.awt.2000 12:34:11] .Java (TM) Language Basics. Part 2.add method is defined to accept any class instance that traces back to the java. a class can be used only by instances of other classes in file:///T|/General/Documentation/Java/Basic Java 2/HTML/oo.

or package. they have already been designed with the above concepts in mind. in Part 2. You might recall that in Part 1. the field or method access level is package by default. You get an error when you try to interpret a class with an access level of package with the appletviewer tool. Your Own Classes When you use the Java API library classes. and classes in the same package.html (7 of 10) [24. package: A package field or method is accessible to other classes in the same package. the applet class had to be declared public so it could be accessed by the appletviewer tool because the appletviewer program is created from classes in another package. class DbaAppl extends Applet implements ActionListener { Also. its subclasses. In Part 1. file:///T|/General/Documentation/Java/Basic Java 2/HTML/oo.07. Lesson 8: Object-Oriented Programming the same package. private Connection c. and password for establishing the database access are all private. public.lang. and they are designed to cooperate with each other where appropriate. This is to prevent an outside class from accessing them and jeopardizing the database connection. Part 2. user name. The same is true if the access level is protected or private. its access level is package by default. If no access level is specified. In Part 2. Here is an applet class declared to have a public access level: public class DbaAppl extends Applet implements ActionListener { Without the public access level (shown below). they have well-defined boundaries. They all descend from java.Java (TM) Language Basics. protected: A protected field or method is accessible to the class itself. Lesson 6: Internationalization the server classes are made public so client classes can access them. Lesson 3: Building Applets. Fields and Methods Fields and methods can be declared private. Part 1. Lesson 7: Database Access and Permissions the connection. public: A public field or method is accessible to any class of any parentage in any package. or compromising the secret user name and password information. protected.Object giving them an inheritance relationship. A class can be declared public to make it accessible to all class instances regardless of what package its class is in.2000 12:34:11] . private: A private field or method is accessible only to the class in which it is defined. Lesson 6: Internationalization server data accessed by client programs is made public.

Java (TM) Language Basics. and resetting the display are closely related and easily form a functional module. When you change a class. Likewise. displaying the data.07. You could. Part 2. background color setting. cooperate. But what about when you write your own classes? How can you be sure your classes have well-defined boundaries. and pears sold by the month. You will. display data. It could access the stored data to print reports on apples. and make use of inheritance? One way is to look at the functions you need a program to perform and separate them into distinct modules where each functional module is defined by its own class or group of classes. Lesson 5: Collections lesson. you only have to recompile that one class.2000 12:34:11] . Well-Defined and Cooperating Classes Looking at the RMIClient2 class from the Part 2. But in a larger program with more data processing. If you need to write a class that has functionality similar to a class in the Java API libraries. peaches. you will not find a String class that takes an Integer object as input because that goes beyond the well-defined boundary for a String. it makes sense to extend that API library class and use its methods rather than write everything from scratch. as long as you did not change any part of its public interface. the storing and printing of customer IDs could be expanded to store and print a wider range of data. Getting data. or throughout a given season. Inheritance Deciding what classes your program needs means separating functions into modules. however. but making your code more efficient and easier to maintain means looking for common functions where you can use inheritance. Making application code modular by separating out functional units makes it easier to update and maintain the source code. and pears sold during the year. In such a case. have a class that defines how to store customer IDs. and reset the display. peaches. You could also have another class that defines report printing. and tracks the number of apples. print customer IDs. find the Integer class has a method for converting its integer value to a String so its value can be displayed in a user interface component. frame menu closing behavior. and a customized title. store customer IDs. Lesson 5: Collections lesson extends JFrame to leverage the ready-made functionality it provides for a program's top-level window including.html (8 of 10) [24. you can see it performs the following functions: Get data. per customer. which only accepts String objects. and another class for printing it in various forms. for example. if you want to add customized behavior to an existing file:///T|/General/Documentation/Java/Basic Java 2/HTML/oo. Lesson 8: Object-Oriented Programming For example. it would make sense to have a separate class for storing data. The RMIClient2 class from the Part 2.

file:///T|/General/Documentation/Java/Basic Java 2/HTML/oo. make it private. Here is one possible solution for the RMIClient1. Lesson 7: Packages and JAR Files. you can extend that class and add the functionality you want.07. _______ 1 As used on this web site. At that time.java and RMIClient2. and see what the compiler has to say about it. and use packages and access levels to protect your application data from all other objects executing in the system. Can you explain why the actionPerformed method cannot be made private? If not. public. the server classes had to be made public and the DataOrder class fields also had to be made public so the client programs can access them. Going back to Part 2. the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform. you can update your class by changing a field definition and the corresponding method implementation. or package as needed and allow other objects to manipulate their private data by calling the methods only.Java (TM) Language Basics.html (9 of 10) [24. and methods an access level so they are not accessed inappropriately by other objects. you might want to create your own JButton class with a different look. Then your program can instantiate your button class instead of the JButton class whenever you need a button with the new look you created. fields. Part 2. Program Improvements It is always best to restrict access as much as possible. fields. and methods. Lesson 8: Object-Oriented Programming class. All methods have an access level of public. More Information You can find more information on Object-oriented programming concepts files in the Object-Oriented Programming Concepts trail in The Java Tutorial. Access Levels You should always keep access levels in mind when you declare classes. This way. Then they make their methods protected. you can write your own class that extends JButton and implement it to appear the way you want. but other objects that access that data do not need to be changed because their interface to the data (the method signature) has not changed. To do this. Consider which objects really need access to the data.java client programs.2000 12:34:11] . no access level was specified for the other classes and fields so they are all package by default. For example. Most object-oriented applications do not allow other objects to access their fields directly by declaring them private. A good exercise would be to go back to the client classes and give the classes. run the javac command to compile.

html (10 of 10) [24.Tutorial .Java (TM) Language Basics. Inc.S. call: (800) 786-7638 Outside the U. dial your country's AT&T Direct Access Number first.Employment . file:///T|/General/Documentation/Java/Basic Java 2/HTML/oo. Privacy Policy.Java in the Real World FAQ | Feedback | Map | A-Z Index For more information on Java technology and other software from Sun Microsystems. Part 2. Lesson 8: Object-Oriented Programming [TOP] Print Button [ This page was updated: 31-Mar-2000 ] Products & APIs | Developer Connection | Docs & Training | Online Support Community Discussion | Industry News | Solutions Marketplace | Case Studies Glossary . Copyright © 1995-2000 Sun Microsystems. Sun Microsystems.2000 12:34:11] .Business & Licensing .07. and Canada.Applets . All Rights Reserved. Inc. Terms of Use.Java Store .

Privacy Policy.pawlan@eng. All Rights Reserved. With this foundation.sun. Training Online Support Community Discussion News & Events from Everywhere Products from Everywhere How Java Technology is Used Worldwide Print Button Java Programming Language Basics TM In Closing [<<BACK] [CONTENTS] After completing JavaTM Programming Language Basics. Monica Pawlan is a staff writer on the JDC team. Inc. and loves to explore emerging technologies. Sun Microsystems.Java Store .Employment . APIs. Part 1 and Part 2 of this training series you should have a solid understanding of JavaTM programming basics and how to use some of the more common application programming interfaces (APIs) available in the Java platform. She has a background in 2D and 3D graphics. Inc. or the documents available on the java. Tech Articles. In particular. database products. file:///T|/General/Documentation/Java/Basic Java 2/HTML/end. dial your country's AT&T Direct Access Number first.html [24.S. you can explore Java programming on your own with the help of the articles and training materials available on the JDC. and Canada. security.Applets .com Print Button [ This page was updated: 31-Mar-2000 ] Products & APIs | Developer Connection | Docs & Training | Online Support Community Discussion | Industry News | Solutions Marketplace | Case Studies Glossary .Tutorial . Copyright © 1995-2000 Sun Microsystems. monica.Java (TM) Basics: In Closing Java Technology Home Page A-Z Index Java Developer Connection(SM) Online Training Downloads. Terms of Use.2000 12:34:13] .com site. one tutorial you might find the Writing Advanced Applications for the JavaTM Platform a good place to continue your studies.sun. call: (800) 786-7638 Outside the U.Java in the Real World FAQ | Feedback | Map | A-Z Index For more information on Java technology and other software from Sun Microsystems. Documentation Java Developer Connection Tutorials.07.Business & Licensing .

//Create text areas creditNo = new JTextArea(). panel. cost = new JLabel("Total Cost:").rmi.setBackground(Color.2000 12:34:15] .add(customerNo).*. java. java. custID = new JLabel("Customer ID:"). icost.*. reset.awt.*. reset = new JButton("Reset"). peachesNo.*.swing.server.awt.add(custID). itotal. total = new JLabel("Total Items:"). panel. pearsNo = new JTextArea().add(panel). static Send send.07. icost = new JTextArea(). reset. class RMIClient2 extends JFrame implements ActionListener{ JLabel creditCard.java (1 of 3) [24.util. HashSet s = new HashSet().file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitCollect/RMIClient2. panel. apples = new JLabel("Apples:"). JTextArea creditNo. java. peaches = new JLabel("Peaches:").rmi.addActionListener(this). file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitCollect/RMIClient2.io.add(creditCard). pears = new JLabel("Pears:").add(creditNo). RMIClient2(){ //Begin Constructor //Create labels creditCard = new JLabel("Credit Card:"). total. panel.event. custID. applesNo = new JTextArea(). String customer.*. applesNo.net. import java. javax.*. panel.GridLayout.white). peaches.Color. JPanel panel.*. itotal = new JTextArea().java import import import import import import import import java. //Add components to panel columns //going left to right and top to bottom getContentPane(). view.awt. //Create buttons view = new JButton("View Order"). customerNo. //Create panel for 2-column layout //Set white background color panel = new JPanel(). cost. pearsNo. java. java. JButton view. panel.add(apples).2)).setLayout(new GridLayout(0. java.addActionListener(this). pears. panel. clicked. peachesNo = new JTextArea(). apples. customerNo = new JTextArea().

} //Print customer IDs public void print(){ if(s. panel. pearsNo. }else{ System.setText(unit). int items. price = new Double(cost).java panel.custID).out.println("Customer ID added").apples).add(reset). customerNo.size()!=0){ Iterator it = s. //Get customer ID and add to list addCustomer(order. //If View button pressed //Get data from server and display it if(source == view){ try{ order = send.add(pearsNo).add(view).custID). panel. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitCollect/RMIClient2. double cost.println("No customer IDs available").07. while(it.getOrder().setText(order.toString(). panel.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitCollect/RMIClient2. panel. icost.println(s). panel. panel.out. panel. DataOrder order = new DataOrder().java (2 of 3) [24.peaches).setText(order.add(applesNo). } //End Constructor //Create list of customer IDs public void addCustomer(String custID){ s.add(itotal).next()). panel.out.pears). peachesNo.add(total). String unit. Double price.hasNext()){ System.getSource(). cost = order. panel. panel.add(custID).add(icost). creditNo.2000 12:34:15] . i. } System.iterator().setText(order.setText(order. Integer itms.out.println(it.add(peaches).add(cost).icost.add(pears).setText(order.add(peachesNo). unit = price.cardnum). System. applesNo. } } public void actionPerformed(ActionEvent event){ Object source = event.

setTitle("Fruit Order"). icost.2000 12:34:15] .java items = order.setText("").setText(""). } catch(java. } } public static void main(String[] args){ RMIClient2 frame = new RMIClient2().setVisible(true).setText("").exit(0). customerNo. frame.setText(""). send = ((Send) Naming.RemoteException e){ System.setSecurityManager(new RMISecurityManager()). itotal. frame. } }. if(System. peachesNo. } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitCollect/RMIClient2. } catch (java.println("Cannot access data in server").rmi.out.println("Cannot access data in server").setText("").NotBoundException e) { System. } catch(java. } try { String name = "//" + args[0] + "/Send". frame.out.pack().println("Cannot access data in server"). } //If Reset button pressed //Clear all fields if(source == reset){ creditNo.setText(i).file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitCollect/RMIClient2. frame.lookup(name)).java (3 of 3) [24. WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.println("Cannot access data in server"). } //Print print().itotal.out.MalformedURLException e) { System. i = itms.setText("").07.rmi.net.getSecurityManager() == null) { System.RemoteException e) { System.addWindowListener(l).rmi.out.setText("").toString(). } catch (java. applesNo. pearsNo. itms = new Integer(items). itotal.

peachchk. peachqnt = new JTextField(). private JTextArea items. customer.getString("1col")).server. private JTextField appleqnt.awt. pearchk. peachqnt. private NumberFormat numFormat. country. //Create labels and text field components applechk = new JLabel(" " + messages.io. import java. import java. import java.Color. appleqnt = new JTextField().*. import server. peachchk = new JLabel(" " + messages.awt. col2.*. appleqnt.swing. pearchk = new JLabel(" " + messages.addActionListener(this).*. import import import import java. import java. peachqnt. applechk. pearqnt. private static ResourceBundle messages. class RMIClient1 extends JFrame implements ActionListener{ private private private private JLabel JLabel JLabel JLabel col1.java (1 of 4) [24. private static Send send.event. creditCard = new JTextField(). //Create left and right column labels col1 = new JLabel(messages.*.*. custID.getString("pears")).*. cost. java.addActionListener(this).setNextFocusableComponent(creditCard). totalItems. totalCost. private JButton purchase.*.awt.GridLayout.getString("title")). private JTextField creditCard.getString("peaches")). pearqnt.text.getString("card")).file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/OO/client1/RMIClient1. pearqnt = new JTextField(). import java.util. private JPanel panel.addActionListener(this).2000 12:34:17] .getString("apples")). cardNum.07. //Internationalization variables private static Locale currentLocale.rmi. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/OO/client1/RMIClient1. java.net. cardNum = new JLabel(" " + messages.*.java package client1. reset. pearqnt. javax. import java. private static String language. private RMIClient1(){ //Begin Constructor setTitle(messages.getString("2col")).rmi.*. col2 = new JLabel(messages.

//Create buttons and make action listeners purchase = new JButton(messages.2000 12:34:17] . file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/OO/client1/RMIClient1. String text.addActionListener(this).add(peachchk).add(purchase). reset = new JButton(messages. } //End Constructor public void actionPerformed(ActionEvent event){ Object source = event. panel.add(cardNum).addActionListener(this).add(creditCard).java (2 of 4) [24. peachesNo.add(totalCost). panel.add(panel).getString("cost")).getString("purchase")). panel. panel. panel.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/OO/client1/RMIClient1. Double cost.getString("items")).add(appleqnt).setLayout(new GridLayout(0.07. panel.2)). reset.getString("reset")). panel.getString("customer")).add(pearchk).setBackground(Color. custID = new JLabel(" " + messages. DataOrder order = new DataOrder().add(col2).add(applechk). purchase. panel. panel.getSource(). panel. //Add components to panel columns //going left to right and top to bottom getContentPane(). totalCost = new JLabel(" " + messages.add(cost). //Create a panel for the components panel = new JPanel(). //Create labels and text area components totalItems = new JLabel(" " + messages.add(col1). panel. pearsNo. panel. panel. panel. text2. cost = new JTextArea(). items = new JTextArea().white). //Set panel layout to 2-column grid //on a white background panel.add(pearqnt).add(totalItems).add(reset). panel. panel. Integer applesNo. num. panel.add(custID).add(items).java customer = new JTextField().add(peachqnt). panel. panel.add(customer).

java //If Purchase button pressed .apples = appleqnt.apples). . .25).items.setText(text2).length() > 0){ //Catch invalid number error try{ pearsNo = Integer.pears). //Calculate total items if(order.getText().itotal += 0.java (3 of 4) [24. order.out. } //Create number formatter numFormat = NumberFormat.RemoteException e) { System.setText(messages.NumberFormatException e){ pearqnt.itotal += 0.itotal).intValue(). } } else { order. order.itotal += pearsNo.getString("send")). text2 = numFormat.icost = (order.lang.peaches = peachqnt. }catch(java. }catch(java.getString("invalid")).07.setText(text).2000 12:34:17] .getText().valueOf(order. } } else { order.apples. try{ send. } catch (java. } } else { order.getText().icost).setText(messages.NumberFormatException e){ appleqnt.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/OO/client1/RMIClient1. this. if(source == purchase){ //Get data from text fields order. order.setText(messages. } if(order. } if(order. //Calculate and display running cost order.custID = customer.cost.length() > 0){ //Catch invalid number error try{ peachesNo = Integer. order. }catch(java.lang. //Display running total text = numFormat.intValue().getText().pears = pearqnt.itotal * 1. } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/OO/client1/RMIClient1.pears.length() > 0){ //Catch invalid number error try{ applesNo = Integer.NumberFormatException e){ peachqnt.rmi.itotal += 0.getString("invalid")).cardnum = creditCard.format(order. order.lang.valueOf(order.valueOf(order.getText().format(order. this.getString("invalid")).println(messages.itotal += applesNo.peaches). order.itotal += peachesNo.peaches.sendOrder(order). order.intValue().getNumberInstance(currentLocale).

} } public static void main(String[] args){ if(args. order.setText(text2).out. messages = ResourceBundle. } catch(java.java (4 of 4) [24.cost.setText(""). country = new String(args[2]). country).getString("nollokup")).getString("nolookup")).RemoteException e){ System. } catch(java.setText("").setText("").println(language + country). text2 = cost. } catch (java.println(messages.println(messages.out.getBundle("client1" + File. country = new String ("US").lookup(name)).toString(). text = num.java //If Reset button pressed //Clear all fields if(source == reset){ creditCard.07. pearqnt.setText(text). appleqnt.items.setVisible(true).setText(""). System.separatorChar + "MessagesBundle".println("English"). currentLocale). } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/OO/client1/RMIClient1.rmi.out. } try { String name = "//" + args[0] + "/Send".exit(0).itotal).length != 3) { language = new String("en"). if(System.net. this.itotal = 0.println(messages.MalformedURLException e) { System.icost = 0.2000 12:34:17] .setText(""). this.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/OO/client1/RMIClient1. } }.getSecurityManager() == null) { System. customer.getString("nolookup")). } currentLocale = new Locale(language. creditCard.rmi. frame. frame.setSecurityManager(new RMISecurityManager()). }else{ language = new String(args[1]). num = new Integer(order.out.out.setText("").toString().NotBoundException e) { System. RMIClient1 frame = new RMIClient1().icost). frame. order. send = ((Send) Naming. System. WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.pack().addWindowListener(l). cost = new Double(order. peachqnt.

rmi. class RMIClient2 extends JFrame implements ActionListener { private private private private private private private JLabel creditCard.addActionListener(this).getString("items")). import java. peaches. total = new JLabel(messages.GridLayout. customerNo = new JTextArea(). import import import import java. pearsNo = new JTextArea(). import java. pears. cost. peaches = new JLabel(messages. //Internationalization variables private static Locale currentLocale. itotal. apples = new JLabel(messages.getString("peaches")). java. customerNo.*. import server. icost = new JTextArea().*. pears = new JLabel(messages. JPanel panel.2000 12:34:19] . import java.text. apples.io.*. cost = new JLabel(messages.getString("view")).getString("cost")). peachesNo = new JTextArea().swing.*.*.java (1 of 4) [24. itotal = new JTextArea(). applesNo = new JTextArea().server. import java. icost. reset.Color. //Create buttons view = new JButton(messages.awt. Set s = null. String customer. pearsNo. JButton view.getString("title")). clicked.*. import java. private NumberFormat numFormat.*.FileInputStream. country.awt.event. javax. //Create labels creditCard = new JLabel(messages.awt.java package client2. private RMIClient2(){ //Begin Constructor setTitle(messages.util. custID. import java. JTextArea creditNo. //Create text areas creditNo = new JTextArea().07. peachesNo. custID = new JLabel(messages.getString("card")). import java.io.net. import java. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/OO/client2/RMIClient2.*.RandomAccessFile. java. applesNo.*. total.*.*.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/OO/client2/RMIClient2.io.getString("apples")). static Send send.rmi. private static ResourceBundle messages. view. private static String language.getString("pears")).getString("customer")). import java.File.io.

add(customerNo).add(reset). panel. panel.add(creditNo).addActionListener(this). panel.setLayout(new GridLayout(0. } //End Constructor //Create list of customer IDs private void customerList(String custID){ if(s==null){ s = new HashSet().getString("reset")).add(pears).java reset = new JButton(messages.next(). panel. //Create panel for 2-column layout //Set white background color panel = new JPanel().add(itotal).2)). panel. panel. while(it. } } }else{ System.white).add(icost).iterator().setBackground(Color. panel.add(creditCard). //Add components to panel columns //going left to right and top to bottom getContentPane().add(peachesNo).out. System.util.NoSuchElementException e){ System. reset.out. panel.2000 12:34:19] .out.println(customer). s.add(custID).java (2 of 4) [24. panel.add(custID). panel.add(cost).add(panel).add(pearsNo).07.add(total). } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/OO/client2/RMIClient2. panel. panel. } } //Print customer IDs private void print(){ if(s!=null){ Iterator it = s. panel. panel.println("No data available").file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/OO/client2/RMIClient2.hasNext()){ try{ String customer = (String)it. panel.println("No customer IDs available"). panel.add(apples).add(view).add(applesNo). }else{ s. panel. }catch (java.add(peaches).add(custID). panel.

peachesNo.setText(unit).setText("").peaches).RemoteException e) { System. price = new Double(order.setText(order. //If View button pressed //Get data from server and display it if(source == view){ try{ order = send. unit = numFormat. Integer itms. } //Print print(). Double price. i = numFormat.format(order.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/OO/client2/RMIClient2.setText(order. } currentLocale = new Locale(language. //Get customer ID and add to list customerList(order.java (3 of 4) [24.setText(order.cardnum).apples). itotal.setText("").07.pears). applesNo.itotal). country = new String ("US").setText(order. customerNo. } } public static void main(String[] args){ if(args.getBundle("client2" + File.2000 12:34:19] .setText("").out. System. country). messages = ResourceBundle.getOrder(). }else{ language = new String(args[1]).setText(order.setText(""). int items. //Create number formatter numFormat = NumberFormat.setText(""). pearsNo.icost). creditNo. double cost.getNumberInstance(currentLocale). icost.separatorChar + file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/OO/client2/RMIClient2.setText("").setText("").println("English").custID). applesNo.java public void actionPerformed(ActionEvent event){ Object source = event.length != 3) { language = new String("en"). } catch (java.rmi.println("Cannot access data in server"). itms = new Integer(order.out. icost.println(language + country).setText(i). country = new String(args[2]).format(price). System.custID). customerNo. String unit. i. itotal.itotal).out. } //If Reset button pressed //Clear all fields if(source == reset){ creditNo. DataOrder order = new DataOrder(). pearsNo. peachesNo.getSource().

RemoteException e){ System.exit(0).rmi. currentLocale). frame. frame. } catch (java.println(messages.getString("nolookup")).getString("nolookup")).2000 12:34:19] .MalformedURLException e) { System.rmi.out. } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/OO/client2/RMIClient2.net.println(messages. } try { String name = "//" + args[0] + "/Send". frame.07. if(System.java (4 of 4) [24.getSecurityManager() == null) { System. } catch(java.setSecurityManager(new RMISecurityManager()). } }.java "MessagesBundle".getString("nolookup")).out.NotBoundException e) { System.out. } catch(java.println(messages.setVisible(true).file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/OO/client2/RMIClient2.lookup(name)).pack(). send = ((Send) Naming.addWindowListener(l). RMIClient2 frame = new RMIClient2(). WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.

itotal = new JTextArea(). peaches = new JLabel(messages. peaches. import java. itotal. icost = new JTextArea().GridLayout.util. RMIClient2(){ //Begin Constructor setTitle(messages.server. javax.2000 12:34:21] .getString("items")). reset = new JButton(messages. apples = new JLabel(messages. apples. NumberFormat numFormat.07.*.rmi.awt.io. applesNo.getString("card")). JTextArea creditNo.swing.getString("title")).getString("cost")).awt. customerNo = new JTextArea(). String customer. pearsNo.getString("reset")).getString("view")). //Create text areas creditNo = new JTextArea(). import java. //Internationalization variables static Locale currentLocale. total = new JLabel(messages.getString("peaches")). static String language. Set s = null. cost. applesNo = new JTextArea(). JPanel panel. clicked.addActionListener(this). reset. java. peachesNo.*. total. import java. import java. pears = new JLabel(messages. view.*.java (1 of 4) [24. java.awt. peachesNo = new JTextArea(). import import import import java. reset.net.*. static ResourceBundle messages. cost = new JLabel(messages. //Create buttons view = new JButton(messages. icost. custID. import server. import java. class RMIClient2 extends JFrame implements ActionListener { JLabel creditCard. country. import java. JButton view.event. pears.getString("customer")). custID = new JLabel(messages.rmi.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/JAR/client2/RMIClient2. static Send send. //Create panel for 2-column layout file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/JAR/client2/RMIClient2.getString("pears")). //Create labels creditCard = new JLabel(messages.*.*.java package client2.Color.*.text.addActionListener(this). customerNo. pearsNo = new JTextArea().getString("apples")).*.*.

} //End Constructor //Create list of customer IDs public void addCustomer(String custID){ s.add(reset). panel. panel.getSource().add(creditNo). //Add components to panel columns //going left to right and top to bottom getContentPane(). panel. System.add(peaches). panel. panel. panel.white).add(apples).out. panel. panel.add(panel).add(itotal). } } public void actionPerformed(ActionEvent event){ Object source = event. }else{ System.add(applesNo).add(custID).add(pears). DataOrder order = new DataOrder().add(pearsNo). panel. Integer itms. panel.add(view).iterator().hasNext()){ System. panel. panel. //If View button pressed //Get data from server and display it if(source == view){ file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/JAR/client2/RMIClient2.07.setLayout(new GridLayout(0.println(s). while(it.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/JAR/client2/RMIClient2.out. Double price. panel.println(it.println("Customer ID added").println("No customer IDs available").size()!=0){ Iterator it = s. panel. String unit.add(total). panel.setBackground(Color.add(creditCard).add(icost).2000 12:34:21] .add(customerNo). panel. panel.add(custID).next()). i.add(peachesNo).2)). panel. } //Print customer IDs public void print(){ if(s. double cost. int items.out.out.java //Set white background color panel = new JPanel().java (2 of 4) [24. } System.add(cost).

itotal). itotal. peachesNo.RemoteException e) { System.setText(order.setText(order.println("Cannot access data in server").length != 3) { language = new String("en"). } } public static void main(String[] args){ if(args. System. customerNo.exit(0). } }.setText(i).setText(order. country = new String(args[2]).peaches).custID). pearsNo. messages = ResourceBundle.itotal).setText(""). } currentLocale = new Locale(language.setText("").getNumberInstance(currentLocale).setText(""). } //Print print(). frame.addWindowListener(l). unit = numFormat. applesNo.setText(order.2000 12:34:21] . country). pearsNo.setText(""). peachesNo.getOrder().out.setVisible(true).java (3 of 4) [24.setText("").separatorChar + "MessagesBundle". creditNo.setText("").java try{ order = send.out.println("English"). }else{ language = new String(args[1]).format(price).getBundle("client2" + File. country = new String ("US"). i = numFormat.out.apples).setText(unit). file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/JAR/client2/RMIClient2. WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.rmi. price = new Double(order.icost).println(language + country).pears). //Create number formatter numFormat = NumberFormat. currentLocale). customerNo.pack(). icost.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/JAR/client2/RMIClient2. applesNo.custID). } //If Reset button pressed //Clear all fields if(source == reset){ creditNo. System. } catch (java. icost. RMIClient2 frame = new RMIClient2(). itotal. itms = new Integer(order.setText(order.format(order. frame.07. frame. //Get customer ID and add to list addCustomer(order.cardnum).setText("").

2000 12:34:21] .lookup(name)). } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/JAR/client2/RMIClient2.getString("nolookup")).file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/JAR/client2/RMIClient2.getString("nolookup")).07. send = ((Send) Naming.setSecurityManager(new RMISecurityManager()).net.rmi.getString("nolookup")). } catch (java.println(messages.println(messages.NotBoundException e) { System.RemoteException e){ System.java (4 of 4) [24.out.println(messages.out.getSecurityManager() == null) { System.rmi.MalformedURLException e) { System. } catch(java. } catch(java. } try { String name = "//" + args[0] + "/Send".java if(System.out.

awt. ObjectInputStream ois = new ObjectInputStream(fis).BorderLayout.println("File not found").out.io.io.awt. } public void sendOrder(DataOrder order){ value += 1.out.io. num = new Integer(value). } return order. orders = num. }catch (java.readObject().println("Unable to read file"). }catch (java.writeObject(order).*.out.out.event. import java.toString().println("File not found"). num = new Integer(get). }catch (java. } } public DataOrder getOrder(){ DataOrder order = null. public class RemoteServer extends UnicastRemoteObject implements Send { Integer num = null.net.io. }catch (java. orders = num.server.awt.IOException e){ System.*.07. import java.rmi. int value = 0.io. try{ FileOutputStream fos = new FileOutputStream(orders).*. ObjectOutputStream oos = new ObjectOutputStream(fos). }catch (java.lang. import java. if(value == 0){ System. public RemoteServer() throws RemoteException { super().out. try{ FileInputStream fis = new FileInputStream(orders). get = 0.println("Data class unavailable"). import java.out.toString().println("Unable to write to file").*.out. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/JAR/server/RemoteServer.2000 12:34:22] .FileNotFoundException e){ System. import java. String orders = null.println("No Orders To Process"). import java.java (1 of 2) [24.ClassNotFoundException e){ System.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/JAR/server/RemoteServer.rmi. oos. } if(value > get){ get += 1.IOException e){ System.FileNotFoundException e){ System.*.java package server.println("No Orders To Process"). import java. order = (DataOrder)ois. } }else{ System.Color.

} } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/JAR/server/RemoteServer.out.println("Cannot look up server object").RemoteException e) { System.com/Send".07.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/JAR/server/RemoteServer.net. Naming. } catch (java.out. remoteServer).2000 12:34:22] .eng.out.println("Cannot create remote server object").setSecurityManager(new RMISecurityManager()).java (2 of 2) [24. System.rmi. try { Send remoteServer = new RemoteServer(). } String name = "//kq6py. } catch (java.sun.getSecurityManager() == null) { System.java } public static void main(String[] args){ if(System.rebind(name.println("RemoteServer bound").MalformedURLException e) { System.

public interface Send extends Remote { public void sendOrder(DataOrder order) throws RemoteException.07.java package server.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/JAR/server/Send.RemoteException.2000 12:34:23] .rmi. } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/JAR/server/Send. public DataOrder getOrder() throws RemoteException.java [24. import java.rmi.Remote. import java.

custID.07. } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/JAR/server/DataOrder.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/JAR/server/DataOrder. import java. cardnum.java package server. peaches.io.*. public double icost. public class DataOrder implements Serializable{ public String apples. public int itotal. pears.java [24.2000 12:34:24] .

import java.getString("peaches")). peachchk = new JLabel(" " + messages. reset.*.addActionListener(this).getString("title")). file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIClient1. pearqnt. java.getString("1col")). cardNum. JTextField appleqnt. peachchk.*. //Create labels and text field components applechk = new JLabel(" " + messages.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIClient1.event.server. totalCost. custID = new JLabel(" " + messages. creditCard = new JTextField(). import java. pearqnt. customer. peachqnt.getString("card")). appleqnt = new JTextField(). NumberFormat numFormat. pearchk = new JLabel(" " + messages. custID. JButton purchase.swing.Color.getString("apples")). JTextArea items.2000 12:34:26] . pearqnt.java import import import import java. //Internationalization variables static Locale currentLocale. col2 = new JLabel(messages.*. import java.awt. static Send send.*.awt. import java.getString("2col")).awt. static ResourceBundle messages.07. class RMIClient1 extends JFrame implements ActionListener{ JLabel JLabel JLabel JLabel col1.text.addActionListener(this).util. import java.addActionListener(this). java.rmi. country.*.setNextFocusableComponent(creditCard). RMIClient1(){ //Begin Constructor setTitle(messages. cost. static String language. cardNum = new JLabel(" " + messages. //Create left and right column labels col1 = new JLabel(messages. pearchk. peachqnt. customer = new JTextField(). peachqnt = new JTextField().*. appleqnt. javax.net. import java. col2.getString("pears")).*.GridLayout.*. JTextField creditCard.getString("customer")). JPanel panel.rmi. totalItems. pearqnt = new JTextField().io. applechk.java (1 of 4) [24.

items = new JTextArea().getString("purchase")).getString("cost")). .cardnum = creditCard.add(items).file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIClient1. //If Purchase button pressed . panel.getString("items")).add(panel).add(pearqnt). purchase. panel.getText(). panel. if(source == purchase){ //Get data from text fields order.07. panel. text2. cost = new JTextArea().add(totalItems). file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIClient1.add(cost).setBackground(Color.getSource().getString("reset")). peachesNo.add(applechk).add(creditCard).add(custID). Double cost. panel. panel. panel.add(reset). panel. pearsNo. num.add(appleqnt).addActionListener(this). panel.2)). panel.add(col2). . } //End Constructor public void actionPerformed(ActionEvent event){ Object source = event.add(pearchk).2000 12:34:26] . panel.add(customer).java (2 of 4) [24.add(cardNum).java //Create labels and text area components totalItems = new JLabel(" " + messages. //Create a panel for the components panel = new JPanel().white). reset. panel. panel. //Set panel layout to 2-column grid //on a white background panel. panel. Integer applesNo. panel. panel. panel. //Create buttons and make action listeners purchase = new JButton(messages. panel.add(totalCost). //Add components to panel columns //going left to right and top to bottom getContentPane().add(col1). reset = new JButton(messages.add(purchase). totalCost = new JLabel(" " + messages.add(peachqnt).addActionListener(this). String text.add(peachchk).setLayout(new GridLayout(0. panel. DataOrder order = new DataOrder().

order.peaches). } if(order.lang. } } else { order.valueOf(order.cost.pears = pearqnt.length() > 0){ //Catch invalid number error try{ pearsNo = Integer.getNumberInstance(currentLocale).custID = customer.valueOf(order.apples = appleqnt.2000 12:34:26] . order.icost = (order.getText().file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIClient1.setText(messages.07.RemoteException e) { System.format(order.setText(text2).pears.apples).NumberFormatException e){ peachqnt.lang.itotal += 0.itotal).NumberFormatException e){ appleqnt.itotal += pearsNo.getText(). } //Create number formatter numFormat = NumberFormat.icost). try{ send. this.itotal * 1.getText(). } } //If Reset button pressed //Clear all fields if(source == reset){ creditCard.setText(text).getString("send")).apples.getText().setText(messages.java (3 of 4) [24. //Calculate total items if(order.intValue().25).getString("invalid")).rmi.items.intValue(). } } else { order. }catch(java.getString("invalid")).pears). }catch(java. } catch (java. }catch(java.peaches = peachqnt.sendOrder(order).intValue().java order.setText("").getString("invalid")). //Calculate and display running cost order.itotal += 0. order. this.itotal += peachesNo.NumberFormatException e){ pearqnt.itotal += applesNo. } } else { order. //Display running total text = numFormat. order.itotal += 0. order.length() > 0){ //Catch invalid number error try{ applesNo = Integer.out.length() > 0){ //Catch invalid number error try{ peachesNo = Integer. order. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIClient1. text2 = numFormat.setText(messages.lang.valueOf(order.println(messages. } if(order.format(order.peaches.

num = new Integer(order. frame. } currentLocale = new Locale(language. country).rmi.out.println(messages.out. country = new String ("US"). this. text2 = cost. System.toString(). currentLocale). messages = ResourceBundle. text = num.rmi.itotal).setText(text2).RemoteException e){ System.getString("nollokup")). cost = new Double(order. send = ((Send) Naming.setText(text). }else{ language = new String(args[1]).setVisible(true).getString("nolookup")).getString("nolookup")).out. order.setText(""). } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIClient1.setText("").cost. WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.MalformedURLException e) { System. } }.07. } catch (java. System.addWindowListener(l).setText("").java (4 of 4) [24.icost = 0.setSecurityManager(new RMISecurityManager()). pearqnt.println(messages.itotal = 0. order.setText("").toString(). } catch(java.getSecurityManager() == null) { System.println(language + country).setText(""). if(System.items. } catch(java. creditCard.length != 3) { language = new String("en").file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIClient1.lookup(name)).icost). } try { String name = "//" + args[0] + "/Send".net.println(messages. country = new String(args[2]). frame. peachqnt.getBundle("MessagesBundle".2000 12:34:26] .out.println("English"). RMIClient1 frame = new RMIClient1().NotBoundException e) { System.exit(0). this.pack().java appleqnt. customer.out. } } public static void main(String[] args){ if(args. frame.

peachesNo = new JTextArea(). file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIClient2. pears = new JLabel(messages. import java. NumberFormat numFormat.getString("cost")).util.getString("card")).getString("view")).getString("items")). peaches.*. pearsNo.getString("peaches")). reset = new JButton(messages.GridLayout.rmi.*.*.awt. panel. String customer. panel. total. static String language.swing. total = new JLabel(messages. peachesNo.2000 12:34:28] . apples = new JLabel(messages.addActionListener(this). JPanel panel. icost. custID. static Send send. Set s = null.setLayout(new GridLayout(0. javax. view. clicked.getString("pears")).*.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIClient2.setBackground(Color. import java. icost = new JTextArea(). java. custID = new JLabel(messages. itotal. import java. JTextArea creditNo. import java.getString("apples")).java (1 of 4) [24. class RMIClient2 extends JFrame implements ActionListener { JLabel creditCard. import java.io.text. reset.awt.getString("title")). static ResourceBundle messages. customerNo = new JTextArea(). applesNo = new JTextArea(). reset.server. cost = new JLabel(messages. cost.*. pearsNo = new JTextArea(). //Create buttons view = new JButton(messages. customerNo.white). //Internationalization variables static Locale currentLocale. //Create panel for 2-column layout //Set white background color panel = new JPanel().addActionListener(this).awt.*.2)).Color. pears. peaches = new JLabel(messages.*. country. //Create text areas creditNo = new JTextArea(). //Create labels creditCard = new JLabel(messages.getString("reset")). import java. applesNo. itotal = new JTextArea().rmi. java.07.*.getString("customer")). RMIClient2(){ //Begin Constructor setTitle(messages.net. JButton view.event. apples.java import import import import java.

creditNo.add(peachesNo). while(it.println(s). panel. }else{ System. int items.add(custID).size()!=0){ Iterator it = s. } //Print customer IDs public void print(){ if(s.add(applesNo). Integer itms.add(panel). System. customerNo. panel.add(reset). Double price. panel.out.getOrder(). } } public void actionPerformed(ActionEvent event){ Object source = event.java //Add components to panel columns //going left to right and top to bottom getContentPane().add(creditNo).println("No customer IDs available").2000 12:34:28] .add(itotal). panel.add(pearsNo).setText(order.java (2 of 4) [24.add(customerNo).getSource().add(total). panel.custID).add(apples).out.out. panel. panel.out.next()). panel. panel. DataOrder order = new DataOrder(). String unit. panel.07.println(it.cardnum).file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIClient2. } //End Constructor //Create list of customer IDs public void addCustomer(String custID){ s. double cost. panel. panel. panel.setText(order. panel.add(pears).add(cost). //If View button pressed //Get data from server and display it if(source == view){ try{ order = send.add(peaches). panel. } System.add(icost).add(creditCard).println("Customer ID added"). panel. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIClient2.add(custID). i.hasNext()){ System.add(view).iterator().

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIClient2.java

//Get customer ID and add to list addCustomer(order.custID); applesNo.setText(order.apples); peachesNo.setText(order.peaches); pearsNo.setText(order.pears); //Create number formatter numFormat = NumberFormat.getNumberInstance(currentLocale); price = new Double(order.icost); unit = numFormat.format(price); icost.setText(unit); itms = new Integer(order.itotal); i = numFormat.format(order.itotal); itotal.setText(i); } catch (java.rmi.RemoteException e) { System.out.println("Cannot access data in server"); } //Print print(); } //If Reset button pressed //Clear all fields if(source == reset){ creditNo.setText(""); customerNo.setText(""); applesNo.setText(""); peachesNo.setText(""); pearsNo.setText(""); itotal.setText(""); icost.setText(""); } } public static void main(String[] args){ if(args.length != 3) { language = new String("en"); country = new String ("US"); System.out.println("English"); }else{ language = new String(args[1]); country = new String(args[2]); System.out.println(language + country); } currentLocale = new Locale(language, country); messages = ResourceBundle.getBundle("MessagesBundle", currentLocale); WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }; RMIClient2 frame = new RMIClient2(); frame.addWindowListener(l); frame.pack(); frame.setVisible(true); if(System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); }

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIClient2.java (3 of 4) [24.07.2000 12:34:28]

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIClient2.java

try { String name = "//" + args[0] + "/Send"; send = ((Send) Naming.lookup(name)); } catch (java.rmi.NotBoundException e) { System.out.println(messages.getString("nolookup")); } catch(java.rmi.RemoteException e){ System.out.println(messages.getString("nolookup")); } catch(java.net.MalformedURLException e) { System.out.println(messages.getString("nolookup")); } } }

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIClient2.java (4 of 4) [24.07.2000 12:34:28]

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/MessagesBundle_en_US.properties

apples=Apples: peaches=Peaches: pears=Pears: items=Total Items: cost=Total Cost: card=Credit Card: customer=Customer ID: title=Fruit 1.25 Each 1col=Select Items 2col=Specify Quantity reset=Reset view=View purchase=Purchase invalid=Invalid Value send=Cannot send data to server nolookup=Cannot look up remote server object nodata=No data available noID=No customer IDs available noserver=Cannot access data in server

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/MessagesBundle_en_US.properties [24.07.2000 12:34:29]

out.server.getLocale(). try { //Path to host where remote Send object is running String name = "//kq6py.*. JTextArea items.rmi.RemoteException e){ System.Applet. } catch (java. public void init(){ language = new String("en").awt.MalformedURLException e) { System. currentLocale). import java. if(System. import java.*.out.awt.net.swing. customer. import java.com/Send".net.util. cost. //Make public public class RMIEnglishApp extends Applet implements ActionListener{ JLabel JLabel JLabel JLabel col1. javax. } catch(java.getString("nolookup")). ResourceBundle messages. } //Create left and right column labels file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIEnglishApp. import java.*.NotBoundException e) { System.event.Color. totalCost. JTextField appleqnt.text. peachchk.getBundle("MessagesBundle". java. JButton purchase. JTextField creditCard. } currentLocale = new Locale(language.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIEnglishApp.*. //Internationalization variables Locale currentLocale.getString("nollokup")). Locale test = messages. custID.println(messages.rmi. messages = ResourceBundle.*.GridLayout. static String language.setSecurityManager(new RMISecurityManager()).rmi.println(messages.getSecurityManager() == null) { System. send = ((Send) Naming.eng.getString("nolookup")).java import import import import java.println(messages.rmi.java (1 of 4) [24.*.applet.awt.out. col2. NumberFormat numFormat.07.2000 12:34:31] . java. import java. reset. pearchk. peachqnt.*. country. country = new String ("US"). import java. import java. cardNum. static Send send. totalItems.*.sun. country). pearqnt.lookup(name)).io. applechk. } catch(java.

addActionListener(this). add(pearqnt). appleqnt. add(cardNum). cardNum = new JLabel(" " + messages. custID = new JLabel(" " + messages. reset = new JButton(messages.2000 12:34:31] . //Set panel layout to 2-column grid //on a white background setLayout(new GridLayout(0. //Add components to panel columns //going left to right and top to bottom add(col1).getString("items")). add(totalCost).getString("customer")).07. add(peachchk).java col1 = new JLabel(messages. peachchk = new JLabel(" " + messages. items = new JTextArea(). //Create buttons and make action listeners purchase = new JButton(messages. purchase. //Create labels and text area components totalItems = new JLabel(" " + messages.getString("card")).getString("pears")).getString("purchase")). add(cost). setBackground(Color. add(totalItems). customer = new JTextField().addActionListener(this). add(col2).getString("1col")). creditCard = new JTextField().addActionListener(this).getString("2col")). add(peachqnt). pearqnt. cost = new JTextArea(). col2 = new JLabel(messages. pearchk = new JLabel(" " + messages.addActionListener(this).getString("cost")). totalCost = new JLabel(" " + messages. add(applechk).file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIEnglishApp. peachqnt.java (2 of 4) [24. add(items).setNextFocusableComponent(creditCard). pearqnt.getString("peaches")).getString("reset")). add(creditCard). file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIEnglishApp. add(pearchk).2)).addActionListener(this).white). peachqnt = new JTextField(). pearqnt = new JTextField(). reset. //Create labels and text field components applechk = new JLabel(" " + messages. add(appleqnt).getString("apples")). appleqnt = new JTextField().

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIEnglishApp.getText().intValue().getText(). } if(order. } if(order.peaches = peachqnt.java add(custID).itotal += peachesNo.length() > 0){ //Catch invalid number error try{ peachesNo = Integer.2000 12:34:31] . order.pears.getString("invalid")).itotal += 0. //Display running total file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIEnglishApp. add(purchase).itotal += 0.setText(messages. Integer applesNo.getText().pears = pearqnt. if(source == purchase){ //Get data from text fields order.java (3 of 4) [24. //Calculate total items if(order. add(reset). .itotal += applesNo.getString("invalid")).lang.getString("invalid")).setText(messages. } //End Constructor public void actionPerformed(ActionEvent event){ Object source = event.apples = appleqnt. order.apples.setText(messages.peaches). order. order.intValue().cardnum = creditCard. order.pears). add(customer). String text.valueOf(order.getNumberInstance(currentLocale).itotal += 0. } } else { order.itotal += pearsNo.peaches.length() > 0){ //Catch invalid number error try{ pearsNo = Integer. text2. DataOrder order = new DataOrder(). .apples).length() > 0){ //Catch invalid number error try{ applesNo = Integer. order. pearsNo. }catch(java.getText().intValue().valueOf(order. //If Purchase button pressed .lang.NumberFormatException e){ peachqnt.lang. order.NumberFormatException e){ pearqnt. } } else { order.NumberFormatException e){ appleqnt.07.getText().valueOf(order. }catch(java. } //Create number formatter numFormat = NumberFormat. Double cost. num. } } else { order.custID = customer. }catch(java. peachesNo.getSource().

getString("send")).java (4 of 4) [24. appleqnt. this. try{ send.sendOrder(order).setText(""). peachqnt. num = new Integer(order.java text = numFormat.setText("").2000 12:34:31] .itotal * 1. } catch (java. //Calculate and display running cost order. text2 = cost.setText(""). text2 = numFormat.format(order. cost = new Double(order.icost).itotal). text = num.setText(""). pearqnt.icost = (order.icost).file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIEnglishApp.07. creditCard.setText("").toString(). } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIEnglishApp.items.format(order. this.25). order. order.icost = 0.itotal).cost. customer.setText(text).println(messages.setText("").items.rmi.toString(). } } //If Reset button pressed //Clear all fields if(source == reset){ creditCard.RemoteException e) { System. this.setText(text2).itotal = 0. this.out.setText(text).setText(text2).cost.

text. java.*. messages = ResourceBundle.getString("nolookup")).Applet.*. peachchk.println(messages.getSecurityManager() == null) { System.2000 12:34:33] . ResourceBundle messages. col2. pearqnt. javax.out. } currentLocale = new Locale(language. country.setSecurityManager(new RMISecurityManager()).net.rmi. } //Create left and right column labels file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIFrenchApp. applechk. JTextField creditCard. import java.out.*. NumberFormat numFormat.io. } catch(java. country).out. public void init(){ language = new String("fr").*. java.getString("nolookup")). reset.*.rmi. } catch (java.swing.awt.println(messages.getString("nollokup")).event.*. if(System. JTextArea items. totalCost. } catch(java. import java.applet. import java. //Internationalization variables Locale currentLocale.net. import java. custID.rmi.*. currentLocale). country = new String ("FR"). //Make public public class RMIFrenchApp extends Applet implements ActionListener{ JLabel JLabel JLabel JLabel col1.getBundle("MessagesBundle". import java.com/Send". import java.rmi. static Send send. pearchk.07. cardNum. customer.java import import import import java.MalformedURLException e) { System.Color.server.awt. static String language. import java.java (1 of 4) [24.sun. peachqnt. JButton purchase.println(messages. Locale test = messages.util. try { //Path to host where remote Send object is running String name = "//kq6py.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIFrenchApp.eng.lookup(name)).GridLayout.awt. totalItems.getLocale(). send = ((Send) Naming. JTextField appleqnt. cost.RemoteException e){ System.*.NotBoundException e) { System.

//Set panel layout to 2-column grid //on a white background setLayout(new GridLayout(0.addActionListener(this). peachqnt.white).getString("reset")).getString("items")). add(totalItems). purchase.getString("cost")). add(col2). appleqnt = new JTextField().getString("pears")).addActionListener(this).addActionListener(this).getString("1col")). col2 = new JLabel(messages. custID = new JLabel(" " + messages. add(pearqnt).getString("card")). add(pearchk). totalCost = new JLabel(" " + messages. peachqnt = new JTextField(). reset.getString("customer")). reset = new JButton(messages. items = new JTextArea().setNextFocusableComponent(creditCard).2000 12:34:33] . add(peachchk). add(peachqnt). file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIFrenchApp. pearqnt = new JTextField(). peachchk = new JLabel(" " + messages.getString("apples")). cost = new JTextArea(). add(creditCard). //Create buttons and make action listeners purchase = new JButton(messages.java col1 = new JLabel(messages.java (2 of 4) [24. appleqnt. creditCard = new JTextField(). add(items). add(cost).getString("peaches")).addActionListener(this).07.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIFrenchApp.getString("purchase")).getString("2col")). add(applechk). pearchk = new JLabel(" " + messages. add(totalCost). //Add components to panel columns //going left to right and top to bottom add(col1). cardNum = new JLabel(" " + messages. //Create labels and text area components totalItems = new JLabel(" " + messages. customer = new JTextField(). pearqnt.2)). add(appleqnt). add(cardNum).addActionListener(this). //Create labels and text field components applechk = new JLabel(" " + messages. pearqnt. setBackground(Color.

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIFrenchApp.java

add(custID); add(customer); add(reset); add(purchase); } //End Constructor public void actionPerformed(ActionEvent event){ Object source = event.getSource(); Integer applesNo, peachesNo, pearsNo, num; Double cost; String text, text2; DataOrder order = new DataOrder(); //If Purchase button pressed . . . if(source == purchase){ //Get data from text fields order.cardnum = creditCard.getText(); order.custID = customer.getText(); order.apples = appleqnt.getText(); order.peaches = peachqnt.getText(); order.pears = pearqnt.getText(); //Calculate total items if(order.apples.length() > 0){ //Catch invalid number error try{ applesNo = Integer.valueOf(order.apples); order.itotal += applesNo.intValue(); }catch(java.lang.NumberFormatException e){ appleqnt.setText(messages.getString("invalid")); } } else { order.itotal += 0; } if(order.peaches.length() > 0){ //Catch invalid number error try{ peachesNo = Integer.valueOf(order.peaches); order.itotal += peachesNo.intValue(); }catch(java.lang.NumberFormatException e){ peachqnt.setText(messages.getString("invalid")); } } else { order.itotal += 0; } if(order.pears.length() > 0){ //Catch invalid number error try{ pearsNo = Integer.valueOf(order.pears); order.itotal += pearsNo.intValue(); }catch(java.lang.NumberFormatException e){ pearqnt.setText(messages.getString("invalid")); } } else { order.itotal += 0; } //Create number formatter numFormat = NumberFormat.getNumberInstance(currentLocale); //Display running total

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIFrenchApp.java (3 of 4) [24.07.2000 12:34:33]

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIFrenchApp.java

text = numFormat.format(order.itotal); this.items.setText(text); //Calculate and display running cost order.icost = (order.itotal * 1.25); text2 = numFormat.format(order.icost); this.cost.setText(text2); try{ send.sendOrder(order); } catch (java.rmi.RemoteException e) { System.out.println(messages.getString("send")); } } //If Reset button pressed //Clear all fields if(source == reset){ creditCard.setText(""); appleqnt.setText(""); peachqnt.setText(""); pearqnt.setText(""); creditCard.setText(""); customer.setText(""); order.icost = 0; cost = new Double(order.icost); text2 = cost.toString(); this.cost.setText(text2); order.itotal = 0; num = new Integer(order.itotal); text = num.toString(); this.items.setText(text); } } }

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIFrenchApp.java (4 of 4) [24.07.2000 12:34:33]

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIGermanApp.java

import import import import

java.awt.Color; java.awt.GridLayout; java.awt.event.*; javax.swing.*;

import java.io.*; import java.net.*; import java.rmi.*; import java.rmi.server.*; import java.util.*; import java.text.*; import java.applet.Applet; //Make public public class RMIGermanApp extends Applet implements ActionListener{ JLabel JLabel JLabel JLabel col1, col2; totalItems, totalCost; cardNum, custID; applechk, pearchk, peachchk;

JButton purchase, reset; JTextField appleqnt, pearqnt, peachqnt; JTextField creditCard, customer; JTextArea items, cost; static Send send; //Internationalization variables Locale currentLocale; ResourceBundle messages; static String language, country; NumberFormat numFormat; public void init(){ language = new String("de"); country = new String ("DE"); if(System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } currentLocale = new Locale(language, country); messages = ResourceBundle.getBundle("MessagesBundle", currentLocale); Locale test = messages.getLocale(); try { //Path to host where remote Send object is running String name = "//kq6py.eng.sun.com/Send"; send = ((Send) Naming.lookup(name)); } catch (java.rmi.NotBoundException e) { System.out.println(messages.getString("nolookup")); } catch(java.rmi.RemoteException e){ System.out.println(messages.getString("nolookup")); } catch(java.net.MalformedURLException e) { System.out.println(messages.getString("nollokup")); } //Create left and right column labels

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIGermanApp.java (1 of 4) [24.07.2000 12:34:37]

add(cardNum). col2 = new JLabel(messages.getString("purchase")).getString("items")). custID = new JLabel(" " + messages.getString("card")).2000 12:34:37] . pearchk = new JLabel(" " + messages. add(peachqnt). pearqnt. purchase. cost = new JTextArea(). pearqnt. add(appleqnt). //Create labels and text field components applechk = new JLabel(" " + messages. //Set panel layout to 2-column grid //on a white background setLayout(new GridLayout(0. appleqnt.getString("apples")). add(cost).getString("cost")). add(applechk).addActionListener(this). file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIGermanApp.addActionListener(this).07. peachqnt. peachchk = new JLabel(" " + messages. //Create buttons and make action listeners purchase = new JButton(messages. add(creditCard).setNextFocusableComponent(creditCard).file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIGermanApp.java (2 of 4) [24. add(totalItems).addActionListener(this). pearqnt = new JTextField(). add(pearqnt). customer = new JTextField(). setBackground(Color. reset. add(totalCost).2)).getString("pears")).java col1 = new JLabel(messages. totalCost = new JLabel(" " + messages.getString("1col")).getString("reset")). creditCard = new JTextField(). add(peachchk).addActionListener(this). cardNum = new JLabel(" " + messages. add(pearchk). appleqnt = new JTextField(). items = new JTextArea(). reset = new JButton(messages.getString("customer")). peachqnt = new JTextField(). //Add components to panel columns //going left to right and top to bottom add(col1).white). add(col2). add(items).addActionListener(this).getString("peaches")).getString("2col")). //Create labels and text area components totalItems = new JLabel(" " + messages.

peachesNo. .getString("invalid")). } if(order. //Display running total file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIGermanApp. order.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIGermanApp.peaches). order.peaches = peachqnt.java (3 of 4) [24.getText(). } } else { order. }catch(java.getSource().valueOf(order.itotal += 0. add(reset).apples. add(purchase). . order.apples).itotal += pearsNo.custID = customer. order. num.getText().pears.2000 12:34:37] .itotal += 0.length() > 0){ //Catch invalid number error try{ peachesNo = Integer.pears). //Calculate total items if(order. } } else { order. order.lang. String text.getText().07.apples = appleqnt.NumberFormatException e){ peachqnt. order. DataOrder order = new DataOrder().setText(messages. } } else { order.itotal += applesNo. }catch(java. } //End Constructor public void actionPerformed(ActionEvent event){ Object source = event. } //Create number formatter numFormat = NumberFormat. //If Purchase button pressed .peaches. }catch(java.java add(custID). } if(order.lang.getNumberInstance(currentLocale).length() > 0){ //Catch invalid number error try{ applesNo = Integer. Integer applesNo.intValue().getString("invalid")).intValue(). order.intValue().lang. pearsNo.itotal += peachesNo. Double cost.pears = pearqnt.NumberFormatException e){ appleqnt.setText(messages.getText().cardnum = creditCard. if(source == purchase){ //Get data from text fields order. text2.valueOf(order.getString("invalid")).valueOf(order.length() > 0){ //Catch invalid number error try{ pearsNo = Integer.itotal += 0. add(customer).getText().NumberFormatException e){ pearqnt.setText(messages.

RemoteException e) { System. text = num.setText("").println(messages.icost = 0.sendOrder(order). this. appleqnt.items.format(order.25).items. this.icost).setText(text2).getString("send")). } catch (java. cost = new Double(order.setText(""). pearqnt. peachqnt.cost.toString(). num = new Integer(order.itotal).toString().2000 12:34:37] .setText("").07.setText(text). this.icost = (order. } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIGermanApp. order. order.setText(""). //Calculate and display running cost order.setText(text2).setText("").itotal = 0.setText("").setText(text).itotal).format(order. try{ send.icost). } } //If Reset button pressed //Clear all fields if(source == reset){ creditCard.rmi.java (4 of 4) [24.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitInt/RMIGermanApp. creditCard.itotal * 1.cost. customer.java text = numFormat. this.out. text2 = cost. text2 = numFormat.

custID. peaches.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/DataOrder. int itotal.io.07. pears. class DataOrder implements Serializable{ String apples. double icost.java import java.2000 12:34:38] . cardnum.java [24.*. } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/DataOrder.

customer.addActionListener(this). cardNum. pearchk = new JLabel(" Pears"). pearchk. //Create labels and text field components applechk = new JLabel(" Apples"). creditCard = new JTextField(). col2 = new JLabel("Specify Quantity"). JTextField appleqnt. import java.*.07. purchase. pearqnt. peachchk. class RMIClient1 extends JFrame implements ActionListener{ JLabel JLabel JLabel JLabel col1. custID = new JLabel(" Customer ID:"). customer = new JTextField().Color.*. RMIClient1(){ //Begin Constructor //Create left and right column labels col1 = new JLabel("Select Items").*. //Create labels and text area components totalItems = new JLabel("Total Items:").server. javax. col2. appleqnt. cost = new JTextArea(). import java. JTextArea items.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RMIClient1.*. items = new JTextArea().rmi. totalCost = new JLabel("Total Cost:"). totalItems. pearqnt = new JTextField().*.java (1 of 4) [24. reset. peachqnt = new JTextField(). JTextField creditCard.2000 12:34:40] . peachqnt.rmi.swing. JPanel panel.addActionListener(this).io. pearqnt. JButton purchase.*. static Send send. pearqnt. reset = new JButton("Reset"). peachqnt. import java. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RMIClient1. reset. appleqnt = new JTextField().addActionListener(this). custID.net.awt.addActionListener(this). import java.awt. cost. cardNum = new JLabel(" Credit Card:").java import import import import java.GridLayout. totalCost.addActionListener(this).event. peachchk = new JLabel(" Peaches"). java. applechk. java. //Create buttons and make action listeners purchase = new JButton("Purchase").awt.setNextFocusableComponent(creditCard).

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RMIClient1. panel. panel. panel. panel.getSource().white).intValue().add(creditCard). panel.add(col1). panel. order.getText().java //Create a panel for the components panel = new JPanel(). order.lang. panel. peachesNo.add(purchase). panel.add(cardNum).valueOf(order.itotal += applesNo. panel.add(reset). } //End Constructor public void actionPerformed(ActionEvent event){ Object source = event. order.add(panel).cardnum = creditCard. if(source == purchase){ //Get data from text fields order.getText().setText("Invalid Value"). //Set panel layout to 2-column grid //on a white background panel.2)). . file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RMIClient1. panel.add(custID). panel. String text.add(items). //Calculate total items if(order.getText().length() > 0){ //Catch invalid number error try{ applesNo = Integer. panel.add(totalItems).add(applechk).add(col2).2000 12:34:40] . DataOrder order = new DataOrder(). panel. panel.add(pearqnt).getText().getText().add(peachqnt).pears = pearqnt.peaches = peachqnt.add(cost). order.07.apples. Double cost. text2.add(customer).add(pearchk). Integer applesNo. panel. order. //Add components to panel columns //going left to right and top to bottom getContentPane().apples). }catch(java.setBackground(Color.custID = customer.java (2 of 4) [24.add(appleqnt). panel. panel. pearsNo. num.setLayout(new GridLayout(0.apples = appleqnt. panel.add(peachchk). //If Purchase button pressed . . panel.add(totalCost).NumberFormatException e){ appleqnt.

icost).out. peachqnt. text2 = cost. }catch(java.toString().25). } if(order.items.setText("").itotal += peachesNo.setText(text2). pearqnt.setText(text2).intValue(). } } //If Reset button pressed //Clear all fields if(source == reset){ creditCard.toString(). cost = new Double(order.cost.itotal).valueOf(order.length() > 0){ //Catch invalid number error try{ peachesNo = Integer.rmi.icost).toString(). text = num.pears.07.itotal * 1. }catch(java. this.length() > 0){ //Catch invalid number error try{ pearsNo = Integer.sendOrder(order).setText("").NumberFormatException e){ peachqnt.setText("Invalid Value"). order.lang.RemoteException e) { System.icost = 0.icost = (order. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RMIClient1.valueOf(order.setText("Invalid Value"). text2 = cost. this.println("Cannot send data to server").file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RMIClient1. } //Display running total num = new Integer(order.java (3 of 4) [24.java } } else { order.itotal += 0.setText(""). cost = new Double(order. order. } } else { order. appleqnt.pears). } if(order. //Calculate and display running cost order.itotal += 0.peaches).toString(). creditCard.setText(""). customer. order.itotal = 0. } } else { order. order.setText(""). text = num.lang.setText(text). this.peaches. try{ send. } catch (java.itotal += 0.itotal).cost. num = new Integer(order.setText("").NumberFormatException e){ pearqnt.itotal += pearsNo.intValue().2000 12:34:40] .

java this.2000 12:34:40] . send = ((Send) Naming.NotBoundException e) { System.out.java (4 of 4) [24.MalformedURLException e) { System.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RMIClient1.exit(0).RemoteException e){ System.getSecurityManager() == null) { System.out.println("Cannot look up remote server object").println("Cannot look up remote server object"). } } public static void main(String[] args){ RMIClient1 frame = new RMIClient1().07. frame.addWindowListener(l).items. frame. } catch(java.rmi.setVisible(true).net. frame.setTitle("Fruit $1. } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RMIClient1.lookup(name)). WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System. } catch(java.pack(). if(System.out.rmi.println("Cannot look up remote server object"). } catch (java.setText(text).setSecurityManager(new RMISecurityManager()). } }. frame.25 Each"). } try { String name = "//" + args[0] + "/Send".

RemoteException.java [24.rmi.2000 12:34:41] .file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/Send.Remote. public interface Send extends Remote { public void sendOrder(DataOrder order) throws RemoteException. import java.rmi. public DataOrder getOrder() throws RemoteException.07.java import java. } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/Send.

out.println("File not found"). orders = num.IOException e){ System. int value = 0.*. try{ FileInputStream fis = new FileInputStream(orders).awt. import java.server.java (1 of 2) [24.07.io.IOException e){ System.ClassNotFoundException e){ System. oos. class RemoteServer extends UnicastRemoteObject implements Send { Integer num = null.net. get = 0.BorderLayout.awt.io.2000 12:34:44] .event.*.toString(). ObjectOutputStream oos = new ObjectOutputStream(fos).readObject(). order = (DataOrder)ois.out. import java.io.FileNotFoundException e){ System.rmi.writeObject(order). }catch (java. } public void sendOrder(DataOrder order){ value += 1.println("No Orders To Process").out.out.println("No data available").*.out.out. } }else{ System.println("File not found").rmi.FileNotFoundException e){ System. import java. import java. ObjectInputStream ois = new ObjectInputStream(fis). try{ FileOutputStream fos = new FileOutputStream(orders). }catch (java.toString().println("Unable to write to file"). } return order.out.println("No Orders To Process").io. }catch (java.*. } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RemoteServer. } } public DataOrder getOrder(){ DataOrder order = null.println("Unable to read file"). import java.*.awt. num = new Integer(get). public RemoteServer() throws RemoteException { super(). import java. num = new Integer(value). String orders = null.lang. orders = num.Color. if(value == 0){ System.java import java. }catch (java. } if(value > get){ get += 1.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RemoteServer.io. }catch (java.

try { Send remoteServer = new RemoteServer().eng. Naming.out.RemoteException e) { System.out.java public static void main(String[] args){ if(System. } String name = "//kq6py.07.rmi.getSecurityManager() == null) { System. } catch (java.println("Cannot look up server object").file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RemoteServer.setSecurityManager(new RMISecurityManager()).println("Cannot create remote server object").net.java (2 of 2) [24.2000 12:34:44] .out. remoteServer). System.println("RemoteServer bound").rebind(name.com/Send". } catch (java. } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RemoteServer.MalformedURLException e) { System.sun.

server. panel.2000 12:34:46] . clicked. import java. pearsNo.setLayout(new GridLayout(0.add(panel).2)). cost = new JLabel("Total Cost:").FileInputStream.util. custID = new JLabel("Customer ID:"). panel.awt.*. //Create buttons view = new JButton("View Order"). icost = new JTextArea(). class RMIClient2 extends JFrame implements ActionListener { JLabel creditCard.*.add(creditNo). peaches.java import import import import java. pearsNo = new JTextArea(). import java.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RMIClient2. JPanel panel. apples = new JLabel("Apples:").rmi. //Create text areas creditNo = new JTextArea().GridLayout. Set s = null. customerNo = new JTextArea().io. import java. applesNo = new JTextArea().awt.java (1 of 3) [24.*. //Add components to panel columns //going left to right and top to bottom getContentPane().io.Color. import java. import java.File. reset = new JButton("Reset"). cost. reset. panel.io. total. java.awt. peachesNo = new JTextArea(). import java.white). peachesNo.RandomAccessFile. icost. import java.*. apples. view.07.swing. pears = new JLabel("Pears:"). itotal = new JTextArea().rmi.*.*.event. JTextArea creditNo.setBackground(Color. peaches = new JLabel("Peaches:"). static Send send. itotal. java. RMIClient2(){ //Begin Constructor //Create labels creditCard = new JLabel("Credit Card:").*. total = new JLabel("Total Items:").*. custID. customerNo. javax. applesNo.*.addActionListener(this).net. String customer.io. panel.addActionListener(this). //Create panel for 2-column layout //Set white background color panel = new JPanel(). JButton view. import java.add(creditCard). reset. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RMIClient2. pears.

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RMIClient2.setText(i). icost.setText(order.add(total). panel.custID). panel.add(reset). panel.setText("").itotal. panel.println("Cannot access data in server").setText(order.getSource(). double cost.toString().add(peachesNo).getOrder(). i = itms. customerNo. panel. } //End Constructor public void actionPerformed(ActionEvent event){ Object source = event.apples).add(applesNo). } catch (java. DataOrder order = new DataOrder().icost.add(custID).setText(order. applesNo. peachesNo.cardnum). price = new Double(cost). unit = price. panel. panel. //If View button pressed //Get data from server and display it if(source == view){ try{ order = send.2000 12:34:46] . peachesNo. itotal.java (2 of 3) [24. applesNo. customerNo. int items. Double price. panel. i.toString().add(customerNo).add(itotal). panel.java panel.setText(order.add(icost).setText(order. panel. } } //If Reset button pressed //Clear all fields if(source == reset){ creditNo. itms = new Integer(items).out.pears). file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RMIClient2. items = order. panel.setText(""). creditNo. cost = order.add(view).add(pears). String unit.add(apples). panel.setText("").RemoteException e) { System.add(pearsNo).add(cost).setText(unit).setText("").add(peaches). Integer itms. pearsNo.peaches). panel.rmi.07.

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RMIClient2. frame. } catch (java.println("Cannot access data in server").addWindowListener(l).lookup(name)).NotBoundException e) { System.setText(""). } try { String name = "//" + args[0] + "/Send".net.exit(0).java pearsNo.07.pack(). frame. frame.RemoteException e) { System.2000 12:34:46] . WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.rmi. send = ((Send) Naming. } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitSerial/RMIClient2. frame.java (3 of 3) [24. } }. itotal.setText("").out.out.setTitle("Fruit Order").out.setText(""). } catch(java.println("Cannot create remote server object"). if(System.setSecurityManager(new RMISecurityManager()).rmi. } catch (java.getSecurityManager() == null) { System.setVisible(true).println("Cannot look up server object"). } } public static void main(String[] args){ RMIClient2 frame = new RMIClient2().MalformedURLException e) { System. icost.

import java. col2 = new JLabel("Specify Quantity").crypto.Color. creditCard = new JTextField(). peachqnt.server.*. RMIClient1(){ //Begin Constructor //Create left and right column labels col1 = new JLabel("Select Items"). //import javax.addActionListener(this). peachqnt.addActionListener(this). pearqnt. totalItems.net. peachchk.*.*. cardNum.*. import java. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1Sealed.swing. customer = new JTextField().*. col2.io.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1Sealed.*. JTextField appleqnt. int itotal=0. custID = new JLabel(" Customer ID:").java. totalCost.java import java. cost = new JTextArea().awt.*.addActionListener(this). peachchk = new JLabel(" Peaches"). appleqnt. static Send send. pearqnt. //Create labels and text area components totalItems = new JLabel("Total Items:"). //Create labels and text field components applechk = new JLabel(" Apples"). cost.*. peachqnt = new JTextField().rmi. pearchk = new JLabel(" Pears").swing.rmi. customer.security. appleqnt = new JTextField(). applechk. reset. cardNum = new JLabel(" Credit Card:"). JButton purchase. import java.security. totalCost = new JLabel("Total Cost:").sun. import java.*. double icost=0.java (1 of 5) [24. pearqnt.awt. custID.setNextFocusableComponent(creditCard). import java. pearchk. import javax. items = new JTextArea(). import java. JTextArea items. JPanel panel.07.*.2000 12:34:49] . pearqnt = new JTextField(). import java.interfaces.GridLayout. JTextField creditCard.awt. import com.event. import java. class RMIClient1 extends JFrame implements ActionListener{ JLabel JLabel JLabel JLabel col1.

addActionListener(this). //Set panel layout to 2-column grid //on a white background panel.add(items). panel.add(appleqnt).add(totalItems).add(pearchk).add(purchase). panel. //Create a panel for the components panel = new JPanel(). reset = new JButton("Reset").2)).add(totalCost).add(custID).file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1Sealed. panel.2000 12:34:49] .setBackground(Color.add(customer).add(col2). panel.add(peachchk).setNextFocusableComponent(reset). reset. panel.java //Create buttons and make action listeners purchase = new JButton("Purchase").setLayout(new GridLayout(0. panel.add(cardNum).add(creditCard). panel. purchase.white). //Add components to panel columns //going left to right and top to bottom getContentPane(). panel. panel. panel.add(panel).add(cost).java (2 of 5) [24.add(applechk).add(col1). panel.addActionListener(this). panel. panel.add(reset). panel.add(peachqnt). panel. panel. creditCard. } //End Constructor /* private void encrypt(credit card number){ // Create cipher for symmetric key encryption (DES) // Create a key generator // Create a secret (session) key with key generator // Initialize cipher for encryption with session key // Encrypt credit card number with cipher // Get public key from server // Create cipher for asymmetric encryption (so not use RSA) // Initialize cipher for encryption with public key // Seal session key using asymmetric cipher // Serialize sealed session key // Send encrypted credit card number and // sealed session key to server } */ file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1Sealed. panel.add(pearqnt). panel.07. panel.

//Encrypt credit card number file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1Sealed. //Calculate total items if(apples. this.getText().valueOf(pears). num.intValue(). apples = appleqnt.lang. } //Display running total num = new Integer(itotal).intValue(). //If Purchase button pressed if(source == purchase){ //Get data from text fields cardnum = creditCard.valueOf(peaches). pears. peaches = peachqnt. apples. } } else { itotal += 0.toString().length() > 0){ //Catch invalid number error try{ applesNo = Integer. } } else { itotal += 0. text2 = cost.getText().getSource().NumberFormatException e){ pearqnt. cardnum. } if(peaches. String number.getText().setText(text2). } if(pears.setText("Invalid Value"). } } else { itotal += 0. }catch(java. Double cost.length() > 0){ //Catch invalid number error try{ peachesNo = Integer.NumberFormatException e){ appleqnt. cost = new Double(icost). }catch(java.getText(). custID = customer. itotal += pearsNo.getText().java public void actionPerformed(ActionEvent event){ Object source = event. peaches. text = num.lang. pears = pearqnt. peachesNo.07.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1Sealed. itotal += applesNo.lang.length() > 0){ //Catch invalid number error try{ pearsNo = Integer.items.25).cost. }catch(java.setText("Invalid Value").java (3 of 5) [24.setText("Invalid Value").toString().valueOf(apples).setText(text). Integer applesNo. custID.intValue(). pearsNo. //Calculate and display running cost icost = (itotal * 1. text.NumberFormatException e){ peachqnt. itotal += peachesNo. this.2000 12:34:49] . text2.

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1Sealed. } } public static void main(String[] args){ try{ UIManager. cost = new Double(icost).cost.sendCustID(custID). peachqnt.setVisible(true).sendPeachQnt(peaches).setText("").pack().2000 12:34:49] .setText("").sendPearQnt(pears). if(System.rmi. num = new Integer(itotal). this. send. } try { String name = "//" + args[0] + "/Send".println("Couldn't use the cross-platform" + "look and feel: " + e).println("sendData exception: " + e.java encrypt(cardnum).setText("").setTitle("Fruit $1. } } //If Reset button pressed //Clear all fields if(source == reset){ creditCard. } RMIClient1 frame = new RMIClient1(). frame.toString(). creditCard. customer. pearqnt.java (4 of 5) [24.items. send = ((Send) Naming.setLookAndFeel( UIManager.setText(""). frame. text2 = cost.toString(). appleqnt. send. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1Sealed. //Send data over net try{ send. this.getCrossPlatformLookAndFeelClassName()).setText(text2).sendTotalItems(itotal).25 Each").getMessage()).out.07.lookup(name)). itotal = 0. frame.setSecurityManager(new RMISecurityManager()).RemoteException e) { System.sendTotalCost(icost).out.addWindowListener(l). } }. icost = 0.getSecurityManager() == null) { System. } catch (java.setText(""). send.exit(0).setText(text). WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System. frame. send. text = num.setText(""). send. }catch (Exception e) { System.sendAppleQnt(apples).

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1Sealed.java } catch (Exception e) { System.printStackTrace().2000 12:34:49] . } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1Sealed.getMessage()).07.out.java (5 of 5) [24. e.println("RMIClient1 exception: " + e.

addActionListener(this).io.security. import java.awt. applesNo = new JTextArea(). import java. import java. JPanel panel. panel. customerNo = new JTextArea().*.*.*. pearsNo. pears.File.spec. total = new JLabel("Total Items:"). icost = new JTextArea().RandomAccessFile.server.util. import javax. total. itotal = new JTextArea(). import com.setBackground(Color.*.*.io. class RMIClient2 extends JFrame implements ActionListener { JLabel creditCard.swing. icost. panel.*.*. //Create text area components creditNo = new JTextArea(). peachesNo = new JTextArea(). view.swing. PrintWriter out = null. applesNo. apples = new JLabel("Apples:").setLayout(new GridLayout(0.crypto. import java. peachesNo.FileInputStream. cost = new JLabel("Total Cost:").Color. reset = new JButton("Reset").addActionListener(this). pearsNo = new JTextArea(). static Send send. clicked. pears = new JLabel("Pears:").io. import javax. //Create buttons view = new JButton("View Order").2)). itotal. peaches. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient2Sealed. reset.java (1 of 4) [24. cost.*.io.net.GridLayout.white). reset. import java.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient2Sealed.awt.*.java. Socket socket = null.event. customerNo. peaches = new JLabel("Peaches:").crypto. String customer.2000 12:34:53] . JButton view. custID. custID = new JLabel("Customer ID:").*. apples. import java. import java. JTextArea creditNo.java import java. //Create panel for 2-column layout //Set white background color panel = new JPanel().rmi.awt. RMIClient2(){ //Begin Constructor //Create labels creditCard = new JLabel("Credit Card:").07.rmi.*. import java. import java.sun.*.*. import java. import java. //import javax.

Double price.setText(text). //If View button pressed //Get data from server and display it if(source == view){ try{ wrappedKey = send. byte[] encrypted.add(panel). encrypted credit card number){ // Get private key from file // Create asymmetric cipher (do not use RSA) // Initialize cipher for decryption with private key // Unseal wrapped session key using asymmetric cipher // Create symmetric cipher // Initialize cipher for decryption with session key // Decrypt credit card number with symmetric cipher } */ public void actionPerformed(ActionEvent event){ Object source = event. Integer itms. panel.07.add(creditCard). double cost.getKey(). panel. panel. String text=null.add(view).add(pearsNo). panel.add(apples). panel. encrypted = send. } //End Constructor /* public String decrypt(sealed key. creditNo.add(peaches).setText(new String(credit)). panel.2000 12:34:53] . panel.getCustID().add(pears). file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient2Sealed.add(creditNo). byte[] wrappedKey. int items. panel. i.add(custID). panel. panel.add(cost).add(reset). customerNo. panel. panel.getSource(). panel.java //Add components to panel columns //going left to right and top to bottom getContentPane(). //Decrypt credit card number String credit = decrypt(sealed.getEncrypted().add(customerNo). panel.add(total).java (2 of 4) [24. unit. encrypted).add(applesNo).file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient2Sealed.add(peachesNo).add(icost).add(itotal). text = send. panel. panel.

setText(""). WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.toString().getAppleQnt(). frame.out. applesNo.setText(text).rmi.2000 12:34:53] . } catch (java.exit(0). itotal.net.getPeachQnt().getSecurityManager() == null) { System.setText(unit). icost.NotBoundException e) { System.setText(""). text = send.setText(text). itotal.setText(text). } try { String name = "//" + args[0] + "/Send".setText("").java text = send. pearsNo.setText("").getTotalItems(). } }.setSecurityManager(new RMISecurityManager()). unit = price.07.RemoteException e){ System.pack(). i = itms.setText("").println("Cannot access data in server").file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient2Sealed.addWindowListener(l). price = new Double(cost). icost.println("sendData exception: " + e.setText(i). cost = send. frame. applesNo. } catch(java.rmi.RemoteException e) { System.getPearQnt(). peachesNo. customerNo. if(System. } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient2Sealed.setTitle("Fruit Order").java (3 of 4) [24.MalformedURLException e) { System.getMessage()).setText("").getTotalCost(). peachesNo. send = ((Send) Naming.out.println("Cannot access data in server").rmi. itms = new Integer(items). } catch (java.setText("").setVisible(true).lookup(name)). items = send. } catch(java. } } //If Reset button pressed //Clear all fields if(source == reset){ creditNo. text = send.out.println("Cannot access data in server"). frame. } } public static void main(String[] args){ RMIClient2 frame = new RMIClient2(). frame. pearsNo.out.toString().

java (4 of 4) [24.07.java } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient2Sealed.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient2Sealed.2000 12:34:53] .

security.*. creditCard = new JTextField(). peachqnt.interfaces.java (1 of 4) [24.awt.07.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1.swing. import java. import java.event. int itotal=0. pearqnt. applechk. reset. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1. peachqnt = new JTextField(). cost = new JTextArea().*. import java. import java. appleqnt.net.crypto.addActionListener(this).java. static Send send. totalCost = new JLabel("Total Cost:"). import com. class RMIClient1 extends JFrame implements ActionListener{ JLabel JLabel JLabel JLabel col1. import java. pearqnt. items = new JTextArea(). col2. customer = new JTextField(). JButton purchase.*. pearqnt = new JTextField(). JTextField creditCard.*.sun. totalCost. pearchk = new JLabel(" Pears"). JTextField appleqnt. cardNum = new JLabel(" Credit Card:").server. double icost=0.*. import java.swing. col2 = new JLabel("Specify Quantity"). peachchk.2000 12:34:56] . cardNum. JPanel panel.addActionListener(this).io.Color. custID. customer.awt. //Create labels and text field components applechk = new JLabel(" Apples").security.GridLayout. cost.*. import java.rmi.java import java. JTextArea items. custID = new JLabel(" Customer ID:").*. pearchk. RMIClient1(){ //Begin Constructor //Create left and right column labels col1 = new JLabel("Select Items"). pearqnt. appleqnt = new JTextField().*.setNextFocusableComponent(creditCard). peachqnt. peachchk = new JLabel(" Peaches").rmi. import javax. import java.addActionListener(this).*.*. //import javax. //Create labels and text area components totalItems = new JLabel("Total Items:").awt. totalItems.

panel.add(pearqnt).setBackground(Color.addActionListener(this).add(pearchk).add(creditCard). peachesNo. Integer applesNo.add(col2). panel. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1. panel. panel.2)). purchase.java (2 of 4) [24.add(col1). creditCard. panel.07. //Set panel layout to 2-column grid //on a white background panel.add(appleqnt).addActionListener(this). panel. panel.setLayout(new GridLayout(0. panel.add(reset).file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1.add(panel). pearsNo.java //Create buttons and make action listeners purchase = new JButton("Purchase").add(totalItems). } //End Constructor private void encrypt(credit card number){ //Create cipher for symmetric key encryption (DES) //Create a key generator //Create a secret (session) key with key generator //Initialize cipher for encryption with session key //Encrypt credit card number with cipher //Get public key from server //Create cipher for asymmetric encryption (RSA) //Initialize cipher for encryption with public key //Encrypt session key //Send encrypted credit card number and session key to server } public void actionPerformed(ActionEvent event){ Object source = event. reset = new JButton("Reset").add(cardNum).add(customer). panel. panel.white). panel. panel. reset. panel.setNextFocusableComponent(reset).add(totalCost).add(peachqnt).getSource(). num.add(items). panel.add(applechk). panel. panel.add(peachchk).add(purchase).2000 12:34:56] . panel. //Add components to panel columns //going left to right and top to bottom getContentPane(). panel. panel.add(cost).add(custID). //Create a panel for the components panel = new JPanel().

intValue().lang.java Double cost. //Calculate totals number = appleqnt.sendPeachQnt(peaches).getText(). custID. try{ send.setText(text2).cost.25). } catch (java.07. String number.getText(). file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1. cost = new Double(icost). peaches = peachqnt. itotal += peachesNo.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1. text2. if(number.NumberFormatException e) { peachqnt. } number = pearqnt.NumberFormatException e) { appleqnt.lang. apples = appleqnt.2000 12:34:56] .valueOf(number). itotal += pearsNo. pears = pearqnt. cardnum. this.getText(). } } else { itotal += 0.toString(). apples. } } else { itotal += 0.getText().setText("Invalid Value").length() > 0){ try{ peachesNo = Integer.setText("Invalid Value"). peaches. this.setText(text).length() > 0){ try{ pearsNo = Integer.getText(). if(number. text = num. send.getText().setText("Invalid Value").length() > 0){ try{ applesNo = Integer. if(number.NumberFormatException e) { pearqnt.sendCustID(custID).getText().sendPearQnt(pears). itotal += applesNo. pears.lang.java (3 of 4) [24.valueOf(number). send. text. send. } catch (java. } } else { itotal += 0.valueOf(number). if(source == purchase){ //Retrieve order information cardnum = creditCard. custID = customer. } num = new Integer(itotal). } catch (java.sendAppleQnt(apples).intValue().toString(). //Encrypt credit card number encrypt(cardnum).getText().items.intValue(). } number = peachqnt. icost = (itotal * 1. text2 = cost.

toString().2000 12:34:56] . send. appleqnt. frame.net.out.addWindowListener(l).out. itotal = 0.setText(""). send = ((Send) Naming.java send. icost = 0.setText(text2).setText("").exit(0). this.rmi. } } if(source == reset){ creditCard.println("Cannot look up remote server object").toString().setText(""). } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1. } catch(java. text2 = cost. } catch (java.NotBoundException e) { System.getSecurityManager() == null) { System. this. customer. num = new Integer(itotal). } } public static void main(String[] args){ RMIClient1 frame = new RMIClient1().setText(text). } try { String name = "//" + args[0] + "/Send".setTitle("Fruit $1.setVisible(true).rmi.cost.out.25 Each"). text = num. } catch (java. frame. } catch(java.sendTotalItems(itotal).RemoteException e) { System. frame.println("Cannot look up remote server object").println("Cannot look up remote server object").items.java (4 of 4) [24.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient1. if(System. } }. peachqnt. frame.setSecurityManager(new RMISecurityManager()).lookup(name)).pack(). creditCard. WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.RemoteException e){ System.setText(""). cost = new Double(icost).out.setText("").MalformedURLException e) { System. pearqnt.07.println("Cannot send data to server").setText("").sendTotalCost(icost).rmi.

Color.server.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient2.awt. apples. clicked. pearsNo = new JTextArea().sun.add(panel).setLayout(new GridLayout(0. apples = new JLabel("Apples:"). cost = new JLabel("Total Cost:").2)). applesNo. JTextArea creditNo. applesNo = new JTextArea().io. import java.setBackground(Color. import java.*. total. //import javax.*.io.swing. icost = new JTextArea().net. custID.rmi. customerNo = new JTextArea(). JButton view. import java. pears.java.*. reset = new JButton("Reset"). total = new JLabel("Total Items:").GridLayout.*.*.addActionListener(this). peaches. class RMIClient2 extends JFrame implements ActionListener { JLabel creditCard.*.File. import java. peachesNo.util. customerNo. import java. peaches = new JLabel("Peaches:"). String customer. import java. icost. creditNo = new JTextArea(). Socket socket = null.*.2000 12:34:58] . panel.add(creditCard). reset.event.io. itotal = new JTextArea(). RMIClient2(){ //Begin Constructor creditCard = new JLabel("Credit Card:"). panel. pears = new JLabel("Pears:").addActionListener(this). file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient2. import java. reset. itotal.*.*. JPanel panel.awt. import java. PrintWriter out = null.security. panel.swing.java (1 of 4) [24.FileInputStream.io. static Send send. peachesNo = new JTextArea(). pearsNo. panel = new JPanel(). custID = new JLabel("Customer ID:"). import java. panel. import java.add(creditNo). cost. import javax. import java. view = new JButton("View Order").07. getContentPane(). view.*. import com.java import java.awt.white).RandomAccessFile.rmi.*.crypto.*.

IOException{ byte b[] = custID.add(reset). panel.add(total).separatorChar + "monicap" + File.java (2 of 4) [24.add(itotal). "rw"). encrypted). i. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient2. double cost.getBytes(). File outputFile = new File(File. out. } public String decrypt(symmetric key. panel. Double price. panel.add(custID).close(). encrypted credit card number){ //Decrypt credit card number //Get private key from file //Create asymmetric cipher (RSA) //Initialize cipher for decryption with private key //Decrypt symmetric key //Instantiate symmetric key //Create symmetric cipher //Initialize Cipher for decryption with session key //Decrypt credit card number with symmetric Cipher } public void actionPerformed(ActionEvent event){ Object source = event. encrypted = send.add(apples).setText(credit). panel. unit.getEncrypted().length()).add(cost).2000 12:34:58] . panel.txt").getCreditCard(). String text=null.add(view). int items. creditNo.write(b). String credit = decrypt(sealed.add(pears). if(source == view){ try{ sealed = send. out. SealedObject sealed.separatorChar + "home" + File. panel.add(applesNo). panel.add(peachesNo).file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient2. out.getSource().07.add(pearsNo). panel. RandomAccessFile out = new RandomAccessFile(outputFile.add(peaches). panel.add(customerNo).separatorChar + "text.seek(outputFile. out. byte[] encrypted. panel. panel. } //End Constructor public void writeToFile(String custID) throws java. panel. panel.java panel.add(icost).writeByte(10). Integer itms.io.

setText("").toString(). frame.setText(""). icost. if(System.toString().setText("").exit(0). unit = price.setText(""). applesNo. WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System. itotal.net. cost = send.out.println("Cannot access data in server"). text = send. itms = new Integer(items). peachesNo. itotal. customerNo. text = send. } catch (java. applesNo. } } if(source == reset){ creditNo. peachesNo.setText(text). writeToFile(text). text = send.pack(). send = ((Send) Naming.setText("").out. } try { String name = "//" + args[0] + "/Send". pearsNo.2000 12:34:58] .out.07. frame.setText(text).java (3 of 4) [24.getSecurityManager() == null) { System. customerNo. i = itms.java text = send. } catch(java.getCustID().getTotalCost().rmi.RemoteException e) { System. frame.println("Cannot create remote server object").setTitle("Fruit Order").rmi. } } public static void main(String[] args){ RMIClient2 frame = new RMIClient2(). } catch (java. price = new Double(cost).getPearQnt().setText(i). icost.setSecurityManager(new RMISecurityManager()).setText("").addWindowListener(l).setText(text).setText(unit).getTotalItems(). pearsNo.NotBoundException e) { file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient2. } catch (java.setVisible(true).lookup(name)). frame.setText(text).RemoteException e) { System.getAppleQnt().println("Cannot look up server object").MalformedURLException e) { System.getPeachQnt().setText("").file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient2. items = send.rmi. } }.

java (4 of 4) [24.java System.println("Cannot access data in server"). } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient2.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitPseudo/RMIClient2.07.out.2000 12:34:58] .

*.event.awt. javax. static Send send. cardNum. creditCard = new JTextField(). totalCost.rmi. JPanel panel. double icost=0.*.io. col2 = new JLabel("Specify Quantity").*. import java. purchase. java. import java. java.swing. cost = new JTextArea(). pearqnt.awt. pearqnt. RMIClient1(){ //Begin Constructor //Create left and right column labels col1 = new JLabel("Select Items"). customer.setNextFocusableComponent(creditCard). int itotal=0. reset. totalItems. peachqnt = new JTextField(). //Create labels and text area components totalItems = new JLabel("Total Items:"). customer = new JTextField().addActionListener(this). JTextField appleqnt. import java. class RMIClient1 extends JFrame implements ActionListener{ JLabel JLabel JLabel JLabel col1.2000 12:35:01] .server. peachchk = new JLabel(" Peaches"). peachqnt. JButton purchase.Color.rmi. peachqnt.net. custID = new JLabel(" Customer ID:"). pearqnt = new JTextField(). file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RMIClient1. pearchk.java (1 of 4) [24.GridLayout.*. custID.awt. peachchk. //Create labels and text field components applechk = new JLabel(" Apples"). JTextArea items. totalCost = new JLabel("Total Cost:").*. applechk. appleqnt = new JTextField().file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RMIClient1.addActionListener(this). cost.addActionListener(this). pearqnt.07. import java. col2. appleqnt.*. cardNum = new JLabel(" Credit Card:"). JTextField creditCard. items = new JTextArea().addActionListener(this). //Create buttons and make action listeners purchase = new JButton("Purchase").java import import import import java. pearchk = new JLabel(" Pears").

panel. send.add(panel).getText(). file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RMIClient1.java reset = new JButton("Reset"). //Add components to panel columns //going left to right and top to bottom getContentPane().add(cost). custID. try{ //Send data over net send.sendCustID(custID). panel. panel. custID = customer. } //End Constructor public void actionPerformed(ActionEvent event){ Object source = event.add(creditCard). pears.2000 12:35:01] .sendPearQnt(pears).add(reset). text. if(source == purchase){ //Get data from text fields cardnum = creditCard. peaches. num.add(applechk).file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RMIClient1.add(col2).getText(). panel. apples = appleqnt.add(pearqnt).getText().07. panel.addActionListener(this).java (2 of 4) [24.add(items). pearsNo.white).add(purchase). peachesNo. panel.setBackground(Color. panel.add(peachqnt). reset. panel.add(totalCost). send. panel. cardnum.add(totalItems).sendCreditCard(cardnum). panel. panel. panel.add(custID). panel.getSource().add(appleqnt). Double cost. peaches = peachqnt.add(peachchk). send. Integer applesNo. //Create a panel for the components panel = new JPanel(). pears = pearqnt.add(col1).add(pearchk).add(customer). String number. panel. .add(cardNum).2)). panel. panel. panel.sendPeachQnt(peaches). . //Set panel layout to 2-column grid //on a white background panel. //If Purchase button pressed . text2.getText(). panel. panel.setLayout(new GridLayout(0. send.getText().sendTotalCost(icost).sendAppleQnt(apples). send. apples.

appleqnt. } //If Return in apple quantity text field //Calculate totals if(source == appleqnt){ number = appleqnt.setText(""). this. if(number. itotal += applesNo.2000 12:35:01] .intValue().length() > 0){ peachesNo = Integer. creditCard.java send.cost. } else { itotal += 0. itotal = 0.getText(). peachqnt.toString(). if(number.length() > 0){ applesNo = Integer. text = num. pearqnt.println("Cannot send data to server"). } else { itotal += 0.setText(""). this.valueOf(number).setText(text).length() > 0){ pearsNo = Integer.items.getText().valueOf(number). } } //If Return in pear quantity text field //Calculate totals if(source == pearqnt){ number = pearqnt.valueOf(number).RemoteException e) { System.sendTotalItems(itotal). icost = 0.toString(). itotal += pearsNo. } catch (java. if(number.getText(). } else { itotal += 0.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RMIClient1.07.setText(text2).java (3 of 4) [24. icost = (itotal * 1.out. } } //If Return in peach quantity text field //Calculate totals if(source == peachqnt){ number = peachqnt. itotal += peachesNo.rmi. customer. text2 = cost.intValue().setText(""). } } //If Reset button pressed //Clear all fields if(source == reset){ creditCard.intValue(). } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RMIClient1.25).setText("").setText(""). cost = new Double(icost).setText(""). } } num = new Integer(itotal).

pack().RemoteException e){ System.2000 12:35:01] . } }.out.out. frame.setVisible(true).07. } catch(java.setTitle("Fruit $1. frame. } catch(java.addWindowListener(l).file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RMIClient1.rmi.25 Each").exit(0).java public static void main(String[] args){ RMIClient1 frame = new RMIClient1(). frame.java (4 of 4) [24.net. if(System.println("Cannot look up remote server object"). send = ((Send) Naming.NotBoundException e) { System.MalformedURLException e) { System. } try { String name = "//" + args[0] + "/Send".getSecurityManager() == null) { System. } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RMIClient1.rmi.println("Cannot look up remote server object").setSecurityManager(new RMISecurityManager()).lookup(name)). WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.println("Cannot look up remote server object").out. frame. } catch (java.

} public String getAppleQnt(){ return apples. class RemoteServer extends UnicastRemoteObject implements Send { private private private private private private private String cardnum. import java. } public void sendCustID(String cust){ custID = cust.07. String apples.net.BorderLayout. } public String getCreditCard(){ return cardnum. } public String getCustID(){ return custID.rmi. } public void sendPearQnt(String prs){ pears = prs.Color. } public void sendTotalCost(double cst){ cost = cst.*.*. String custID.server. } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RemoteServer. int items.awt.*.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RemoteServer.*.awt. public RemoteServer() throws RemoteException { super(). } public void sendCreditCard(String creditcard){ cardnum = creditcard.event.io. import java. import java. } public String getPearQnt(){ return pears. import java.2000 12:35:02] .rmi. double cost. import java. String peaches. } public String getPeachQnt(){ return peaches.java (1 of 2) [24.*. } public void sendPeachQnt(String pchs){ peaches = pchs. import java. } public void sendAppleQnt(String apps){ apples = apps. String pears.java import java.awt.

} catch (java.out.eng. } catch (java.println("Cannot create remote server object").out.println("Cannot look up server object").getSecurityManager() == null) { System. try { Send remoteServer = new RemoteServer(). } String name = "//kq6py.java (2 of 2) [24.out. remoteServer).sun.println("RemoteServer bound").com/Send".07. } public static void main(String[] args){ if(System.rmi.2000 12:35:02] . } public int getTotalItems(){ return items. System. } public void sendTotalItems(int itm){ items = itm.rebind(name.net.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RemoteServer.setSecurityManager(new RMISecurityManager()). } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RemoteServer.RemoteException e) { System.MalformedURLException e) { System. Naming.java public double getTotalCost(){ return cost.

apples. apples = new JLabel("Apples:").*. import java. total.util.swing.2000 12:35:04] .add(creditCard). panel. cost = new JLabel("Total Cost:"). pears = new JLabel("Pears:").addActionListener(this). itotal. reset. icost. applesNo. import java. import java. custID. panel.07. peaches.io. import java.net. panel. RMIClient2(){ //Begin Constructor //Create labels creditCard = new JLabel("Credit Card:"). java.*.*.*.File.RandomAccessFile.*. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RMIClient2.io. customerNo.awt. java. pears. panel.java (1 of 3) [24.rmi. reset = new JButton("Reset").*. //Create text area components creditNo = new JTextArea(). peachesNo.Color. javax.*. total = new JLabel("Total Items:").2)). applesNo = new JTextArea().FileInputStream. //Add components to panel columns //going left to right and top to bottom getContentPane(). import java.awt.*.io. cost. static Send send. JPanel panel.awt. pearsNo = new JTextArea().io.addActionListener(this).server. import java. peaches = new JLabel("Peaches:").add(panel). clicked. icost = new JTextArea(). import java. JTextArea creditNo.rmi. pearsNo. import java.setLayout(new GridLayout(0. String customer.java import import import import java. peachesNo = new JTextArea().GridLayout. class RMIClient2 extends JFrame implements ActionListener { JLabel creditCard. custID = new JLabel("Customer ID:"). reset. view. itotal = new JTextArea().*. customerNo = new JTextArea().file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RMIClient2. //Create panel for 2-column layout //Set white background color panel = new JPanel().setBackground(Color. //Create buttons view = new JButton("View Order"). JButton view.white).event.add(creditNo).

getAppleQnt(). panel. text = send. panel.rmi.add(total).add(pears). price = new Double(cost).setText(i).setText(unit).java (2 of 3) [24.add(customerNo). itotal.add(view).add(peaches). peachesNo. creditNo. } } //If Reset button pressed .2000 12:35:04] .add(custID).RemoteException e) { System. panel. items = send.add(itotal). panel.getSource().getCreditCard().setText(text). pearsNo.getPeachQnt().add(apples). . text = send.add(cost). double cost.07. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RMIClient2.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RMIClient2.setText(text).getTotalCost(). Integer itms. panel.add(pearsNo). icost. panel. } //End Constructor public void actionPerformed(ActionEvent event){ Object source = event. panel. } catch (java.add(icost). int items. Double price.setText(text). panel. panel.toString(). panel. itms = new Integer(items).getCustID(). unit.add(applesNo). //If View button pressed //Get data from server and display it if(source == view){ try{ text = send.java panel.getTotalItems(). . i. unit = price. applesNo.add(peachesNo). panel.add(reset). panel. text = send.out.toString(). String text=null. i = itms.println("Cannot access data in server").getPearQnt().setText(text). customerNo. text = send. cost = send. panel.setText(text).

RemoteException e){ System. } catch(java. pearsNo.println("Cannot access data in server"). send = ((Send) Naming. frame.setText("").net. frame.pack(). } catch (java.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RMIClient2.lookup(name)).out. if(System. itotal. } } public static void main(String[] args){ RMIClient2 frame = new RMIClient2().NotBoundException e) { System.setSecurityManager(new RMISecurityManager()). customerNo.out. } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/RMIClient2. frame.setText("").setText("").java //Clear all fields if(source == reset){ creditNo.setText("").setVisible(true).rmi.07.exit(0). WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.getSecurityManager() == null) { System.rmi. peachesNo.2000 12:35:04] .println("Cannot access data in server"). frame.setText("").MalformedURLException e) { System. } catch(java.out. } }.java (3 of 3) [24.setText("").setText("").addWindowListener(l). icost. } try { String name = "//" + args[0] + "/Send".println("Cannot access data in server"). applesNo.setTitle("Fruit Order").

public void sendTotalItems(int items) throws RemoteException. import java. public void sendPeachQnt(String peaches) throws RemoteException. public String getCreditCard() throws RemoteException. public void sendAppleQnt(String apples) throws RemoteException.RemoteException. public String getCustID() throws RemoteException.rmi.java [24. public void sendCustID(String cust) throws RemoteException.java import java.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/Send. public String getPeachQnt() throws RemoteException.rmi. public String getPearQnt() throws RemoteException. } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/Fruit/Send. public void sendTotalCost(double cost) throws RemoteException. public int getTotalItems() throws RemoteException. public double getTotalCost() throws RemoteException. public interface Send extends Remote { public void sendCreditCard(String cardnum) throws RemoteException.2000 12:35:04] .Remote. public void sendPearQnt(String pears) throws RemoteException. public String getAppleQnt() throws RemoteException.07.

//Create labels and text area components totalItems = new JLabel("Total Items:"). custID.addActionListener(this).*. JTextField appleqnt. peachqnt. reset. pearqnt = new JTextField().server.event. pearchk = new JLabel(" Pears"). file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitImprove/RMIClient1.awt. totalCost.*.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitImprove/RMIClient1. JTextField creditCard. col2 = new JLabel("Specify Quantity"). items = new JTextArea().rmi. int itotal=0. peachchk. RMIClient1(){ //Begin Constructor //Create left and right column labels col1 = new JLabel("Select Items"). static Send send. import java.GridLayout. purchase. creditCard = new JTextField().awt.2000 12:35:06] . peachchk = new JLabel(" Peaches").swing. JButton purchase.*. import java. javax.java (1 of 4) [24. pearqnt. //Create buttons and make action listeners purchase = new JButton("Purchase"). pearqnt. totalCost = new JLabel("Total Cost:").awt.addActionListener(this). import java.addActionListener(this). cost = new JTextArea(). appleqnt = new JTextField(). pearchk. custID = new JLabel(" Customer ID:"). double icost=0. JPanel panel. peachqnt.net.java import import import import java.setNextFocusableComponent(creditCard).*. applechk.addActionListener(this).07. cost. cardNum. cardNum = new JLabel(" Credit Card:"). //Create labels and text field components applechk = new JLabel(" Apples"). peachqnt = new JTextField(). totalItems. class RMIClient1 extends JFrame implements ActionListener{ JLabel JLabel JLabel JLabel col1. pearqnt. col2.Color. import java. customer.*. appleqnt.*. java. java.rmi. JTextArea items.io. customer = new JTextField().

panel.java reset = new JButton("Reset"). peaches = peachqnt.add(cardNum). pearsNo. panel. .getText(). pears = pearqnt. panel.getText(). //If Purchase button pressed . Double cost.2)). panel.add(col2).intValue(). panel. apples = appleqnt.add(peachqnt). //Create a panel for the components panel = new JPanel(). //Add components to panel columns //going left to right and top to bottom getContentPane(). panel.add(purchase). peaches.getSource(). custID = customer.getText().add(reset). String cardnum.valueOf(apples).setBackground(Color. panel.add(applechk).add(custID).add(pearchk).length() > 0){ applesNo = Integer.add(appleqnt).add(panel). text. panel.setLayout(new GridLayout(0.add(col1). panel.07. panel. //Set panel layout to 2-column grid //on a white background panel. panel.add(items).addActionListener(this).add(totalCost).add(customer). text2. //Calculate total items if(apples. pears.add(pearqnt). custID. num.add(creditCard). if(source == purchase){ cardnum = creditCard. } //End Constructor public void actionPerformed(ActionEvent event){ Object source = event.add(totalItems).white). itotal += applesNo. panel.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitImprove/RMIClient1.getText(). panel. panel.add(peachchk).add(cost). Integer applesNo. apples. } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitImprove/RMIClient1.2000 12:35:06] .java (2 of 4) [24. reset. } else { itotal += 0. panel.getText(). panel. peachesNo. panel. . panel. panel.

println("Cannot send data to server").items. icost = 0.setTitle("Fruit $1. text = num. this. text2 = cost.intValue(). } else { itotal += 0.out.setText("").length() > 0){ peachesNo = Integer. itotal += peachesNo.setText(""). customer. cost = new Double(icost). send.sendAppleQnt(apples).toString(). send.cost.toString().sendCreditCard(cardnum).setText(text2). } if(pears. frame. cost = new Double(icost). send.toString().sendPeachQnt(peaches). //Calculate and display running cost icost = (itotal * 1.java if(peaches.valueOf(pears). this.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitImprove/RMIClient1.sendCustID(custID).valueOf(peaches).length() > 0){ pearsNo = Integer.cost. this.setText(""). text2 = cost. send.java (3 of 4) [24. num = new Integer(itotal). pearqnt.intValue().setText(""). itotal = 0. WindowListener l = new WindowAdapter() { file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitImprove/RMIClient1. itotal += pearsNo.setText(text2).toString().RemoteException e) { System.07. } catch (java.setText(text).sendPearQnt(pears).25 Each").setText("").2000 12:35:06] .setText(text).rmi. send. appleqnt. peachqnt.25). this. } //Display running total num = new Integer(itotal). } else { itotal += 0. } } public static void main(String[] args){ RMIClient1 frame = new RMIClient1().setText(""). send. text = num. } } //If Reset button pressed //Clear all fields if(source == reset){ creditCard.sendTotalItems(itotal). //Send data over net try{ send.sendTotalCost(icost). creditCard.items.

lookup(name)). if(System.MalformedURLException e) { System.rmi.pack(). } catch(java.println("Cannot look up remote server object"). } catch(java.java (4 of 4) [24. frame.java public void windowClosing(WindowEvent e) { System.out.RemoteException e){ System.net. } catch (java.2000 12:35:06] .file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitImprove/RMIClient1. frame.07.addWindowListener(l).println("Cannot look up remote server object").NotBoundException e) { System. } }.getSecurityManager() == null) { System. } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitImprove/RMIClient1.out. send = ((Send) Naming.println("Cannot look up remote server object").exit(0).rmi.out. frame.setSecurityManager(new RMISecurityManager()).setVisible(true). } try { String name = "//" + args[0] + "/Send".

cost = new JTextArea(). cardNum = new JLabel(" Credit Card:"). //Create buttons and make action listeners purchase = new JButton("Purchase").awt.awt.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitError/RMIClient1. custID. cost. double icost=0.event.net.*.java (1 of 4) [24.java import import import import java. items = new JTextArea().awt. //Create labels and text field components applechk = new JLabel(" Apples"). peachchk = new JLabel(" Peaches"). pearqnt. import java. JPanel panel. totalItems. appleqnt.2000 12:35:09] . peachqnt. cardNum. import java. pearchk.GridLayout. reset.io. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitError/RMIClient1. java. col2.swing. int itotal=0. class RMIClient1 extends JFrame implements ActionListener{ JLabel JLabel JLabel JLabel col1. JButton purchase. purchase. //Create labels and text area components totalItems = new JLabel("Total Items:"). java. totalCost = new JLabel("Total Cost:"). JTextField appleqnt. import java.addActionListener(this).*.07.addActionListener(this). RMIClient1(){ //Begin Constructor //Create left and right column labels col1 = new JLabel("Select Items"). JTextField creditCard. pearqnt. import java. peachqnt. col2 = new JLabel("Specify Quantity"). customer = new JTextField(). appleqnt = new JTextField().rmi. JTextArea items.addActionListener(this).rmi.*. pearqnt = new JTextField(). applechk. pearchk = new JLabel(" Pears"). totalCost.setNextFocusableComponent(creditCard). custID = new JLabel(" Customer ID:"). peachqnt = new JTextField().server.*. static Send send. javax.*. peachchk.addActionListener(this). creditCard = new JTextField().Color.*. pearqnt. customer.

add(appleqnt).add(totalItems). panel. apples = appleqnt.add(customer). peachesNo.add(creditCard).intValue(). }catch(java. num. //Set panel layout to 2-column grid //on a white background panel. apples. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitError/RMIClient1.add(panel).07. panel. //Calculate total items if(apples. .setText("Invalid Value"). panel.getText().addActionListener(this). panel.setBackground(Color. panel.add(pearqnt). cardnum. custID. panel.getText(). peaches. panel.add(col1).NumberFormatException e){ appleqnt.lang.add(peachchk).add(cost). panel. String number. panel. panel. Double cost. panel. pears = pearqnt. //Create a panel for the components panel = new JPanel(). pears.getSource().setLayout(new GridLayout(0.add(cardNum).add(totalCost). panel.add(purchase). panel. text.getText().add(applechk).length() > 0){ //Catch invalid number error try{ applesNo = Integer.add(reset).java reset = new JButton("Reset").add(items). if(source == purchase){ cardnum = creditCard. panel.2)).add(pearchk). panel. //Add components to panel columns //going left to right and top to bottom getContentPane(). pearsNo.getText(). reset.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitError/RMIClient1.add(peachqnt).add(custID).getText(). panel.add(col2). } //End Constructor public void actionPerformed(ActionEvent event){ Object source = event. panel. text2. . custID = customer. Integer applesNo.white).java (2 of 4) [24.2000 12:35:09] . panel. panel. //If Purchase button pressed . itotal += applesNo. peaches = peachqnt.valueOf(apples).

sendAppleQnt(apples). cost = new Double(icost). text = num.intValue(). send. } catch (java.setText(""). appleqnt. //Calculate and display running cost icost = (itotal * 1. } //Display running total num = new Integer(itotal).out.toString().2000 12:35:09] .println("Unable to send data").cost.setText(""). itotal += peachesNo. itotal += pearsNo.setText("").sendCreditCard(cardnum). } } else { itotal += 0.setText(text2).25). peachqnt. pearqnt.sendTotalItems(itotal). send. this.setText("Invalid Value"). customer. send.setText("").items.setText(text). }catch(java.java } } else { itotal += 0.length() > 0){ //Catch invalid number error try{ pearsNo = Integer. //Send data over net try{ send.valueOf(peaches).sendCustID(custID).sendPearQnt(pears).toString().sendPeachQnt(peaches).java (3 of 4) [24. creditCard. this. } if(pears. icost = 0.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitError/RMIClient1.setText(""). } } //If Reset button pressed //Clear all Fields if(source == reset){ creditCard. send.lang.NumberFormatException e){ pearqnt.length() > 0){ //Catch invalid number error try{ peachesNo = Integer.intValue().RemoteException e) { System. send. send. text2 = cost.setText("Invalid Value").rmi.lang. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitError/RMIClient1.sendTotalCost(icost).07. }catch(java. } if(peaches.valueOf(pears).NumberFormatException e){ peachqnt. } } else { itotal += 0.setText("").

this.NotBoundException e) { System. frame. text2 = cost.MalformedURLException e) { System. this.java (4 of 4) [24.rmi.java cost = new Double(icost). frame.out.setText(text). } } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitError/RMIClient1.out.out.rmi.getSecurityManager() == null) { System.lookup(name)).setSecurityManager(new RMISecurityManager()). send = ((Send) Naming.println("Cannot look up server object"). if(System.25 Each"). } }. text = num.println("Cannot access data in server").file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/FruitError/RMIClient1. } } public static void main(String[] args){ RMIClient1 frame = new RMIClient1().setVisible(true).07. frame.setText(text2).net. } catch (java. } catch(java. num = new Integer(itotal).2000 12:35:09] . frame.setTitle("Fruit $1. itotal = 0. WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.RemoteException e) { System.println("Cannot create remote server object").pack(). } try { String name = "//" + args[0] + "/Send". } catch (java.addWindowListener(l).exit(0).cost.toString().items.toString().

add(panel). import java.java (1 of 2) [24. panel.07. getContentPane().getText(). out. panel.add("South". JButton button.Color. textField.println("Text received :" + line).white).println("No I/O"). text). button.*. System.getSource(). BufferedReader in = null.awt. Socket socket = null.getOutputStream(). } catch (IOException e){ System.setLayout(new BorderLayout()).net. System. if(source == button){ //Send data over socket String text = textField. javax. java.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/SocketClient.add("North".out. clicked. 4444).setText(new String("")). panel = new JPanel().readLine().setBackground(Color.out.event.*. out = new PrintWriter(socket. } //End Constructor public void actionPerformed(ActionEvent event){ Object source = event.exit(1). import java.getInputStream())). button = new JButton("Click Me").eng").2000 12:35:10] .*. JPanel panel. System.println("Unknown host: kq6py. panel. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/SocketClient. } catch (UnknownHostException e) { System.exit(1). class SocketClient extends JFrame implements ActionListener { JLabel text. } } } public void listenSocket(){ //Create socket connection try{ socket = new Socket("kq6py". } catch (IOException e) { System. in = new BufferedReader(new InputStreamReader(socket.out.BorderLayout.awt. panel. System.awt.addActionListener(this).add("Center". textField = new JTextField(20).swing.println(text). panel. PrintWriter out = null.java import import import import java.io. button). java. //Receive text from server try{ String line = in.println("Read failed"). SocketClient(){ //Begin Constructor text = new JLabel("Text to send over socket:"). true).exit(1). JTextField textField.out.*. textField).

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/SocketClient.java

} } public static void main(String[] args){ SocketClient frame = new SocketClient(); frame.setTitle("Client Program"); WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }; frame.addWindowListener(l); frame.pack(); frame.setVisible(true); frame.listenSocket(); } }

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/SocketClient.java (2 of 2) [24.07.2000 12:35:10]

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/SocketServer.java

import import import import

java.awt.Color; java.awt.BorderLayout; java.awt.event.*; javax.swing.*;

import java.io.*; import java.net.*; class SocketServer extends JFrame implements ActionListener { JButton button; JLabel label = new JLabel("Text received over socket:"); JPanel panel; JTextArea textArea = new JTextArea(); ServerSocket server = null; Socket client = null; BufferedReader in = null; PrintWriter out = null; String line; SocketServer(){ //Begin Constructor button = new JButton("Click Me"); button.addActionListener(this); panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.setBackground(Color.white); getContentPane().add(panel); panel.add("North", label); panel.add("Center", textArea); panel.add("South", button); } //End Constructor public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if(source == button){ textArea.setText(line); } } public void listenSocket(){ try{ server = new ServerSocket(4444); } catch (IOException e) { System.out.println("Could not listen on port 4444"); System.exit(-1); } try{ client = server.accept(); } catch (IOException e) { System.out.println("Accept failed: 4444"); System.exit(-1); } try{ in = new BufferedReader(new InputStreamReader(client.getInputStream())); out = new PrintWriter(client.getOutputStream(), true); } catch (IOException e) { System.out.println("Accept failed: 4444"); System.exit(-1);

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/SocketServer.java (1 of 2) [24.07.2000 12:35:11]

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/SocketServer.java

} while(true){ try{ line = in.readLine(); //Send data back to client out.println(line); } catch (IOException e) { System.out.println("Read failed"); System.exit(-1); } } } protected void finalize(){ //Clean up try{ in.close(); out.close(); server.close(); } catch (IOException e) { System.out.println("Could not close."); System.exit(-1); } } public static void main(String[] args){ SocketServer frame = new SocketServer(); frame.setTitle("Server Program"); WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }; frame.addWindowListener(l); frame.pack(); frame.setVisible(true); frame.listenSocket(); } }

file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/SocketServer.java (2 of 2) [24.07.2000 12:35:11]

exit(-1).getInputStream())).BorderLayout.event.textArea = textArea. ServerSocket server = null.07.out. true). System. PrintWriter out = null. import java. textArea). } //End Constructor public void listenSocket(){ try{ server = new ServerSocket(4444). JTextArea textArea = new JTextArea().*.out. BufferedReader in = null.white).add("North".client = client. textArea.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/SocketThrdServer. private JTextArea textArea.io. //Send data back to client out. try{ in = new BufferedReader(new InputStreamReader(client.java (1 of 2) [24.readLine(). } catch (IOException e) { System.java import import import import java. class ClientWorker implements Runnable { private Socket client.*. panel. System.swing. } } } } class SocketThrdServer extends JFrame{ JLabel label = new JLabel("Text received over socket:").println("Read failed").println("Could not listen on port 4444"). out = new PrintWriter(client.awt. JPanel panel. ClientWorker(Socket client. getContentPane(). javax.exit(-1). } catch (IOException e) { System. SocketThrdServer(){ //Begin Constructor panel = new JPanel().Color.2000 12:35:12] .append(line).add(panel).println("in or out failed"). label). System. } public void run(){ String line. panel.setLayout(new BorderLayout()).add("Center". panel.getOutputStream().*.net. import java. java.awt. } catch (IOException e) { System.out. panel.exit(-1). } while(true){ try{ line = in.println(line).awt.setBackground(Color.*. file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/SocketThrdServer. JTextArea textArea) { this. java. this.

exit(-1). frame. } catch (IOException e) { System.2000 12:35:12] .java (2 of 2) [24. frame.exit(-1).07. frame. System. frame. } catch (IOException e) { System.close().addWindowListener(l).listenSocket(). textArea). WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System. System. } } file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/SocketThrdServer.println("Accept failed: 4444").out. } } } protected void finalize(){ //Objects created in run method are finalized when //program terminates and thread exits try{ server.exit(0). try{ w = new ClientWorker(server. } }. t.java } while(true){ ClientWorker w.accept(). } } public static void main(String[] args){ SocketThrdServer frame = new SocketThrdServer().setTitle("Server Program"). frame.start().setVisible(true).out.file:///T|/General/Documentation/Java/Basic Java 2/HTML/Code/SocketThrdServer.pack(). Thread t = new Thread(w).println("Could not close socket").