0% found this document useful (0 votes)
20 views

Java

1. Java is an object-oriented programming language commonly used for developing network and internet applications. It allows applications to run on any platform due to its platform independence. 2. Java supports multithreading and applets. Applets are Java programs that run in web browsers on the client side of a web connection. 3. Key features of Java include being architecture neutral, distributed, multithreaded, secure, dynamic with automatic garbage collection.

Uploaded by

Rahul Ramesh
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Java

1. Java is an object-oriented programming language commonly used for developing network and internet applications. It allows applications to run on any platform due to its platform independence. 2. Java supports multithreading and applets. Applets are Java programs that run in web browsers on the client side of a web connection. 3. Key features of Java include being architecture neutral, distributed, multithreaded, secure, dynamic with automatic garbage collection.

Uploaded by

Rahul Ramesh
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 24

Java:

It is an object oriented programming language which is used commonly for


developing networking applications and internet applications.Java is a highly powerful
language whose applications are
platform independent. Java also supports, MultiThreading, a specialized form of
MultiTasking. These two features are unique to Java. Further,Java applications can be
divided into two,

1. Application programs.
2. Applets.

Application programs are programs which are similar to programs created using
any other language. But it is the "Applets" that makes Java, a special language. Applets
are Java programs that can be run using a web browser and hence an Applet executes on
the client side of a web connection.

Features of Java:

Architecture-Neutral

Distributed

Multithreaded

Secure
Dynamic

Automatic Garbage Collection

1. Java is a portable language(i.e) java programs in the form of binary code can be run on
variety of architectures to produce a unique output.
The feature that enables this, is the output of the java compiler. As, usual it is not the
platform specific .EXE file, but it is the .CLASS file which contains byte codes. Byte
codes are highly optimized set of intermediate instructions designed to be executed by the
Java Runtime Environment. In fact, each and every Java program is compiled by the Java
compiler and a corresponding .CLASS file is created. Then the .CLASS file is
interpretted by an interpretter to generate the required output.

2. Java can be used for developing networking or distributed applications.


It is possible, since Java provides built-in classes for handling network
communication.

3. Multithreading is a specialized form of multitasking. In multithreading two or more


pieces of a single program run concurrently as seperate "threads", thus enabling quicker
processing and ensuring resource utilization. It is used to make maximum utilization of
the cpu-time.

4. Security, is an important concern as far as networking is concerned.


Since, Java programs are compiled to a .CLASS file, and the .CLASS file
is interpretted to the desired output, the Java Runtime Environment is
in full control the execution process. Thus it forms as a "fire-wall" between the host
machine and rest of the network.

5. In Java, memory allocation for an object is done dynamically at the runtime. This
enables an object to be tied more closely with the methods it
operates upon, thus, enabling a call to the method which matches the type of the call,
dynamically, at the runtime. No, static memory allocation for objects is possible in Java.

6. In Java, though the memory is explicity allocated as and when needed,


deallocation is entirely automated and is not an explicit process. In Java, the
memory occupied by an object is automatically reclaimed by the garbage collector, when
an object goes out of scope, and is released for further use. This, implicit garbage
collection in Java is a great power of Java.

APPLET

What is applet
--------------
Applets are java programs that are integrated into web pages. When a web page
containing an applet is displayed by a web browser, the applet is loaded and
executed. The applet's output is displayed within a subset of the browser's display
area.

When an applet begins ,it calls the following methods,


in the following sequence

1. init()
---------
The init() method is the first method to be called. This is where you should
initialize variables. This method is called only once during the life time of your
applet.

2.start()
---------
The start() method is called after init(). It is also called to restart an applet
after it has been stopped. start() is called each time an applet's HTML document
is displayed on the page.

3.paint()
---------
The paint() method is called each time your applet's output must be
redrawn. paint() is called when the applet begins execution.The paint method has
one parameter of type Graphics.This parameter will contain the graphics
context,which describes the graphics environment in which the applet is
running.

