Web Technology Unit 4
Web Technology Unit 4
UNIT-IV
Streaming – Networking Principles method invocation – Sockets for Clients - Sockets for Servers –
Protocols handlers – Content handlers – Multicast sockets – Remote.
4. 1. Streams:
Input is data going into a program; output is data flowing out of a program. I/O is frequently done
using I/O streams.
A stream is a sequence of data flowing from a source to a destination. I/O streams can be connected
to a wide variety of data sources and destinations.
The core Java language does not have any I/O methods. For a program to do I/O, it must import an
I/O package called java.io.
Data for a program may come from several sources .Data created by a program may be sent to
several destinations.
The correspondence between a program and a data source or destination is called a stream. An
input stream handles data flowing into a program. An output stream handles data flowing out of a
program
Data Source
Data Destination
A processing stream operates on the data supplied by another stream.Often a processing stream
acts as a buffer for the data coming from another streams.
For examples, disk file data usually is delivered by the operating system in block of 512 bytes at a
time. Usually this data is buffered and delivered to a program in more suitable sizes. In the
following , the keyboard sends data to the Input stream system.in,which is connected to a
BufferedReader stream. system.in is a stream object that the Java system automatically creates
when the program starts running
BufferedReaderstdin=newBufferedReader(newInputstreamReader(system.in));
Java Program
Stdin system.in
The data is transformed along the way. The raw bytes from the keyboard are grouped together into a string
object that the program reads using stdin.readsLine() .
Types of streams:
Types of Streams
Streams are byte-oriented or character-oriented. Each type has input streams and output streams.
Character-oriented streams:
Specialized for character data.
Transforms data from/to 16-bit Java char used inside programs to UTF format
used externally.
Inputstream is an abstract class from which all byte-oriented input streams are derived.
Its descendant classes are used for general-purpose input (non-character input).
These streams are aimed at delivering data to a program in groups of 8-bit bytes .
The bytes can be grouped into the size necessary for the type of data.
For examples, if a disk file contains 32-bit int data, data can be delivered to the program
in 4-byte group in the format as Java primitive type int. For different input streams is given as
below.
Input Stream
InputStreams defines the following methods for reading bytes and arrays of bytes:
A ByteArrayInput Stream reads data from an array of bytes. For instances the following code
shows how to use the FileInput Stream.
Import java.io.*
Int c;
System.out.println( c);
In.close()
OutputStreams:
Outputstream is an abstract class from which all byte-oriented output streams are derived. Its
descendant classes are used for general purpose (non-character output). These streams are aimed at writing
groups of 8-bit byte to output destinations. Byte are in the same format as Java primitive types. For example,
4-Byte groups corresponding to type int can be written to a disk file. For different output streams is shown as
below.
outputStrea
m
ByteArrayoutpu
fileoutputstream
tstream
pipeoutputstrea
mm
filteroutputstrea
m objectoutputstream
bufferedoutputstrea
dataoutputstream printstrea
mam
m
Outputstreams
OutputStreams defines the same methods but for byte as mentioned below :
int c;
out.write(C);
in.close ( );
out.close ( );
Filter Streams:
The java .io packages provides a set of classes that defines and partially implement filter streams .
The read method in a readable filter stream reads input from the underlying stream,filter it, and
passes on the filtered data to the caller .
The write method in a writable filter stream filters the data and then writes it to theUnderlying
stream. The filtering done by the filter streams depends on the stream .
Some streams buffer the data,some count data as it goes by, and others convert data to another form
.
The filters come in two forms the filter streams and the readers and writes .
Most filter streams provided by the java.io packages are subclasses of FilterInputStream and
FilterOutputStream and are listed here :
To use a filter input or output stream,attach the filter stream to anoyher input or output stream when it is
created. For example, a filter stream can be attached to the standard input stream, as in the following code.
String input ;
....//do somthing
The reading and writing can be done with respect to the last stream in the chain.
Buffered streams
.....
BufferedOutputStreams will cache output and not perform an actual write ( ) until the buffer is full. The buffer
can be clearedby calling flush ( ).
Readers and Writer deal with character streams .These are abstract classes . A program must
use classes derived from them . For example, a BufferedReader is a Reader.
Character streams are optimized for handling character data. They also translate between the internal
format used by Java program and external format used for text files. Inside a Java program character data is
represented with the 16-bit char data type. The character of a string use the same 16- bit code. On a disk
file,character are represented in a format called UTF. This format uses one, two or three bytes per character
and is intended to be a universal format one format for all text files in any language anywhere in the world .
Writer:
Writer is an abstract class from which all character-oriented output streams are derived. All these
streams are aimed at receving 16- bit char data from a program, and sending it to another destination, which
may use a different character format (such a UTF format on a disk file ).
All these classes are character-oriented output stream. The different writer classes are given as below
Writer(abstrac
t)
charArraywriter
pipewriter
stringwriter
Filterwriter
(abstract)
bufferedwriter
Outputstrem
writer printwriter
writer
Filewriter
Reader:
Reader is an abstract class from which all character-oriented input streams are derived. These streams
are aimed at delivering 16-bit char data to a program although the source of the data may be in a different
formay(such as UTF format on a disk file).
reader
charArrayreade pipereader
r stringreader
Filterreader(abr
act
bufferedreader inputstreamReade
r
int read ( )
writer defines these methods for writing characters and array of characters:
Int write(int c)
Data streams:
The data input stream and data output stream classes provide methods for reading and writn java’s
primitive data types and strings in a binary format. The binary formats are used to exchange data between
two programs or networks or pipes. The data output stream class offers the following methods:
All data is written in big-endian format and in two’s complement form. Datainputstream offers 9 classes along
with normal read(),available() and close() method.
Object streams:
ObjectInputStream and ObjectOutputStream are wrapper classes that can be wrapped around
arbitrary inputstreams and output streams.
This makes it possible to do object input and output on any byte-stream. The methods for object I/O
are readobject(), in objectinputstream and writeobject(object obj),in objectoutputstream.
Both of these methods can throw IOExceptions. Note that readobject() returns a value of type object,
which generally has to be typedcaasst to a more useful type.
Objectinputstream and objectoutputstream only work with objects that implement an interface named
serializable. Furthermore, all of the instances variables in the object must be serializable.
However, there is little work involved in making an object serializable interface does not declare any
methods.
It exists only as a marker for the complier to tell it that the object is meant to be writable and
readable. Many of java’’s standard classes are already declared to be serializable,including all the
component classes in swing and in the AWT(abstract window toolkit). This means,in particular,that
GUI(graphical user interface) components can be written to objectoutputstreams and read fraom
object inputstreams.
Network
A network is a collection of computers and other devices that can send data to and receive data from each
other, more or less in real time. A network is normally connected by wires, and the bits of data are turned into
electromagnetic waves thatmove through the wires.
Node
Each machine on a network is called a node. Every network node has an address: a series of bytes that
uniquely identify it
Host
Host refers to a networked general purpose machine rather than a single purpose device.
Protocol
A protocol is a set of rules defining how computers communicate how address work, how data is split into
packets etc.
The host-to-network layer defines how a particular network interface, such as an Ethernet card or a PPP
connection, sends IP datagrams over its physical connection to the local network and the world.
A network layer protocol defines how bits and bytes of data are organized into larger groups called
packets, and the addressing scheme by which different machines find each other.
Data is sent across the internet layer in packets called datagrams. Each IP datagram contains a header
from 20 to 60 bytes long and a payload that contains up to 65,515 bytes of data. (In practice most IP datagrams
are much smaller, ranging from a few dozen bytes to a little more than eight kilobytes.)
Always 0100 (decimal 4) for current IP; will be changed to 0110 (decimal 6)
for IPv6, but the entire header format will also change in IPv6.
An unsigned integer between and 15 specifying the number of 4-byte words in the header; since the
maximum value of the header length field is 1111 (decimal 15), an IP header can be at most 60 bytes long.
A 3-bit precedence field that is no longer used, 4 type-of-service bits (minimize delay, maximize
throughput, maximize reliability, minimize monetary cost), and a bit. Not all service types are compatible. Many
computers and routers simply ignore these bits.
An unsigned integer specifying the length of the entire datagram, including both header and payload.
A unique identifier for each datagram sent by a host; allows duplicate datagrams to be detected and
thrown away.
3-bit flags
The first bit is 0; second bit is if this datagram may be fragmented, 1 if it may not be; third bit is if this is
the last fragment of the datagram, 1 if there are more fragments.
In the event that the original IP datagram is fragmented into multiple pieces, itidentifies the position of this
fragment in the original datagram.
Number of nodes through which the datagram can pass before being discarded; used to avoid infinite
loops.
1-byte protocol
Six for TCP, 17 for UDP, or a different number between and 255 for each of more than one hundred
different protocols (some quite obscure);
A checksum of the header only (not the entire datagram) calculated using a 16-bit one's complement sum.
Java does not support. Consequently, we will not discuss these here. The interested
reader is referred to TCP/IP Illustrated, Volume 1, by W. Richard Stevens for more details on these
fields.
The transport layer is responsible for ensuring that packets are received in the order they were sent and
making sure that no data is lost or corrupted.
If a packet is lost, then the transport layer can ask the sender to retransmit the packet. There are two
primary protocols at this level.
The first, the Transmission Control Protocol (TCP), is a high-overhead protocol that allows for
retransmission of lost or corrupted data and delivery of bytes in the order they were sent. The second
protocol, the User Datagram Protocol (UDP).
The layer that delivers data to the user is called the application layer.
The three lower layers all work together to define how data is transferred from one computer to another.
The application layer decides what to do with that data after it's transferred.
Every computer on an IP network is identified by a 4-byte number. This is normally written in a format like
199.1.32.90, where each of the four numbers is one unsigned byte ranging in value from to 255.
Ports
Each computer with an IP address has several thousand logical ports (65,535 per transport layer protocol,
to be precise).
The Internet
Internet addresses are assigned to different organizations by the Internet Assigned Numbers Authority
(IANA),[1] generally acting through intermediaries called ISPs
Firewalls
The hardware and software that sits between the Internet and the local network, checking all the data that
comes in or out to make sure it's kosher, is called a firewall.
The most basic firewall is a packet filter that inspects each packet coming into or out of a network and
uses a set of rules to determine whether that traffic is allowed.Filtering is usually based on network
addresses and ports.
Proxy Servers
Proxy servers are related to firewalls. If a firewall prevents hosts on a network from making direct
connections to the outside world, a proxy server can act as a go-between.
4.2.2Client/Server Networking
A server process is allowed to listen to a port until a client connects to it. A server accepts many
clients at the same port, although each session is unique.
4.3. SOCKETS:
TCP provides a reliable, point to point communication channel that client-server application on the internet
use to communicate with each other.
To communicate over TCP, a client program and a server program establish connection with each another.
Each program binds a socket to the end of the connection.
To communicate, the client and the server each reads from and writes to the socket bound to the
connection.
A socket is one end-point of a two way communication link between two programs running on the network.
Socket classes are used to represent the connection between a client program and a server program.
The java.net package provides two classes-sockets and server socket-that implements the client side as
well as the sever side of the connection, respectively.
There are two basic types of network sockets on IP networks-those that use the transmission control
protocol(TCP) and those that use the user datagram protocol(UDP).TCP is a reliable protocol in which data
packets are guaranteed to be delivered in the order. If a packet expected at the receiving end of a TCP socket
does not arrive in the set period of time, then it is assumed lost, and the packet requested from the sender
again. The receiver does not move on the next packet until the first is received.UDP,on the other hand,makes
no guarantees about delivery of packets, or the order in which packets are delivered. The sender transmits a
UDP packet,and it either reaches the receiver or it does not.
The socket class is used for creating TCP connections over an IP network. A socket is typically created
using an Inetaddress to specify the remote host, and a port number to which the host can connect. A process
on the remote host must be listening on that port number for incoming connection requests.
The InetAddress provides to access host names and IP addresses. The following methods are provided to
create InetAddress objects.
Static InetAddress getLocalhost() throws unknownhostexception this method returns an InetAddress object for
the local machine.
Static InetAddress getbyname (string host) throws unknownhostexception
This method returns an Inet address object for the specified host name. the host name can be either
pneumonic identifier such as www.javaregime.com IP address such as 121.1.28.60.This is the only method that
can be used by a client to get remote host’s details.
The following methods are provided to extract information from an InetAddress object.
Byte[ ] getAddress( )
o This method returns an array of byte corresponding to the IPAddress held in the InetAddress object.
The array is in network byte order,i.e. high byte (back to front ) and must be converted to astring
before being displayed to the screen.
String getHostName( )
o This method returns the host name held in the InetAddress object. If the host name is not already
known, an attempt is made to look it up, if this fails, the address is returned as a string.
try {
{ }
A socket is a Java representation of a TCP network connection in the client side. The function of the client
socket are to
o This creates a socket and connects to the specified port of the host address.
o The following methods allow the remote host address and local or remote port numbers to be
identified. There methods also allow for the creation of input and output streams.
The code below creates a socket to the remote host on the specified port (6005, in this case ):
InputStream in = s.getInputStream( );
ServerSocket :
Serversocket ( int port,int count ) throws IOException- This construct a serversocket that listens on the
specified port,argument 1,of the local machine. Argument 1 is mandatory and must be supplied. But
arguments 2, the outstanding connection requests parameter , may be omitted or the default of 50 is used. If
the count option is used, it specifies the number of outstanding requests that should be queued by the
operatin system before discarding. This option is useful if the server is slow in accepting requests .
The following are the methods that allow accepting the connection when the serversocket is listening and
information about the server socket is to be obtained.
Socket accept ( ) throws IOException – This method blocks until a client makes a connection to the port on
which the serverSocket is listening .A socket is returned corresponding to the TCP connection from the client.
Void close ( ) throws IOException – This method closes the serversocket. It does not close any of the currently
accepted connections,it only stops additional connections being made by clients.
Int getLocalPort( ) –Returns the integer value of the port on which serversocket is listening.This is useful if the
server specifies port number 0,which means that the operating system assigns the next unused port.
System.out.println (“Waiting”);
ClientSocket .getInetAddress ( ) );
Server .close ( );
Datagram socket :
o The UDP socket connectins are created and used through the Datagramsocket and Datagrampacket
classes.
o A Datagramsocket sends and receives data using UDP packets , represented as datagrampacket
objects
o Before two computer can talk to each other over a UDP connection,they both have to have a
Datagramsocket connected to a port on their local machines. This is done by simply creating a
datagramsocket object , For example ,
In this example , a UDP socket is connected to a specific port (6050) on the localhost. We can construct
the Datagramsocket without specifying the port also. An unused port on the local host is usually used. The port
number can be found by using the getLocalport method.
Data is sent over a Datagramsocket using Datagrampacket objects . Each Dtagrampacket contains a
data buffer , the address of the remote host to send the data to, and the port number that the remote
computer is listening to. Therefore , to send a buffer of data to a process listening to port 6050 on host
my .host . com, the code given below is added.
The remote process can receive the data in the form of a Datagrampacket by calling the receive( )
method on its Datagramsocket . The received Datagrampacket will have the host address and port number of
the sender filled in as a side-effect of the call.
A simple example:
Here is an example program that repeatedly waits until it is contacted on its server socket.when it is
finally contacted,it starts up a new thread that outputs the first 100 fibonacci numbers.
Import java.net.*;
Import java.io.*;
Import java.lang.*;
Try
While(true)
Socket inSoc=sSoc.accept();
FibT.start();
Catch(Exception e)
System.out.println(e.toString());
}}}
Socket threadsoc1;
Int F1=1;
Int F2=1;
treadSoc1=inSoc;
Try
For(int i=0;i<100;i++)
Int temp;
Temp=F1;
FibOut.println(F1);
F1=F2;
F2=temp+F2;
Catch(Exception e)
System.out.println(e.toString());
Try
threadSoc1.close();
Catch(Exception e)
System.out.println(e.tostring());
}}}
Import java.net.*;
Import java.io.*;
Socket appSoc;
BufferReader in;
String msg;
Try{
for(int I =0;i<100;i++0
Msg=in.readLine();
System.out.println(msg);
}}
Catch(Exception e)
System.out.println(e.tostring());
}}
Multicast Sockets:
o A site that multicasts information is similar in many ways to a television or radio station
that broadcasts its signal.
o The signal originates from one sources , but it can reach everyone in the station’s signal
area .Broadcasting is generally suited to any application that requires a number of
machines in a distributed group to receive the same data; for example,
conferencing,group mail and news distribution , and network management .
o Most of the high- level network protocols only provide a unicast transmission service. That
is , nodes of the network only have the ability to send to one node at a time .
o All transmission with a unicast service is inherently point-to-point. If a node wants to send
the same information to many desyination using unicast transport services , it must
perform a replicated unicast, and send N copies of the data to each destination.
o A better way to transmit data from one source to many destination is to provide a multicast
transport service .
o With a multicast transport service , a single node can send data to many destinations by
making just a single call on the transport service.In a nutshell, multicasting is a datagram
based service to send messages to multiple clients .
Whenever a multicast message is sent out, a multicast group ID specifies the destination
group. These group ID’s are essentially sets of IP addresses called class D.
Therefore, if a host wants to receive a multicast message sent to a particular group, it needs
to listen to all messages sent to that particular group.
There are three types of IPV4 addresses unicast, broadcast, and multicast. Unicast addresses
are used for transmitting message to single destination nodes.
Broadcast addresses are used when a message is supposed to be transmitted to all nodes in
a subnetwork.
For delivering a message to a group of destination nodes which are not necessarily in the
same subnetwork, multicast addresses after used.
Classes A, B and c IP addresses are used for unicast messages, whereas class D IP addresses those in the
range 221.0.0.1 to 239.255.255.255 inclusive are used for multicast messages.
In java multicasting can be done using the java.net.MulticastSocket class. This is a subclass of
java.net.Datagransocket. This kind of socket is used on the client side to listen for packets that the server
broadcasts to multiple clients. The multicast datagram socket clas is useful for sending and receiving IP
multicast packets. Thus, java.net.MulticastSocket and java.net.DatagramPAcket are used together to
implement multicasting in java.
A mulitcastSocket is a UDP DatagramSocket, with additional capabilities for joining groups of other
multicast hosts on the Internet. One would join multicast group by first creating a Multicastsocket, with a
desired port, then invoking the joinGroup method. One can leave a group by using the method leaveGroup.
The following are the two constructors to create the multicast sockets
There are methods other than the joingroup (Addr) and leaveGroup(addr). The class also provides
functions, that set and get the time to live for DatagramPackets sent to a MulticastGroup, which specifies in
how many “hops” DatagramPackets sent to a mulitcastGroup, which specifies in how many “hops” are needed
for the packet to be forwarded on the network for itexpires. They are seTTl(ttl) and getTTl(ttl). The parameter
ttl is an unsigned 8 bit value.
A SIMPLE EXAMPLE
The following source code is a simple example that sends date and time to its multiple clients.
SERVER PROGRAM:
Import java.net.*;
Import java.io.*;
Import java.util.*;
Public class MulitcastServer
{
Public static final int PORT=2001;
Public static void main(string args[]) throws Exception
{
MulticastSocket socket;
DatagramPacket packet;
InetAddress address;
Address=InetAddress.getByName();
Socket=new MulticastSocket();
Socket.joinGroup{address};
Byte[] data=null;
for {; ;}
{
Thread.sleep(1000):
String str={ new Date().toString();
Data=str.getBytes();
Packet=new DatagramPAcket();
(data,str.length(), address,Port);
Socket.send(Packet);
}
}
}
CLIENT PROGRAM:
Import java.net.*;
Import java.io.*;
Public class MulitcastClient
{
Public static final int PORT=2001;
Public static void main(String args[]) throws Exception{
MulticastSocket socket;
DatagramPacket packet;
InetAddress address;
Address = InetAddress.getByName(args[0]);
Socket=new MulticastSocket(Broadcastserver.PORT);
Socket.joinGroup(address);
Byte[]=data=null;
Packet=new DatagramPacket(data,data.length);
For(;;)
{
Socket.receive(packet);
String str=new String(packet.getData());
System.out.println(“time signal received from”+packet.getAddress()+”time is :”+Str):
}
}
}
The RMI architecture is based on one important principle that definition of behavior and the
implementation of that behavior and the code that implements the behavior to remain separate and
to run on separate JVMs.
Specifically, in RMI the definition of a remote service is coded using a Java Interface. The
implementation of the remote service is coded in a class. Therefore the key to understanding RMI is
to remember that interfaces define behavior and classes define implementation. The following
diagram illustrates this separation.
The RMI implementation is essentially built from three abstraction layers. The first layer is the Stub
and skelton layer, which lies just beneath the view of the developer. This layer intercepts method
calls to a remote RMI service.
The next layer is the Remote Reference Layer. This layer understands how to interpret and manage
references made from clients to the remote service objects. In JDK 1.1, this layer connects clients to
remote service objects that are running and exported on a server. The connection is a one to one
link. In the java 2 SDK, this layer was enhanced to support the activation of remote service objects
via Remote Object Activation.
The transport layer is based on TCP/IP connections between machines in a newtwork. It provides
basic connectivity, as well as some firwall penetration strategies.
USING RMI:
There are three processes that participate in supporting remote method invocation
There are two kinds of classes that can be used in java RMI
1. A remote class is one whose instances can be used remotely. An object of such a class can be references in
two different ways:
Within the address space where the object was constructed the object is an ordinary object
which can be used like any other object.
2. A serializable class is one whose instances can be copied from one address space to another. An instance of a
serializable object is one that can be marhalled.
A remote class has two parts: the interface and the class itself. The remote interface must have the following
properties:
A SIMPLE EXAMPLE:
1. INTERFACE
The first step is to write and compile the java code for the service interface. The calculator interfaces defines
all of the remote features offered by the service.
2. IMPLEMENTATION
This is the calculatorImpl class:
Public class CalculatorImp1 extends java.rmi.server.unicast
RemoteObject
Implements Calculator{
Public CalculatorImpl1()
Throws java.rmi.RemoteException{
Super();
}
Public long add(long a,long b)
Throws java.rmi.RemoteException{
Return a+b;
}
Public long sub(long a,long b)
Throws java.rmi.RemoteException{
Return a-b;
}
Public long mul(long a,long b)
Throws java.rmi.RemoteException{
Return a *b;
}
Public long div(long a,long b)
Throws java.rmi.RemoteException{
Return a/b;
}}
All of the Remote interface and classes should be compiled using javac. Once this has been completed,
the stubs and skeletons for the remote interfaces should compiled bu using the rmic stub compiler. The stub
and skeleton of the example Remote interface are compiled with the following command:
Rmic CalculatorImpl
3. Client side
A remote method invocation can return a remote object as its return value, but a remote object must be
defined in order to perform a remote methodinvocation. The name of a remote object includes the following
information.
The internet name of the machine that is running the object registry with which the remote object is being
registered.
The port to which the object registry is listening.
Example
Import java.rmi.Naming;
Import java.rmi.RemoteException;
Import java.net.MalformedURLException;
Import java.rmi.NotBoundException;
Try
{Calculator c=(Calculator)
Naming.looup(
“rmi://localhost/CalculatorService”);
System.out.println(c.sub(4,3));
System.out.println(c.add(4,5));
System.out.println(c.sub(3,6));
System.out.println(c.sub(9,3));
Catch(MalformedURLException murle)
System.out.println();
System.out.println(“MalformedURLException”);
System.out.println(murle);
Catch(RemoteException re)
{System.out.println();
System.out.println(“RemoteException”);
System.out.println(re);
Catch(NotBoundException nbe)
{System.out.println();
System.out.println(“NotBoundException”);
System.out.println(nbe);
Catch(java.lang.ArithmeticException ae)
{System.out.println();
System.out.println(“java.lang.ArithmeticException”);
System.out.println(ae);
}}}
4.server side
The server program should register at least one remote object with the object registry. The statement for the
is Naming.rebind{ objectName,object);
Import java.rmi.Naming;
Public CalculatorServer()
Try
Naming.rebind(“rmi://localhost:6060/calculatorService”,c);
Catch(Exception e)
System.out.println(“trouble:”+e);
New CalculatorServer();
Before starting the server, start the object registry, using the command
Rmiregistry &
The server will take a few seconds to start running and to construct and register remote object. The
client is run like any other object.th example client is executed using
Protocol handler
Most popular web browser support protocol other than HTTP .these other protocols include
FTP ,gopher ,email and application specification protocols .support for these protocols are built
into browser to became larger and slower to load
Java support additional protocol through the use of protocol handle referred to us the stream
handler .these protocol handler are used to retrieve web objects using application specific
protocol. The protocol are specified in the URL referring the objects
Protocol handlers are implemented as subclasses of thr URLS team handler class. The
URLStreamhandler classs defines four accessmethod that can be overridden by its subclasses,but
only the openconnection() method is required to be overridden
The openconnection() method tokes a URL with its assigned protocol as a parameter and return an object of
class URLconnection .the URLconnection object can be used to create input and output streams and to access
the resource addressed by the URL
The parseURL() and set URL() method are used to implement custom URL syntax parsing.the to
ExternalForm() method is used to convert the URL of the protocol type to a string object
The purpose of a protocol handler is used to implement a customer protocol needed to access
web object identified URLs that requires the custom protocol. Protocol handlers, are not directly
installatatiated are accessed . the method of the URLconnections object that’s is returned by a
protocol handler are invoked to access the resource referenced by the protocol
A protocol is indentified beginning with the first character of the URL and continuing to the first
colon (:) contain the URL .for example the protocol of the URL http://www.myportal.com/ is http
and the protocol of the URLmyprotocol//myweb.com is my protocol
The first step to implement a protocol handler is to defined the protocol handler as sub class of
the URLstreamhandler class .the openconnection method of the protocol handler creates an URL
connection object that can be used to acess an URL designating the specified protocol
A protocol handler is associated with a specific protocol type through the use of a
URLStreamHandlerFactory object.the create URLstreamHandlerFactory interface is used to
return a protocol handler for a specific protocol type
The set URLStreamHandlerFactory() method of the URL class is used to set an URLStreamFactory
as the default URLStreamhandlerfactory as the defaultURLStreamhandlerfactory to be used all
protocol types
Following is an example of implementing a simple protocol handler. In the example there is a CGI
program ,named myprotocol, that’s returns a cookie type message when the URL of the program
is access this section defines the myprotocol to access the myprotocol program on the web server
the protocol is a not a real internet protocol;
It is an example to illustrate the use of protocol handlers .the URL for the example is protocol
consisting of myprotcol:// followed by hostname.for example, myprotocol://myportal.com access
the illustrate protocol on the web server
import java.net.*;
import java.io.*;
IOException
String host=url.gethost();
Return newURL.openconntection();
}}
The URLillustraehandler class extends the URLstream handler class and provide a single method that is
the openconnection() method which takes a URL object as a parameter and returns an object of the URL
connection the class.it also throw the IOException
The openconnectio() method uses gethost() method of the URL class to extact the host name conatinig the
URL . it then ,uss the http URL by contain http ://with the host name and then the location of th my protocol
CGI program, /CGI-bin/myprotocl .the openconnection() method of the URL class is used too return the
URLconnection object associated with new URL
The URLillustredhandler class wraps the myprotocol CGI program using the myprotocol protocol .thirds
protocol is implemented through an HTTP connection to CGI program
The getapplication program illustrate the use of protocolhandler . it access the myprotocol program on the web
server using the example protocol
Import java.net.*;
Import java.io.*;
Try{
URL.setURLStreamhandlerfactory(illustratefactory);
System.out.println(“fetching URL:”+args[0]);
System.out.println((string) url.getcontent());
}catch(malformedURLexception ex)
Error(“bad URL”);
}catch(IOException ex)
Error(“IOException occurred.”);
System.out.println(s );
System.exit(1);
Public illustratefactory()
If(protocol.equals(“myporotocol))
System.out.println(“requeted protocol:”+protocol);
Return null;
}}
4.7.CONTENT HANDLERS
A web browser encounters the number of external programs are plug in that are used to
supplement the capabilities provide by the browser. These external programs are used to display
and process file that sure not normally supported by the browser
Java support additional internal of external program to the cntent handler mechanism .conthen
handler are used to retrieve object via a URL connection object
Content handler are implemented as subclass of the contenthandler class .a content handler is
only required a to implement the single method the getcontent() method that override the
method provided by the contend handler class this method takes an URLconnection object as a
parameter an d returns an object of an specific MIME ( multipurpose internet mail extension) type
The purpose of ta contenthandler is to extract an object of a given MIME type from the input
stream of a URLconnection object.content handlerare not directly instated or accessed. The
getcontent() method of th URL and URLconnection classes cause handler to be created to
invoked to perform their processing
The first step to implementing the content handler idsto define the class of the object to
extracted the content handler. The contend handler is the define as subclass of the contenhandler
class .the getconten() method of the content handler perform the extraction of the object of a
specific MIME type from the input stream associated with the URL connection object
A content handler is associate dwith the MIME type the through use of the contenthandlerfactory
object .the create contenthandler() method of the contenthandlerfactory interface is used to
return a content handler for a specific MIME type
An example of implementing a simple content handler is explained below an example MIME type
a.text/cg,is created to implement object of the character grid type .it uses the O character to draw the grid .
the grid is specified by the Boolean array theta identifies whether the drawing character is to displayed. This
particular character grid is represented using the following text string :
55010010101001000101010001
The first character(5) represent the grid height .the second character also (5) represent the grid with.
The third character is the grid drawing character. The renaming character specific whetted the draw character
to be displayed at a particular grid position .one signified that the draw character should be displayed and 0
sgininfec that it should not be displayed. The array is arranged in row order beginning with to pm of the grid
{ height=h;
Width=w;
Ch=c;
Value=val;
}}
Import java.net.*;
Import java.io.*;
IOException{
Datainputstream in =new
Datainputstream(url.getinputstream());
For(int i=0;i<height;++i)
For(int j=0;j>width;++j)
byte b= in.readbyte()
if(b==48) value[i][j]=true;
}}
In.close();
}}
The gridcontenthandeler class extends the contenthandler class and provide the single method.the
getcontent() method takes an URLconnecton object as an parameter and returns an object of an object class it
also throws the IOException exception
The getcontent() method creates an object of class datainpustream and assign it to the variable it uses
getinputstream() method of the URLconnection class to access the inputstream associated with a
URLconnection
The getgridapplication illustrate the use of content handlers.it retives an object of the chargrid type from he
web server
Import java.net.*;
Import java.io.*;
Try{
URLconnection.setcontenthandlerfactory(Gridfactory);
System.out.prinln(“fetchinf URL:”+args[o]);
System.out.prinln(“height:”cg.height);
System.out.prinln(“width:”cg.width);
system.out.prinln(“char:”cg.ch);
For(intj=0;j<cg.width;++j){
If(cg.value[i][j]) System.out.prinl(cg.ch);
} System.out.print();
Error(“bad URL”);
}catch(IOException ex)
Error(“IOException occurred.”);
System.out.println(s );
System.exit(1);
}return null;
The getgridapp program defines the gridfactory as a contenthandlerfactory.it implements the create
contenthandler() method and checks to see if the MIME typr passed to it is text cg. if it is not, the null value is
return to the single that the java supply content handler should be used. If the MIME type ids text /cg,the
requested the MIME types displayed d and the gridcontenthandler object is returned.