When an applet is terminated, the following sequence of method calls


takes place.

1.stop()
--------
The stop() method is called when a web browser leaves the HTML
document containing the applet (ex-when it goes to another page).

2.destroy()
-----------
The destroy() method is called when the environment determines that your
applet needs to be removed completely from memory.The stop() method is always
called before destroy().

Applet Dispaly Methods


----------------------
drawString()
------------
public void drawString(String message,int x,int y)

Used to output a string to an applet, which is a member of the Graphics


class.

setBackground()
---------------
void setBackground(Color newColor)

Used to set the background color of an applet's window.

setForeground()
---------------
void setForeground(Color newColor)

Used to set the foreground color ie, the color in which text is shown.

CONSTANTS DEFINED BY THE CLASS Color


--------------------------------

Color.black Color.megenta Color.blue


Color.orange
Color.cyan Color.pink Color.darkGray Color.red
Color.gray Color.white Color.green Color.yellow
Color.lightGray
(Default background color=lightGray foreground color=black)

Methods to obtain the current settings for the background and fore-ground
colors are

Color getBackground()
Color getForeground()

THE HTML APPLET TAG


-------------------
The APPLET tag is used to start an applet from both an HTML document and from
an appletviewer.-An applet viewer will execute each APPLET tag that it finds
in a separate window, while web browsers like NetscapeNavigator, Internat
Explorer and Hotjava will allow many applets on a single page.

Full syntax for APPLET----------------------


<APPLET
[CODEBASE=codebaseURL]
CODE=appletfile
[ALT=alternateText]
[NAME=appletInstanceName]
WIDTH=pixels HEIGHT=pixels]
[ALIGN=alignment]
[VSPACE=pixels][HSPACE=pixels]
>
[<PARAM NAME=AttributeName1 VALUE=AttributeValue>]
[<PARAM NAME=AttributeName2 VALUE=AttributeValue>]
....
[HTML Displayed in the absence of java]
</APPLET>

DOCUMENTBASE
------------
Java will allow the applet to load data from the directory that held the HTML
file that started the applet called DOCUMENTBASE.

CODE BASE
---------
The directory that the applet's class file was loaded from called CODE BASE.

These directories are returned as URL objects by getDocumentBase() and


getCodeBase().

JFC -Java Foundation Classes


introduced in jdk1.2

1.Swing
2.Pluggable look and feel
3. java2D
4. Drag & Drop
5. Accessibility

Swing - extention to AWT -GUI component

250 class & 75 interface in 10 packages

packages

1. javax.swing
2. javax.swing.event
3. javax.swing.plaf
4. javax.swing.table
5. javax.swing.text
6. javax.swing.tree
7. javax.swing.undo
8. javax.swing.plaf.basic
9. javax.swing.plaf.multi
10. javax.swing.border

Advantages

1. Wide variety of Component


All swing components starts with "J". For eg. JButton,JList,JMenu...
2. Pluggable look and feel
a.win32 App
b.Motif App
c. Mac App
All swing component by default will have metal appearance.
All awt component takes the appearance of peer(OS) objects.
But swing component will have a same appearance(metal) for all types of OS. So
the appearence won't vary from System to System

3. MVC Architecture
Model, View Controller Architecture.
View - The properties that are set to the component.
Controller - The action that can be registered with the component.
Model - The appearance of the componant such as metal,motif or windows
These three will be running in a seperate thread in Swing architecture. View &
controller are combined in the component.

4. Keystroke handling

5. Action object
- Same component can referred to same action. For eg. a toolbar object and a
menu object can referred to same action.

6. Nested Container
Except containers such as JApplet,JFrame,JDialog & JWindow all other
components are lightweight component.
Heavyweight component are component that takes the appearance of the peer
objects. Lightweight components have its won appearance.
All lightweight component are placed over heavy weight component.
All awt component are heavy weight component.
A Container will be created from the heavy weight component inorder to add the
swing component. ContentPane class is used to create the container. ContentPane -
super class - LayerPane - super class - JRootPane
All swing components can be added only on the content pane.

JInternalFrame are lightweight container.


7. Virtual Desktops
JDesktopPane and JInternalFrame

8. Component Borders

9. Customized Dialogs
messagedialogs,confirms dialogs,inputdialogs...

10. Standard Dialogs


JFileChooser
JColorChooser

11. Structured table and tree components


JTable JTree

12. Powerful text manipulation


13. Undo & Redo
14. Accessiblity - all components had implemented Accessiblity interface
Object
|
Component
|
Container
|
JComponent
-AbstractButton
- JButton
-JMenuItem
-JMenu
-JCheckBoxMenuItem
-JRadioButtonMenuItem
-JMenuBar
-JToggleButton
-JCheckBox
-JRadioButton
-JLabel
-JList
-JComboBox
-JScrollBar
-JTextComponent
- JTextField
-JPasswordField
-JTextArea
-JProgressBar
-JToolBar
-JSlider
-JSeperator
-JFileChooser
-JColorChooser
-JInternalFrame
-JDesktopPane
-JOptionPa

Object -- Component -- Container --> Panel --> Applet --> JApplet

Object
|
Component
|
Container
- Window
-JWindow
-Frame
-JFrame
-Dialog
-JDialog

Constructor:

It is a method which has the same name as the class name and is executed
automatically, when an instance for the class is created. A constructor can take
arguments.But, a constructor will not return any value.

Properties of a constructor:
1. A constructor has the same name as the class name.
2. A constructor will not return any value.
3. A constructor can be overloaded.
4. A constructor need not be explicitly called.
Types
=======

1. Default constructor.
It is the constructor that is called by default (i.e) when no other constructors are
defined in the class. It is the constructor that would be executed first.
2. Parametrized constructor.

It is the constructor that takes aruguments.


Java Networking:

Network :
A network is nothing but a connection of autonomous
computers and peripherals.Network enables the sharing of resources
and communication. Internet is a network of networks.Network in java
is possible through the use of java.net package.

Protocols
Communication in a network or a different network requires
certain set of rules called protocols.In java networking is done using
TCP/IP protocol(connection-oriented) and UDP protocol(conntion-less).
Some other protocols are,

HTTP ->Hyper text transfer protocol.(enables interaction with internet)


FTP ->FileTransferProtocol (enables transfer of files bet'n computers)
SMTP->SimpleMailTransferProtocol(provides email facility)
NNTP->NetworkNewsTransferProtocol(act as a bulletin board
for sharing news).

TCP/IP :
Tcp/ip Sockets are the most reliable ,bi-directional ,stream
protocols.The server has to wait for the client's request.The server uses the ServerSocket
class and the client uses the Socker class to connect to the server.
The getInputStream method is used to receive the input from the
port and getOutputStream method is used to send the data to the port .
Socket
Socket is a one which act as medium of transfer of data in a
network in which TCP/IP act as protocol and IPaddress forms the
address of the Socket.

Client/Server
Computer which,requests for some service from another
computer is called as client.The one that processes the request is called as server.

InternetAddress
Every computer connected to a network has a unique
IP(internet protocol) address.It is 32 bit number which has four
numbers separated by periods. A sample IPaddress is 80.0.0.54

Domain Naming Service


It is very difficult to remember the ip address. A alternate
solution to this problem is domain naming service(DNS).
For ex www.microsoft.com implies that com is the domain name server
for the US commerical sites.and microsoft the microsoft company's
server name.
-*******-
Classes in the java.net package:
InetAddress :
It is a class of the java.net package which is used to encapsulate
the ipaddress and the DNS. The methods in this class are

static InetAddress getLocalHost ->return the localhostname


and ip address
static InetAddress getByName(String hostname) ->return the
ipaddress of the passed hostname.

Datagram: -

It is a type of packet that represents an entire communication.There is no


necessity for connection or disconnection stages when communicating using datagrams.
(ie) using datagrams we can create a connection less,less reliable connections.

The classes used in datagram communication are


DatagramPacket ->act as a datacontainer.
DatagramSocket->is a class used to send and receive
DatagramPackets.

DatagramPackets
Constructors in this class are
1)DatagramPacket(byte data[],int size);
2)DatagramPacket(byte data[],int size,InetAddress i ,int port);

DatagramSocket
Constructor used in this class are(Socket exceptio must be caught)
1)DatagramSocket s=new DatagramSocket();
2)DatagramSocket s=new DatagramSocket(int port);

Methods used in send and receive are


1) send(DatagramPacket d)->dispatch the given datagram packet object.
2)receive(DatagramPacket p)->receive the given datagram packet object.
3)close()->closes the socket connection.

IOException on send and receive must be caught.


Difference between c++ an java

C++ JAVA
1. Supports the usage of pointers No pointers support.
2. uses header files uses
packages.
3. implicit type conversion No implicit type conversion
that leads to imprecision.
4. supports operator overloading No support for
operator overloading.
5. memory allocation can be memory allocation can only
static or dynamic. be dynamic.
6. hasn't got a built-in support has got a built-in suppor
for multithreading. for multithreading.
7. supports multiple interheritance. supports
interfaces.
8. platform - dependent. Platform independent.
9. supports friend funs. no support for friend fun.

Inheritance:

It is the technique by which objects of a newly created class gets or acquires


the properties of the object of an already existing class.Inheritance is the key to
reusability.

Note:

The class that exists, is known as "base class or parent class" and the class whose
object gets the properties of the "base class" is known as "derived class or child class."

Java supports three types of inheritances.

1. Single:

It is the type of inheritance where there is a single base class and a single
derived class.

2. Multilevel:

It is the type of inheritance where a derived class is created from another


derived class (i.e) there exists a derived class whose properties are got by another derived
class.

3. Hierarchical:

It is the type of inheritance where a base class has a minimum of two derived
classes (i.e) the properties of a single class are acquired by a minimum of two classes.

Interfaces:

Java does not supports mulitiple inheritance. To avoid this drawback, it supports
the concept of interfaces. An interface is an abstract collection of methods which can be
implemented by individual classes. An interface itself has no definition and should not
contain definition for the methods contained in it. A variable declared within a interface
becomes a final variable, (i.e) its value cannot be changed within the class that inherits
the interface.An interface is similar to an abstract class and no objects of an interface can
be created. But, a single class can inherit any no. of interfaces, which is not possible in
the case of an abstract class.

When a class inherits the properties of another class, the keyword "extends" is
used, when a class inherits the properties of an interface, the keyword "implements" is
used and when an interface inherits the properties of another interface, the keyword
"extends" is used.

Syntax:

<access_specifier> interface <interface_name>


{
<ret_type> <method_1>(<valid argument list>);
<ret_type> <method_2>(<valid argument list>);
<ret_type> <method_3>(<valid argument list>);
|
|
|
<ret_type> <method_n>(<valid argument list>);
<data_type> <var_1> =<value>;
<data_type> <var_2> =<value>;
.
.
.
<data_type> <var_n> =<value>;
}

where,
access_specifier, is either "public" or has the default value and
interface_name, is any valid identifier.

JDBC(Java Data Base Connectivity):

It is a java specific API that allows the users to connect to databases. The
medium for interaction is
the standard SQL(Structured Query Language). The classes and interfaces for a database
connectivity is contained in the "java.sql" package. The important classes and interfaces
of this api are,

Connection(interface)
DriverManager(class)
Statement(interface)
PreparedStatement(interface)
CallableStatement(interface)
ResultSet(interface)
Types(class)
DatabaseMetaData(interface)
ResultSetMetaData(interface)

Steps involved in a database connectivity:

1. Establishing the connection to the required database.

2. Processing a SQL statement.

3. Retrieving the results.

4. Closing the established connection.

Type 1 drivers use a bridge techology to connect a Java Client to an ODBC database
service. Sun's JdbcOdbc bridge is the most common type 1 driver.
These drivers are implemented using native code.

Type 2 drivers wrap a thin layer of Java around Database specific native code libraries.
For Oracle databases, the native code libraries might be based on the OCI(Oracle Call
Interface) libraries, which were originally designed for C/C++ programmers. Because
Type 2 drivers are implemented using native code, in some cases they have better
performance than their all_Java counterparts. However they add some risk, because a
defect in a driver's native code section can crash the entire server.

Type 3 drivers communicate via a generic network protocol to a piece of custom


middleware. The middleware component might use any type of driver to provide the
actual database access. WebLogic's Tengah product is an example of this type of driver.
The type of protocol in the middleware depends on the vendor of the database.

Type 4 drivers are the most common type of drivers used is real-time applications.
Written entirely in Java, Type 4 drivers understand database specific networking
protocols and can access the database directly without any additional software.

// Exception
/*Exceptions are errorenous events that occur during the execution of the program. They
can be ArithmeticException(occurs when a value is divided by zero etc),
NumberFormatException(occurs when a string is given as input for an interger variable),
NegativeArraySizeException(occurs when an array is creted with a negative size) etc.
In Java, the runtime exceptions can be handled using exception
handlingblocks and keywords("try","catch","throws","throw","finally"). */
Packages:

Packages are containers for java classes and interfaces in order to


compartmentalize the class name space. Using the concept of package, the user is free to
create his own java classes and interfaces and contain them within a package. Once, the
package is referenced, the user can intantiate the classes and implement the interfaces
within the package. Hence, it is possible to have two classes with the same name under
different packages.

Syntax:

package <package_name>;
class <class name>
{
body of the class
}
interface <interface name>
{
body of the interface
}

import statement:

The "import" statement is used to reference the java packages in our programs.
There are three forms of import statements,

1. import package.*; import java.io.*;


2. import package.class_name; import java.io.BufferedReader;
3. import package.interface_name; import java.awt.event.ActionListener

"classpath" environment variable:

The java compiler and the java interpretter searches for the files with ".class"
extension in the path specified in the "classpath" environment variable. The current
working directory is, by default, included to the "classpath" environment variable. Hence
it is possible to compile and execute the programs from the current directory.

Steps to create a package:

1. create a directory which has the same name as the package name.
2. include the "package" keyword as the first statement in the program along with the
package name(the name of the directory).
3. write the class declaration and implementation and save the file as class_name.java
within the directory.
4. compile using java compiler.
Overloading:

1. The signature of the methods differ.


2. Overloading is done within a particular class.
3. This is a compile time entity.

Overridding:

1. The singature of the methods should be same.


2. Overridding involves a minimum of two classes.
3. This is a run time entity.

Streams:

logical entities accessing and displaying information

File

inputstream -reads input-read()


character streams /byte streams(8 bits)
FileInputStream,FilterInputStream,BufferedInputStream,PushBackInputStream,Reader
outputstream-writes input-write()
FileOutputStream,FilterOutputStream,BufferedOutputStream,Writer,

marksupported()-True/false
mark()
reset()

File:
getName();
getPath();
getAbsolutePath()
isAbsolute();
isDirectory();
isFile();
isReadOnly()

The keyword "super" can be used for the following

1. To call an instance variable in the base class.(super.variblename)

2. To call an instance method in the base class. While an instance method is


being called, the call could be made from a construnctor or another instance
method.(super.methodname(arguments list))
3. To call a constructor. While a constructor is being called, the call should
be made from a constructor and the call cannot be from a method. The call
to a base class constructor should be the first statement in the derived
class constructor and so only a single construct of a base class can be
called from a derived class constructor.(super() or super(argument list))

Swing:
It is the major improvements in the JDK between versions 1.1 and 1.2.It is also
one of the key APIs of the Java foundations Classes(JFC).

The Swing provides a large number of useful GUI controls that originated with
Netscape's Internet Foundation classes(IFC).

Relationship between Swing,awt and JFC:


---------------------------
| jfc |
| ------------------ |
| |awt -------- | |
IFC---------- |-->| Swing| | |
| | --------- | |
------------------ |
| |
---------------------------

The swing compenents can be used interchangeably with AWT components.

The JComponenent class of javax.swing is the top level class of the swing
component hierarchy.It is a subclass of the java.awt.Container class.

Jcomponent has the following direct Subclasses:

AbstractButton:
The top-level button class.it is subclassed by JButton(traditional and enhanced
GUI buttons),JToggleButton(checkboxes and radio button) and JMenuItem(menus and
menu items).

JComboBox:
A combination of atext field and drop-down list.
JInternalFrame:
A frame that supports all standard frame operations and can be used as an internal
GUI compenent.The JDesktopIcon inner class is used to implement an iconified form of
an internal frame.
JLabel:
A label that may contain text,an image,or both.
JLayerPane:
A panel that support several layers.It is used to manage layered frames as a
desktop.
JList:
A list component that can be tailered in a variety of ways.
JMenuBar:
A menu bar that can be added to any container.It displays a pop-up menu of menu
items.

API's of the JFC:

AWT
Swing
PLAF(Plugable Look and Feel)
2d
DND -> Drag and drop support
Accesibilty

Features of swing:

1. Light weight controls(controls that no native


representation and use fewer resouces when compareed to heavy weight components(awt
controls)).
2. They are 100% java code and hence they are
platform independent.
3. Based on MVC(Model View Controller architecture).
Model - The data of the component.
View - The graphical representation of the component.
Control- The events handled by the component.
4. Platform independent look and feel.
5. Plugable look and feel.
6. Keystrokes can be mapped to components enabling mouseless operations.
7. Advances painting.
8. More no. of enhance components.

Synchronization

Bringing together, Orgainze.

synchronization - keyword used to enable synchronization among threads.Can be used


along with the methods or inside block.

monitor - It is an object used as a mutually exclusive lock.


At a time
only one thread can access the monitor. Second thread can't
enter until the first comes out.
semaphore - another such object.

InterprocessCommunication
Exchange of data or message among threads.
wait() - make the thread to wait for data.
notify() - to notify the waiting thread,
notifyAll() - to notify all the waiting threads.

SERVLET:

Servlets are small programs that execute on the server side of a web
connection.Applets dynamically extend the fuctionality of a web browser,Servlets
dynamically extend the functionality of a web server.
Java Servlet Development Kit(JSDK): It contains the class libraries that you will
need to create servlets.A utility known as the servletrunner is also included,which enables
you to test some servlets that is created.

Common Gateway Interface(CGI):

It allows seperate process to read data from the HTTP request and write data to
the HTTP response.A variety of different languages were used to build the programming
for CGI,including C,C++ and PERL(Practical Extraction
Reporting Language).

Servlets offer several advantanges over CGI:

* Performance is significantly better.


Servlets execute within the address space of a web server.Creating a
separate process to handle each client request is not necessary.Hence the resources of the
server in considerably saved.
* Servelts are platform independent,because they are written in JAVA.
* The full functionality of the java class libraries is available to a servlet.It can
communicate with applets, databases,or other software via sockets and RMI mechanism.

The life cycle of servlet:

The three methods are central of a servlet,


* init():
** This method is invoked only when the servlet is first loaded into the
memory.The initialization parameters can be passed to the servlet so that it may configure
itself.It is called only once during the entire life-time of the servlet.
* service():
** Which is called to process the request and may also formulate a
response for the client.
* destroy():
**If the server decides to unload the servlet from its memory, it calls
the destroy method to relinguish any resources,such as file handles that are allocated to
the servlet.Any important data may saved to a persistant store.
They are implemented by every servlet and are invoked at specific times by the
server.

This is the life-cycle of a GenericServlet. When, the servlet happens to be a HttpServlet,


it overrides the doGet() or doPost() instead of the service() method.

The javax.servlet packages:

Interfaces:

Servlet--->It declares the life cycle methods for a servlet.


ServeltConfig--->allows servlet to get initilization parameters.
ServletContext--->Enables to servelt log event and access information about
their environment.
ServeltRequest--->It is used to read data from client request.
ServletResponse--->It is used to write data to a client response.
Class:
* GenericServlet--->It configures the Servlet and ServletConfig interfaces.
* ServletInputStream--->It provides an input stream for reading requests from a
client.
* ServletOutputStream--->It provides an output stream for writing responses to a
client.
* ServletException---> Indicates that a servlet error occured.
* UnavailableException--->Indicates that a servlet is permanently or temporarily
unavailable.
*HttpServlet ---> Indicates that the servlet supports
http protocol.

//steps

set classpath=%classpath%;c:\javawebserver2.0\lib\servlet.jar

javac filename.java

copy filename.class c:\javawebserver2.0\servlets

copy filename.html c:\javawebserver2.0\public_html

url:

http://localhost:8080/servlet/filename -- servlet

http://localhost:8080/filename.html -- html file


RMI:

RemoteMethodInvocation(RMI) is a part of JDK. It allows as to develop


distributed applications. Distributed systems require computations that are running in
different address spaces, practically on different machines, must be able to communicate
between one machine to another. Java RMI facilitates such a communication specifically
for java applications. The RMI is platform independent because Java is platform
independent. The RMI can communicate only from one JVM to another. So, the user
need not learn any other language to develop the distributed application by using RMI.

In RMI the application is divided into objects. The objects communicate with each other
through an interface. This interface is used to access the remote object and its methods.
RMI passes objects by their true type, as a result the behaviour of those objects is not
changed when they are sent to another virtual machine. To develop the distribted
application using RMI we have to follow the steps given below,

1. Define the interfaces.


2. Implement these interfaces.
3. Compile the interfaces and their implementations with the java compiler.
4. Compiler the server implementation with rmi compiler.
5. Create and compile the server and client applications using java compiler.
6. Run the RMI Registry.
7. Run the application.

RMI architecture consists of four layers;

1. Application Layer:

The application layer is the actual implementation of the client and


server applications. Here, the high level calls are made in order to access and export
remote objects. The client can acces the remote method through an interface that extends
java.rmi.Remote. When we want to define a set of methods that will be remotely called,
they must be declared in one or more interfaces that should extends java.rmi.Remote.

2. Proxy Layer:

The stub and skeleton file created using the RMI compiler which
represent the client and server side of a remote object, froms the proxy layer.The stub
acts on the client side of the application and the skel acts on the
server side of the application. The main function of proxy layer is marshaling and
unmarshaling the parameters.
Process of converting input parameters to the a format that can be transmitted
across the network is called marshaling.

A reverse process of marshaling in which the data is converted from a format


portable across the network to the format used by the methods is called as unmarshaling.

Stub:

The stub is client side proxy of the remote object. It has three primary
responsibilities,

1. It presents the same remote interfaces as the object of the server


application. Therefore, from the perspective of the client application,
the stub is equivalent to the remote object.

2. It works with JVM and RMI system on client machine to serialize any
arguments to a remote method call and sends this information to server machine.

3. The stub receives any result from the remote method and returns it to
the client.

Skeleton:

The skeleton is a server side proxy of the remote object. It has thre
primary responsibilities,

1. It receives the remote method call and any associated arguments. It


works with the JVM and RMI system on the server machine to deserialize any arguments
for this remote method call.

2. It invokes the appropriate method in the server object using these


arguments.

3. It receives any return value from this method call and works with the
JVM and RMI system on server machine to serialize this return
value and sends the information back to the client.

3. Remote Reference Layer:

The remote reference layer is effectively between proxy


layer(stub and skel) and the transport layer, which handles the actual communication
protocols. When transmitting the parameter or objects through the network is should be in
the form of a stream. The JVM works with the java byte codes. It can get the stream-
oriented data from the transport layer and give it to the proxy layer and wise versa.
This layer is used to,

1. Handle the replicated objects. Once this featue is incorporated into


the RMI system, the replicated objects will allow simple dispatch to many programs that
are exporting substantially the same remote objects.

2. It is responsible for establishing persistence and strategies for


recovery of lost connections.

4. Transport Layer:

1. It is reponsible for handling the actual machine to machine


communication, the default communication will take place through a standarad TCP/IP.

2. It creates a stream that is accessed by the remote reference layer to


send and receive data to and from other machines.

3. It sets up the connection to remote machines.

4. It manages the connection.

5. It monitors the connections to make sure that they(remote machines)


are live.

6. It listens for connections from other machines.

RMI registry:

RMI registry is a simple server that enables an application to lookup objects


that are exported for remote method invocation. It is also called as BOOTSTRAP
REGISTRY. The registry simply keeps track of the address of remote objects that are
being exported by their application. In any distributed system all the objects are assigned
unique names that are used to identify the object.

javac <remote_interface_name>.java
javac <implementation of remote interface>.java
rmic <implementation of remote interface>
javac <client application>.java
javac <server application>.java

start rmiregistry(started in the server machine)

java <server application>


java <client application>
The Java Bean:

A java bean is a software compenent that has been designed to be reusable in a


variety of different environments.There is no restriction on the capability of a bean.

Advantages Of java beans:


* A bean obtain all the benefits of java's "write-once,run-anywhere" paradigm.
* The properties,events, and methods of a bean that are exposed to an
application builder tool can be controlled.
* A bean may be designed to operate correctly in different locales,which makes
it useful in global markets.
* The configuration settings of a bean can be saved in persistent storage and
stored at a later time.
* A bean may register to receive events from other objects and can generate
events that are sent to other objects.
Application Builder tools:
* A palette is provided that lispts all of the available beans.
* A worksheet is displayed that allows the designer to lay out beans in a
graphical user interface.
* special editors and customizers allows a bean to be configured.
* Commands allow a designer to inquire about the state and behaviour of a
bean.The information automatically becomes available when a bean is added to
the pallete.
The Bean Developer Kit:
It is a simple example of a tool that enables you to create,configure, and
connect a set of beans.
The JAR(Java Archive)files:
The BDK expect beans to be packaged within JAR files.A JAR files allows you to
efficiently deploy a set of classes an their associated resources.
The JAR utility:
A utility is used to generate a JAR files.Its syntax is,
jar options files
where options are,

c --->A new archive is to be created.


C --->Change directories during command execution.
f --->The first element in the file list is the name of the archive that is to be
created or accessed.
m --->The second element in the first file list is the name of the external
manifest file.
M --->Manifest file not created.
t --->The archive contents should be tabulated.
u --->Update existing JAR file.
0 --->Do not use compression.
v --->Verbose output
For ex:
Tabulating the contents of a JAR files:
jar tf xyz.jar
Create a new bean:
* Create the java source files.
* Compile source files.
* Create a manifest file.
* Generate a JAR file.
* Start the BDK.
* Test
The manifest files contains:
Name: sunw/demo/colors/colors.class
Java-Bean: True
Generate a JAR files:
jar cfm ..\jars\colors.jar colors.mft sunw\demo\colors\*.class
Start the BDK:
Change to the directory c:\bdk\beanbox and type run.

You might also like