total doc load detect

73
Load Detector ABSTRACT  The load detection, i.e. detectin g of th e work load of a person interacting with the application has formed to be necessary. By knowing the work load, it will be helpful for scheduling of the work to the individuals, thus effectively using the resources. The tool which we are developing will be helpful to automatically detect the load and will give a clear visibility to schedule the work.  The project is comprised of 3 modules. They are 1. Administrator Module. 2. Server Module 3. Intelligent Agent  The details of the individual module are as follows: 1. Administrator Module:-  Thi s mo du le wi ll be help ful in co nf igur ing of th e system. Once conf igur ed, the appl icat ion reports the status, load of the systems is reported. It provides the user to view the details in most advanced graphical model. 2. Server Module:- In this module the application is binded to a predef ined port and listens for the incoming calls, and gives the information the client requests. 3. Intelligent Agent:-  The agents move alo ng the networ k and gather the informat ion neces sary for knowing the status and workloa d per system and repo rts the information back to the administrator where it shown graphically. 1

Upload: satya-narayana

Post on 10-Apr-2018

222 views

Category:

Documents


0 download

TRANSCRIPT

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 1/73

Load Detector

ABSTRACT

  The load detection, i.e. detecting of the work load of a person

interacting with the application has formed to be necessary. By knowing thework load, it will be helpful for scheduling of the work to the individuals, thuseffectively using the resources. The tool which we are developing will behelpful to automatically detect the load and will give a clear visibility toschedule the work.

 The project is comprised of 3 modules. They are

1. Administrator Module.

2. Server Module

3. Intelligent Agent

 The details of the individual module are as follows:

1. Administrator Module:-

  This module will be helpful in configuring of the system. Onceconfigured, the application reports the status, load of the systems is

reported. It provides the user to view the details in most advanced graphicalmodel.

2. Server Module:-

In this module the application is binded to a predefined port andlistens for the incoming calls, and gives the information the client requests.

3. Intelligent Agent:-

  The agents move along the network and gather the information

necessary for knowing the status and workload per system and reports theinformation back to the administrator where it shown graphically.

1

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 2/73

Load Detector

PROBLEM ANALYSIS

Existing system

 The load detection of the persons and effective use of the resources isdifficult for the managers of any business organization with their presentsystem. with the present system they manually check the load i.e. no of transaction that were done for the day is computed and the loadscheduling and distributing is done for the next day by the managers .Thisprocess is not accurate and difficult to get a snap-shot at any particularperiod of time.

Drawbacks Of Existing System

1) Manual checking of the load is a time consuming process.

2) Manual computing will not fetch the accurate results.

3) It’s not possible to find out the load in a particular period of time, whichis a tedious process.

4) Maintaining of the previous data and managing of the data in books andothers is difficult.

Advantages of the New System

Here in the new system, a better GUI is provided for themanagers or any persons who take up the work of scheduling of the jobs. The GUI which is provided for the user helps him to check the load of hisorganization as a whole or individually. Our system helps the user toschedule the jobs very easily by plotting various kinds of graphs i.e. in apulse format. The application that we developed helps the user to check the

load at any moment and will get a snap-shot on his organization.

Enhancements in the new System

1) Displaying of the users login and logout information and showingthe status individually.

2) The GUI is designed utmost user-friendliness which helps the userto do his job enthusiastically.

2

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 3/73

Load Detector

3) The software which is developed will be helpful to schedule the jobs and we can keep a watch on the subordinates.

REQUIREMENT ANALYSIS

1) System Description:

 This project is developed as stand-alone and net-based solution.

 The software used is as follows:

a) GUI : JFC/Swing

b) Networking : Socket programming.

c) Storage : Fat File System

2) System Security:

In order to avoid the unauthorized accessing, password control is

given in order to operate in a controlled environment.

3) System Configuration:

  The system is very easy to configure, and the interface is self-explanatory and it is event driven, can be operated using mouse/key board.

4) Scope of the Work:

 The scope of the project work includes the following activities.

a) Study of Java, and understanding of TCP/IP programmingusing java network programming.

b) Study of the design procedures, ranging from requirement.

5) System Specifications:

Hardware Specification:

Keyboard : KB with 104 Keys.Processor : Pentium XMonitor : SamsungHard Disk : 20 GB

3

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 4/73

Load Detector

RAM : 128 MBPrinter : Any Dotmatrix/Laser/Inkjet

Software Specification:

-Java Runtime Environment along with OS.

Functional Requirements:

General description of Inputs and Outputs are as follows:

Inputs:

The Inputs to Administration Module

a) System Configuration : System name is selected from combo box andheld by is also selected from combo box.

b) Control Paneli) Time Inputs : The average time taken by the employee to process

a transaction apart from using

computer is entered.

ii) Grouping : Grouping is done based on the sharing of commonwork by theemployees.

iii) Alerts : Alert option can be checked to receive the alertmessages if an employee is idle for a long time.

The Inputs to Server Module

a) Key Board and Mouse messages are received which is sent by theapplication.

b) Requests from the client to for sending of the details.

The Inputs to Client Module

a) Getting Information by connecting to all systems.

 

4

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 5/73

Load Detector

Outputs:

The Outputs of Administration Module

System Configuration : Sets the details like system name with whomheld in a file.

  Time Configuring : Stores the details in its respective file.

Grouping : Stores the information and grouped in a file.

Alerts : Alerts are stored as a Boolean value in itsrespective file.

The Outputs of Server Module

 The Messages from the input devices are received from the applicationand it writes the information to the file for every predefined time.

 The requests from the client’s are processed and the information thatare stored in the file is returned to the client, thus helping the client todisplay the information according to his needs.

The Outputs of Client’s Module

  The information that is necessary to find out the load is carried

through a program which connects to all the systems at regular intervalsand thus getting the necessary data which is processed and sent by theserver. Here at the client’s side various graphs are plotted which can becustomized according to the users.

The Administration Module Interface

The GUI is developed in JFC/Swing and various forms are:

a) System Configuring.

b) Control Panel 

5

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 6/73

Load Detector

i) Time Inputsii) Groupingiii) Alerts.

Description of Administration Module 

 The initial settings after installing the product is to do the

System configuring ,i.e. get the Addresses of the system and display thosein a combo box and the GUI that is developed will guide you the rest of theprocess.

  The various screens are provided to configure the average time

per transaction excluding the computer usage to be entered and groupingfeature is provided which helps the software to automate the scheduling of the jobs.

The Server Module Interface

Here the software is developed to process the various kinds of request,which is running in the background.

Description Of the Server Module

The program will take care of processing of therequest made by the client and the messages that were received by thekeyboard and mouse are processed and storing those in the respective files,later on it supplies the information back to the client when requested.

The Client Module Interface:

 The GUI is developed in JFC/Swing.

a)Login Status

b)Load Status

Description of Client Module:

6

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 7/73

Load Detector

   The GUI helps the user to check the status of loggingin and logout and the status of the system is displayed .Another screen i.e.the load status displays the various graphs of load e.g. in Pulse form.

Developers Responsibilities:

 The developers responsibilities is to install, provide necessarytraining for the administrator/employee of the organization about thehandling of the product and the different ways to configure and usage of theproduct and also to train them, how to take necessary backupsdaily/periodically, and the developer has to test the product on the originaldata and has to demonstrate to the user and take the acceptance letter, andthe developer has to provide necessary support in the future for the productby making few negotiations.

DESIGN

Design is the technical kernel of software engineering. During the designprocess. the initial design is derived from the requirements., and refined itfurther by thoroughly analyzing the flow and interconnection of the modules. The basic steps involved in design are :

1. Data design.2. Interface design.

Data Design:

Here we used fat file system in which the elements of data supported bydelimiter. The data stored in files are :

1. Data of the users login and other information.

2. Data of the System that were Configured.

3. Data of the time inputs of the various users.

4. Data of the grouping of the users.

5. Data of the alerts.

6. Data stored at the application regarding the inputmessages.

7. Data that stored on the application side regarding thelogging.

7

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 8/73

Load Detector

Interface Design:

Based on the external internal requirement different forms , which will bethe interface between the human/machine are developed. The stepsinvolved in GUI development is:

1. By identifying the work tasks and environment GUI is designed.2. GUI construction is made by putting different controls to take the inputs.3. GUI testing and validation.

 The different user interfaces designed are as follows:

1. Administration Module

a) System Config.

b) Control Panel. 

 Time Inputs.

Grouping.

Alerts.

2. Server Module 

8

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 9/73

Load Detector

No GUI all the background processes.

3. Clients Module

a) Login Status.

b) Load Status. 

Detailed Design

Administrator Module:

Class Name External FilesLinked

Functionality Data FilesLinked for

Retrieving &Stored

1.SystemConfig

2.ControlPanel

3.TimePanel

4.GroupPane

----------

 TimePanelGroupPanelAlertPanel

----------

----------

Allows the user toconfigure theSystem and held by

details.

Allows the user toconfigure the timeinputs, groupingand alerts.

Allows the user toenter the details of the average time

taken for atransaction

SystemConfig.txt

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

Time.txt

Group.txt

9

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 10/73

Load Detector

l

5.AlertPanel

6.Login

7.ChangePwd

8.SignUp

-----------

ChangePwd

Signup

-----------

-----------

It allows to groupthe users.

Allows the user toset/unset the alerts.

Facilitates to enterinto the applicationwith authentication

Allows the user tochange thepassword.

 To signup for theapplication

Alert.txt

Users.txtUserPwd.txt

UserPwd.txt

Signup.txt

Server Module:

ClassName

External FilesLinked

Functionality Data Files Linkedfor Retrieving &

Stored

1.Client

.

---------- Receives the inputsand processes therequests of the user.

Mess.txt

Client Module:

10

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 11/73

Load Detector

Class Name ExternalFiles Linked

Functionality Data FilesLinked for

Retrieving &Stored

1.LoginStatus

2.Pulse

----------

----------

Displays the detailsof the logginginformation bygetting informationfrom the server

Displays the load ina pulse format.

Mess.txt

Mess.txt

CONTEXTLEVEL DIAGRAM

11

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 12/73

Load Detector

Fat File System

 

Administrator Module:

Users.txt

Userpwd.txt

12

LoginAdministrator 

Main Menu

Load

Detector

Administrator 

User 

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 13/73

Load Detector

System Config.txt Time.txt Alerts. txt Group.txt

 

Clients.

13

System

Config

Control

Panel

User Logging

Status

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 14/73

Load Detector

Mess.txt

Use Case Diagram

14

LocalSystem

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 15/73

Load Detector

15

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 16/73

Load Detector

TESTING

Once source code has been generated. Software must be tested touncover as many errors as possible before delivery to the customer.

Software testing is a critical element of software quality assurance andrepresents the ultimate review of specification design and code generation.

Testing objectives:

1. Testing is a process of executing a program with the intent of findingan error.

2. A good test case is one that has a high probability of finding an as yetundiscovered error.

3. A successful test is one that uncovers an as yet undiscovered error.

Testing Principles:

1. All tests should be traceable to customer requirements.2. Tests should be planned large before testing begins.3. Testing should begin “In the small” and progress towards testing “In

the large”.4. To be most effective, testing should be conducted by an independent

third party.

 The system can be tested in one of two ways.

White-box testing

 This is performed knowing the internal workings of a product, tests areconducted to ensure that “all gears mesh”, that is, that internal operationperforms according to specification and all internal components have beenadequately exercise. This can be done on close examination of proceduraldetail. Providing test cases that exercise specific set of conditions and / orloops tests logical paths through the software.

Using the white-box testing we can derive test cases that

Guarantee that all independent paths within a module have been exercisedat least once.

Exercise all logical decisions on their true and false sides.

Execute all loops at their boundaries and within their operational boundsand

Exercise internal data structures to assure their validity.

By the test cases each of the JIS modules have executed at least once andtested for bugs. All the logic decisions on their true and false sides are

executed so that the system will perform well.

16

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 17/73

Load Detector

Black-Box Testing

Knowing the specified function that a product has been designed toperform, tests can be conducted that demonstrate each function is fullyoperational, at the same time searching for errors in each function. Itenables us to derive sets of input conditions that will fully exercise allfunctional requirements for a program.

It attempts to find errors in the following categories:

Incorrect or missing functions.

Interface errors.

Errors in date structures or external database access.

Performance errors.

Initialization and termination errors.

 Tests are designed to answer the following questions:

How the functional validity tested?

What classes of input will make good test cases?

Is the system particularly sensitive to certain input values?

How are boundaries of a data class isolated?

What data rates and data volume can the system tolerate?

What effect will specific combinations of data have on systemoperation?

All the functions in the system are tested one after another and the desiredtasks are fulfilled. Input values should lie in the data values size and thesemust check before processing. All the boundary values are tested.

System testing strategies have the following generic characteristics:

Testing begins at the module level and works “outward” toward theintegration of the entire computer-based system.

17

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 18/73

Load Detector

Different testing techniques are appropriate at different points intime.

The developer of the software and an independent test groupconducts testing.

Testing and debugging are different activities, but debugging mustbe

accommodated in a testing strategy.

The different test strategies used are:

Unit Testing

It focuses verification effort on the smallest unit of system design-themodule. Using the procedural design description as a guide, importantcontrol paths are tested to uncover errors within the boundary of themodule. In the Drug Tunneling System all the small units are tested forerrors.

Integration Testing

Integration testing is a systematic technique for construction of theprogram structure while conducting test to uncover errors associated withinterfacing. The objective is to take unit tested modules and build a programstructure that has been dictated by design. In the DTS top-down integrationis followed, that is modules are integrated by moving downward through thecontrol hierarchy, beginning with the main control. Validation Testing

Validation succeeds when system functions in a manner that can bereasonably expected by the end user. This is achieved through a series of 

black-box test that demonstrate with requirements. There are two testsconducted for the system validation.

Alpha Test

A customer conducts it at the developer’s site. The software is used ina natural setting with the developer “looking over the shoulder” of the userand recording errors and usage problems.

Beta Test

18

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 19/73

Load Detector

 This test is conducted at one or more users sites by the end uses(s) of the software. Here the developer is generally not present. Therefore, thebeta test is a “live” application of the software in an environment thatcannot be controlled by the developer. The customer records all problemsthat are encountered during beta testing and reports these to the developerat regular intervals. The Jeans Information System is tested at different sitesand doing modifications to the system rectifies the problem reported by thecustomers.

Testability:

Software testability is simply how a computer program can be tested. Thecharacteristics that leads to testable software as follows.

1. Operability.

2. Observability.

3. Controllability.

4. Decomposability.

5. Simplicity.

6. Stability

7. Understandability.

Test Case Design:

An engineered product can be tested in one of the two ways:

1. Knowing the specified function that a product has been designed toperform, tests can be conducted that demonstrate each function is

fully operational while at the same time searching for error in eachfunction.

19

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 20/73

Load Detector

2. Knowing the internal working of a product.

3. The first approach is called black box testing and second white boxtesting.

System Test Cases:

 This product is built on GUI using JFC/Swing and networking programming.,we have to test the events and in associated function by doing a specifiedtasks. These cases are listed below.

Administrator Module:

 Test Case 1: Run Main Menu program and run the reporting program.

Output : Reports the system name and displays in a combo box.

 Test Case 2 : Enter the details of information of time inputs and press thesave button.

Output : Saves the data to its respective file.

 Test Case 3: Group the users and press save button.

Output : Saves the data to its respective file else shows the necessarydialog.

 Test Case 4: Check the alert and press the save button.

Output : Data is stored into its respective file else reports the exception.

Server Module:

 Test Case 1 : Run the application and look for the messages that were

transferring to the program.,and those details has to write to a file.

20

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 21/73

Load Detector

Output : Data is written to the file.

 Test Case 2 : Connect to the system from the client where the application isrunning.

Output : If connects, shows the active else shows the necessaryinformation. 

Client’s Module:

 Test Case 1: Click the login status and check for the logging details.

Output : Shows the logging details and turns the status to active.

 Test Case 2 : Click the load status

Output : Displays the results of load in a graphical format.

21

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 22/73

Load Detector

22

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 23/73

Load Detector

23

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 24/73

Load Detector

24

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 25/73

Load Detector

25

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 26/73

Load Detector

26

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 27/73

Load Detector

27

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 28/73

Load Detector

28

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 29/73

Load Detector

29

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 30/73

Load Detector

30

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 31/73

Load Detector

31

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 32/73

Load Detector

32

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 33/73

Load Detector

33

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 34/73

Load Detector

34

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 35/73

Load Detector

35

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 36/73

Load Detector

36

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 37/73

Load Detector

37

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 38/73

Load Detector

38

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 39/73

Load Detector

39

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 40/73

Load Detector

40

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 41/73

Load Detector

41

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 42/73

Load Detector

42

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 43/73

Load Detector

43

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 44/73

Load Detector

Code.

SignUp Code

 public void actionPerformed(ActionEvent ae)

{

if(ae.getSource()==jb_signup)

{

if(jtf_pwd.getText().trim().equals(jtf_cpwd.getText().trim()))

44

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 45/73

Load Detector

signup();

else

{new DialogInformation(ct,"Check the Password");jtf_pwd.requestFocus();}

}

if(ae.getSource()==jb_clear)

clear();

if(ae.getSource()==jb_close)

close();

}

public void keyPressed(KeyEvent ke)

{

if(ke.getSource()==jb_signup&&ke.getKeyCode()==ke.VK_ENTER)

{

if(jtf_pwd.getText().trim().equals(jtf_cpwd.getText().trim()))

signup();

else{new DialogError(ct,"Check the Password");jtf_pwd.requestFocus();}

}

if(ke.getSource()==jb_clear&&ke.getKeyCode()==ke.VK_ENTER)

clear();

if(ke.getSource()==jb_close&&ke.getKeyCode()==ke.VK_ENTER)

close();

MainMenu Code .

 public void run()

{

try{

ServerSocket ss=new ServerSocket(2001);

System.out.println("Address Recording Started");

while(true)

{

Socket s=ss.accept();

Thread t=new Thread(new RecAddC(s));

t.start();

}}catch(Exception j){System.out.println(j);}

}

}

class RecAddC implements Runnable

{

Socket s;

RecAddC(Socket s)

{

this.s=s;

}

 public void run()

45

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 46/73

Load Detector

{

String namev=null;

DataInputStream dis=null;

try{

dis=new DataInputStream(s.getInputStream());

String name=dis.readLine();

while(name==null)

name=dis.readLine();

 boolean flag3=false;

Enumeration e=MainMenu.v.elements();

 boolean b=e.hasMoreElements();

 

if(b==false)

MainMenu.v.addElement(name); 

outer:while(e.hasMoreElements())

{

namev=(String)e.nextElement();

if(name.equals(namev))

{

flag3=true;

break outer;

}

else

flag3=false; 

}//while

if(flag3==false)

MainMenu.v.addElement(name);

}catch(Exception j){System.out.println(j);}

finally

{

Code For Client .

try{

Thread t=new Thread(new SendLog());

t.start();

Thread t1=new Thread(new ResCheck());

t1.start();

InetAddress ia=InetAddress.getLocalHost();

46

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 47/73

Load Detector

String name=ia.getHostName();

Socket s=new Socket("devserver",2001);

PrintStream ps=new PrintStream(s.getOutputStream());

 ps.println(name);

 ps.close();

}catch(Exception j){System.out.println(j);}

}

}

class SendLog implements Runnable

{

String data;

 public void run()

{

PrintStream ps=null;

DataInputStream dis=null;

String login=null;

String logout=null;

try{

ServerSocket ss=new ServerSocket(3000);

System.out.println("Sending log information started");

while(true)

{

Socket s=ss.accept();

dis=new DataInputStream(s.getInputStream());

data=dis.readLine();

login=getLog("c:/Login.txt");logout=getLog("c:/Logout.txt");

 ps=new PrintStream(s.getOutputStream());

 ps.println(login+"#"+logout);

 ps.close();

}//while

}catch(Exception j){System.out.println(j);}

}

 public String getLog(String path)

{

String log=null;

DataInputStream dis1=null;try{

dis1=new DataInputStream(new FileInputStream(path));

String str=dis1.readLine();

while(str!=null)

{

StringTokenizer st=new StringTokenizer(str,"#");

String date=(String)st.nextToken();

if(data.equals(date))

log=(String)st.nextToken();

str=dis1.readLine();

}//outer(m)

}catch(Exception j){System.out.println(j);}

47

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 48/73

Load Detector

finally{try{dis1.close();}catch(Exception j1){}}

return log;

}//end of method

}//end of class

class ResCheck implements Runnable

{

 public void run()

{

try{

ServerSocket ss=new ServerSocket(3001);

System.out.println("Responding systems started");

while(true)

{

Socket s=ss.accept();

System.out.println("System Tested OK");

 JAVA

About Java

Initially the language was called as “oak” but it was renamed as “Java”in 1995. The primary motivation of this language was the need for a

48

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 49/73

Load Detector

platform-independent (i.e., architecture neutral) language that could beused to create software to be embedded in various consumer electronicdevices.

o  Java is a programmer’s language.o  Java is cohesive and consistent.

o Except for those constraints imposed by the Internet environment, Java gives the programmer, full control.

Finally, Java is to Internet programming where C was to systemprogramming.

Importance of Java to the Internet

 Java has had a profound effect on the Internet. This is because, Java

expands the Universe of objects that can move about freely inCyberspace. In a network, two categories of objects are transmittedbetween the Server and the Personal computer. They are: Passiveinformation and Dynamic active programs. The Dynamic, Self-executing programs cause serious problems in the areas of Securityand probability. But, Java addresses those concerns and by doing so,has opened the door to an exciting new form of program called theApplet.

 Java can be used to create two types of programs:

 Applications and applets. An application is a program that runs on ourComputer under the operating system of that computer. It is more orless like one creating using C or C++. Java’s ability to create Appletsmakes it important. An Applet is an application designed to betransmitted over the Internet and executed by a Java –compatible webbrowser. An applet is actually a tiny Java program, dynamicallydownloaded across the network, just like an image. But the differenceis , it is an intelligent program, not just a media file. It can react to theuser input and dynamically change.

FEATURES OF JAVA

Security

Every time you that you download a “normal” program, you are riskinga viral infection. Prior to Java, most users did not download executable

49

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 50/73

Load Detector

programs frequently, and those who did scanned them for virusesprior to execution. Most users still worried about the possibility of infecting their systems with a virus. In addition, another type of malicious program exists that must be guarded against. This type of program can gather private information, such as credit card numbers,bank account balances, and passwords. Java answers both of theseconcerns by providing a “firewall” between a networked applicationand your computer.

When you use a Java-compatible Web browser, you can safelydownload Java applets without fear of virus infection or maliciousintent.

Portabil ity

For programs to be dynamically downloaded to all the various types of platforms connected to the Internet, some means of generatingportable executable code is needed .As you will see, the samemechanism that helps ensure security also helps create portability.Indeed, Java’s solution to these two problems is both elegant andefficient.

The Bytecode

 The key that allows the Java to solve the security and portabilityproblems is that the output of Java compiler is Bytecode. Bytecode is a

highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). That is, in its standard form, the JVM is an interpreter for bytecode.

 Translating a Java program into bytecode helps makes it much easierto run a program in a wide variety of environments. The reason is,once the  run-time package exists for a given system, any Javaprogram can run on it.

Although Java was designed for interpretation, there is technically

nothing about Java that prevents on-the-fly compilation of bytecodeinto native code. Sun has just completed its Just In Time (JIT) compilerfor bytecode. When the JIT compiler is a part of JVM, it compilesbytecode into executable code in real time, on a piece-by-piece,demand basis. It is not possible to compile an entire Java program intoexecutable code all at once, because Java performs various run-timechecks that can be done only at run time. The JIT compiles code, as itis needed, during execution.

50

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 51/73

Load Detector

 Java Virtual Machine (JVM)

Beyond the language, there is the Java virtual machine. The Javavirtual machine is an important element of the Java technology. Thevirtual machine can be embedded within a web browser or anoperating system. Once a piece of Java code is loaded onto a machine,it is verified. As part of the loading process, a class loader is invokedand does byte code verification makes sure that the code that’s hasbeen generated by the compiler will not corrupt the machine that it’sloaded on. Byte code verification takes place at the end of thecompilation process to make sure that is all accurate and correct. So

byte code verification is integral to the compiling and executing of  Java code.

 

  Javac

 

.

The above p ic ture shows the development process atypical

 Java programming uses to produce byte codes and executes them. The first box indicates that the Java source code is located in a .Javafile, which is processed with a Java compiler called javac. The Javacompiler produces a file called a .class file, which contains the bytecode. The .class file is then loaded across the network or loaded locallyon your machine into the execution environment is the Java virtual

machine, which interprets and executes the byte code.

 Java Architecture

  Java architecture provides a portable, robust, high performingenvironment for development. Java provides portability by compilingthe byte codes for the Java Virtual Machine, which are then interpretedon each platform by the run-time environment. Java is a dynamicsystem, able to load code when needed from a machine in the same

room or across the planet.

51

 JavaSourceCode

Java

Byte

Code JVM

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 52/73

Load Detector

Compilation of code

When you compile the code, the Java compiler creates machine code(called bytecode) for a hypothetical machine called Java VirtualMachine (JVM). The JVM is supposed to execute the bytecode. The JVMis created for overcoming the issue of portability. The code is written

and compiled for one machine and interpreted on all machines. Thismachine is called Java Virtual Machine.

Compi l ing and interpret ing Java Source Code

During run-time the Java interpreter tricks the byte code file intothinking that it is running on a Java Virtual Machine. In reality thiscould be a Intel Pentium Windows 95 or Sun SARC station runningSolaris or Apple Macintosh running system and all could receive codefrom any computer through Internet and run the Applets.

Simple

 Java was designed to be easy for the Professional programmer to learnand to use effectively. If you are an experienced C++ programmer,learning Java will be even easier. Because Java inherits the C/C++

syntax and many of the object oriented features of C++. Most of theconfusing concepts from C++ are either left out of Java or

52

Source

Code………..………..

………..

PCCompiler

MacintoshCompiler

SPARC

Compiler

Java Byte

Code

Platform

Independent

Java

Interpreter

Java

Interpreter

Macintosh

Java

Interpreter

(SPARC)

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 53/73

Load Detector

implemented in a cleaner, more approachable manner. In Java thereare a small number of clearly defined ways to accomplish a given task.

Object-Oriented

  Java was not designed to be source-code compatible with any otherlanguage. This allowed the Java team the freedom to design with ablank slate. One outcome of this was a clean usable, pragmaticapproach to objects. The object model in Java is simple and easy toextend, while simple types, such as integers, are kept as high-performance non-objects.

Robust

  The multi-platform environment of the Web places extraordinary

demands on a program, because the program must execute reliably ina variety of systems. The ability to create robust programs was given ahigh priority in the design of Java. Java is strictly typed language; itchecks your code at compile time and run time.

  Java virtually eliminates the problems of memory management anddeallocation, which is completely automatic. In a well-written Javaprogram, all run time errors can –and should –be managed by yourprogram.

53

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 54/73

Load Detector

SWINGS

The comp.sun.java.swing classes can be grouped into the followingresponsibility areas:

1. The Jcomponent branch for widgets2 .Layout manager classes

1. Box Layout

2. Overlay layout3. scrollpanel layout4. viewport layout5. Sizerequirements

3. The Model classes and interfaces.4. The Manager Classes

1. Desktopmanager and default Deskttopmanager.2. FocusMangaer and DefaultFocusManager3. MenuSelectionManager4. RepainManger

5. ToolTipManager6. UiManager

5. The AbstractAction and KeyStroke Classes and ActionInterface6. Miscellaneous Classes

1 .BorderFactory2. Imageicon and Icon interface3. LookAndFeel4. ProgressMonitor and ProgressMonitorInputStream

5. SwingUtilities6. GrayFilter7. Timer.

54

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 55/73

Load Detector

In addition to the above cor com.sun.java.swing package , manysubpackages provide additional support.

Com.sun.java.swing.border Defines various borderrendering styles

Com.sun.java.swing.colorchooser Support classes for colorchoosing component

Com.sun.java.swing.event Swing-specific eventclasses

Com.sun.java.swing.filechooser Support classes forchoosing files

Com.sun.java.swing.plaf.* Pluggable look and feelsupport classes

Com.sun.java.swing.table Table usage supportclasses.

  Com.sun.java.swing.text.* Text component supportclasses,including HTML and Rich text Format(RTF)

Com.sun.java.swing.tree Tree Componentsupport classes.

Com.sun.java.swing.undo Undo/Redoimplementation support Classes.

 

 Jcomponent Classes

Like java.awt, the majority of classes within packagecom.sun.java.swing are related to GUI creation.

  Jbutton and Jlabel The swing button and label widgets,providing support for a single line of text, an image, andpopup tool tips.

 Jpanel and Box The Container widgets, providing support forbuffering of painting operations, user-defined borders, andmuch more.

 Jmenu,Jmenuitem,Jseparator,JcheckBoxMenuItem,JradioButtonMenuItem,JmenuBar,and Jpopupmenu The Menu widges:amenu, menu Item, menu separator,toggleable menu items,menu bar and popup menu. Each can have a single line of text, an image, and popup tool tips.

Layout manager Classes

In addition to the half dozen or so layout managerclasses in AWT, ther are more avialble in Com.sun.java.swing . These offerthe same benefits available with the java.awt.layout managers, which are

basically platform-independent applications:

55

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 56/73

Load Detector

With the BoxLayout class, components are laid out either vertically orhorizontally in a single column or row. Each component does not haveto be the same size and there is support for providing spacersbetween components.

 The over lay Layout class offers support for arranging componentsone on top of another.

Class scrollpanel layout provides the layout manager used by the  JscrollPane with areas for your own scrollbars,headers,and cornerimages.Usualyy you will never use this outside of the one created foryou when you user JscrollPane.

  The ViewPortLayout class is similar to ScrollPanel Layout in that itexists for the Jviewport class benefit. It offers sizing and alignmentsupport for when objects in viewport are larger than space permits.

Class Size Requirements is a support class for the layout mangers, tohelp calculate component sizes and positions

 

Model Classes and Interfaces

The swing widgets offer two means of operations. You can storetheir data internally and let them act accordingly, or you can store the dataexternally. When the data is truly stored outside the widget, the meansused is the model classes rovided within the com.sun.java.swing package.Bystoring the dat externally you can chage the widget used and the view of thedata, without worrying about losing anything. While working in this manner

creates more robust and maintainable programs, its takes longer toser upinitially.

Manager Classes:

Like just about everything in Sing, You can customize the behaviour of almost everything. The various manager classes in com.sun.java.swing offerhlp in allowing you to customize the user’s experiences with your programs.For instance, if you don’t like the way those little tool tip messages are

displayed when you rest your mouse over a widget, you can use the tool tipmanager to adjust behavior like the delay time. Each of the Manager classesis responsible for its own area of the swing experience.

Abstract action and Keystroke classes and action interface

The AbstractAction, Keystroke and action classes provide analternative to the simple minded approach of handling events within theAWT widgets. Normally, developers would program responses to specificuser behavior during the course of an application. This is fine for things thatlive in isolated worlds. However by declaring a well defined servicesprotocol, developers can define services when they need them. For instanceif you define how to save a JtextArea a multilane input field you would

56

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 57/73

Load Detector

normally associate that behaviour with fiel save menu. However, if you wereto register the save action with ask the jtextarea how to do it . The Jtextareaknows what action operations it supports. You would find your abstractactionimplementation supporting save present and associate it to some otherinterface. The keystroke class is also available, to support keyboard-orientedevents.

Miscellaneous Swing Classes

The following com.sun.java.swing classes do not fall neatly into anycategory.

 The BorderFactory class works with the border subpackage. Using theabstract Factory creation pattern, the Border Factory class createsBorder objectives without your specifying the actual concrete class

that implements the Border Interface.  The ImageIcon class provides an implementation of the Icon interface

for Image Objects. You use icons for displaying images with labels,buttons and menus among many other places.

Along with several .plaf subpackages, the LookAndFeel class providesthe basis for swing’s pluggable look-and-feel support.

 The progressMonitor and ProgressMonitorInputStream pair provides apre buit generic popup window to permit users to interrupt the loadingof files.

 The Swing Utilities class provides a set of convenience routines for

common operations. Among may others, methods exist for finding acomponent’s top level window and checking which mouse button amouse event is for

 The grayfilter represents an image related support class used by singthat the development team thought other developers wouldwelcome.GrayFilter turns any image into a “grayscale” image.

 The timer class provides the means to signal periodic operations.

 Java Networking

One of the best features of Java is its networking support. Java hasclasses that range from low-level TCP/IP connections to ones that provideinstant access to resources on the World Wide Web. Even if you have neverdone any network programming before, Java makes it easy.

 The following chapters introduce you to the networking classes and how touse them. A guide to what is covered by each chapter follows:

• “Introduction to Java Network Programming”

57

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 58/73

Load Detector

•  You are reading contains an introduction to TCP/IP networking and alist of the concepts you should be familiar with before reading the restof the networking section.

• “The java.net Package”• A tour of the classes that make up the Java networking package

 java.net. The exceptions raised by the networking classes also arecovered, as are the interfaces specified by the package.

• “Network Programming”•  The meat of the networking chapters contains examples of how to use

the networking classes. There also is a section about deciding which Java classes best suit your networking needs.

• “Overview of Content and Protocol Handlers”• Discusses what protocol and content handlers are, how they can be

applied, and provides an introduction to writing your own.• “Extending Java with Content and Protocol Handlers”

• Classes can be written to allow the URL class to deal with newprotocols and content types. For example, a Web browser written in Java could be extended to deal with a new image format. This chapterdetails how to write and use these classes.

Prerequisites

 Though networking with Java is fairly simple, there are a few concepts andclasses from other packages that you should be familiar with before readingthis part of the book. If you are only interested in writing an applet thatinteracts with an HTTP daemon, you probably can just concentrate on theURL class for now. For the other network classes, you will need at least apassing familiarity with the World Wide Web, java.io classes, threads, and TCP/IP networking.

World Wide Web Concepts

If you are using Java you probably already have a familiarity with the Web.Knowledge of how Uniform Resource Locators (URLs) work is needed to usethe URL and URLConnection classes.

 java.io Classes

Once you have a network connection established using one of the low-levelclasses, you will be using java.io.InputStream and java.io.OutputStreamobjects or appropriate subclasses of the objects to communicate with the

58

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 59/73

Load Detector

other endpoint. Also, many of the java.net classes throw java.io.IOExceptionwhen they encounter a problem.

Threads

Although not strictly needed for networking, threads make using the networkclasses easier. Why tie up your user interface waiting for a response from aserver when a separate communication thread can wait rather than theinterface thread? Server applications also can service several clientssimultaneously by spawning off a new thread to handle each incomingconnection.

TCP/IP Networking

Before using the networking facilities of Java, you need to be familiar with

the terminology and concepts of the TCP/IP networking model. The last partof this chapter should serve to get you up to speed.

Internet Networking: A Quick Overview

  TCP/IP (Transmission Control Protocol/Internet Protocol) is the set of networking protocols used by Internet hosts to communicate with otherInternet hosts. If you have ever had any experience with networks ornetwork programming in general you should be able to just skim this sectionand check back when you find a term you are not familiar with. A list of 

references is given at the end of this section if you would like more detailedinformation.

TCP/IP and Networking Terms

Like any other technical field, computer networking has its own set of  jargon. These definitions should clear up what the terms mean.

• Host• Individual machine on a network. Each host on a TCP/IP network has at

least one unique address (see IP number).• Hostname• Symbolic name that can be mapped into an IP number. Several

methods exist for performing this mapping, such as DNS (DomainName Service) and Sun’s NIS (Network Information Services).

• IETF• Internet Engineering Task Force, a group responsible for maintaining

Internet standards and defining new ones.• Internet• Network of networks. When capitalized as the Internet it refers to the

globally interconnected network of networks.•

IP number

59

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 60/73

Load Detector

• Unique address for each host on the Internet (unique in the sense thata given number may only be used by one particular machine, but aparticular machine may be known by multiple IP numbers). Thiscurrently is a 32-bit number that consists of a network part and a hostpart. The network part identifies the network the host resides on andthe host part is the specific host on that network. Sometimes the IPnumber is referred to as the IP address of a host.

• Packet• Single message sent over a network. Sometimes a packet is referred

to as a datagram, but the former term usually refers to data at thenetwork layer and the latter refers to a higher-layer message.

• Protocol• Set of data formats and messages used to transmit information.

Different network entities must speak the same protocol in order tounderstand each other.

• Protocol stack• Services can be thought of as different layers that use lower-level

services to provide services to higher-level services. This set of layersproviding network functionality is known as a protocol stack.

• RFC• For Comments—documents in which proposed Internet standards are

released. Each RFC is issued a sequential number, which is how theyare usually referenced. Examples are RFC 791, which specifies theInternet Protocol (the IP of TCP/IP), and RFC 821, which specifies theprotocol used for transferring e-mail between Internet hosts (SMTP).

• Router• Host that knows how to forward packets between different networks. A

router can be a specialized piece of network hardware or can besomething as simple as a machine with two network interfaces (eachon a different physical network).

• Socket• Communications endpoint (that is, one end of a conversation). In the

  TCP/IP context, a socket usually is identified by a unique pairconsisting of the source IP address and port number and thedestination IP address and port number.

The Internet Protocols

 TCP/IP is a set of communications protocols for communicating betweendifferent types of machines and networks (hence the name internet). Thename TCP/IP comes from two of the protocols: the Transmission ControlProtocol and the Internet Protocol. Other protocols in the TCP/IP suite are theUser Datagram Protocol (UDP), the Internet Control Message Protocol (ICMP),and the Internet Group Multicast Protocol (IGMP).

60

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 61/73

Load Detector

  These protocols define a standard format for exchanging informationbetween machines (known as hosts) regardless of the physical connectionsbetween them. TCP/IP implementations exist for almost every type of hardware and operating system imaginable. Software exists to transmit IPdatagrams over network hardware ranging from modems to fiber-opticcable.

TCP/IP Network Architecture

 There are four layers in the TCP/IP network model. Each of the protocols inthe TCP/IP suite provides for communication between entities in one of theselayers. These lower-level layers are used by higher-level layers to get datafrom host to host. The layers are as follows, with examples of what protocols

live at each layer:

• Physical (Ethernet, Token Ring, PPP)• Network (IP)•  Transport (TCP, UDP)• Application (Telnet, HTTP, FTP, Gopher)

The TCP/IP protocol stack. 

Each layer in the stack takes data from the one above it and adds theinformation needed to get the data to their destination, using the services of the layer below. One way to think of this layering is like the layers of anonion. Each protocol layer adds a layer to the packet going down theprotocol stack. When the packet is received, each layer peels off itsaddressing to determine where to send the packet next.

As an example, suppose that your Web browser wants to retrieve somethingfrom a Web server running on a host on the same physical network. Thebrowser sends an HTTP request using the TCP layer. The TCP layer asks theIP layer to send the data to the proper host. The IP layer then would use thephysical layer to send the data to the appropriate host.

At the receiving end, each layer strips off the addressing information thatthe sender added and determines what to do with the data. Continuing theexample, the physical layer would pass the received IP packet to the IPlayer. The IP layer would determine that the packet is a TCP packet and passit to the TCP layer. The TCP layer would pass the packet to the HTTP daemonprocess. The HTTP daemon then processes the request and sends the datarequested back through the same process to the other host.

61

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 62/73

Load Detector

 Addressing information is added and removed at each layer.

In a case where the hosts are not on the same physical network, the IP layerwould handle routing the packet through the correct series of hosts (knownas routers) until it reaches its destination. One of the nice features of the IPprotocol is that individual hosts do not have to know how to reach every hoston the Internet. The host simply passes to a default router any packets fornetworks it does not know how to reach.

For example, a university might only have one machine with a physicalconnection to the Internet. All of the campus routers would know to forwardall packets destined for the Internet to this host. Similarly, any host on theInternet only has to know to get packets to this one router to reach any hostat the university. The router would forward the packets to the appropriatelocal routers.

 An example of IP routing. 

NOTE

 There is a publicly available program for UNIX platforms called traceroute thatis useful if you want to find out what routers actually are responsible forgetting a packet from one host to another and how long each hop takes. Thesource for traceroute can be found by consulting an Archie server for an FTPsite near you, or from ftp://ee.lbl.gov.

The Future: IP Version 6

Back when the TCP/IP protocols were being developed in the early 1970s,32-bit IP numbers seemed more than capable of addressing all the hosts onan internet. Though there currently is not a lack of IP numbers, the explosive

growth of the Internet in recent years is rapidly consuming the remainingunassigned addresses. To address this lack of IP numbers a new version of the IP protocols is being developed by the IETF. This new version, known aseither IPv6 or IPng (IP Next Generation), will provide for a much largeraddress space of 128 bits. This address space will allow for approximately3.4 x 1038 different IP addresses.

IPv6 will be backward compatible with current IP implementations to allowolder clients to interoperate with newer ones. Other benefits of the newversion are as follows:

• Improved support for multicasting (sending packets to severaldestinations at one time).

62

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 63/73

Load Detector

• Simplified packet header formats.• Support for authentication and encryption of packet contents at the

network layer.• Support for designating a connection as a special flow which should be

given special treatment (such as real-time audio data that needs quickdelivery).

 These enhancements to TCP/IP should allow the Internet to continue thephenomenal growth it has experienced over the past few years.

Where to Find More Information

 This was not meant to completely cover the subject of TCP/IP. If your

curiosity has been piqued, the following online documents and books mightbe of interest to you.

RFCs

 The first and definitive source of information on the IP protocol family arethe Request For Comments documents defining the standards themselves.An index of all of RFC documents is available through the Web athttp://ds.internic.net/ds/rfc-index.html. This page has pointers to all currentlyavailable RFCs (organized in groups of 100) as well as a searchable index.

Gives the numbers of some relevant RFCs and what they cover. Keep inmind that a given RFC might have been made obsolete by a subsequentRFC. The InterNIC site’s index will note in the description any documentsthat were made obsolete by a subsequent RFC.

RFCNumber

Topic

791 The Internet Protocol (IP)

793 The Transmission Control Protocol (TCP)

768 The User Datagram Protocol (UDP)

894 Transmission of IP Datagrams over Ethernet Networks

1171 The PPP Protocol

1883 IP Version 6

63

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 64/73

Load Detector

1602 The Internet Standards Process: How an RFC Becomes aStandard

1880 Current Internet Standards

Network programming

 This chapter shows how to put Java’s networking classes to use in appletsand applications. Before getting into the examples, a short overview ispresented of the capabilities and limitations of the different network classes.If you have never done any network programming, this should help youdecide on what type of connection class you need to base your application. This overview should help you to pick the Java classes that will best fit yournetworking application. An overview of Java security, as it relates to networkprogramming, is also given.

 The examples show you what each of the Java networking classes does andhow to use them. The first example is an applet that retrieves a specifiedURL and displays the contents in a window using the URL andURLConnection classes. Next is a client for the Finger protocol thatdemonstrates the use of Socket objects. The TCPServer example shows howto use a ServerSocket to write a simple TCP-based server. The last two

examples use the DatagramSocket and DatagramPacket in both server andclient roles.

Which Class Is Right for Me?

 The answer to this question depends on what you are trying to do and whattype of application you are writing. The different network protocols havetheir own advantages and disadvantages. If you are writing a client forsomeone else’s protocol, the decision probably has been made for you. If 

you are writing your own protocol from scratch, the following should help

64

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 65/73

Load Detector

you decide what transport method (and hence, what Java classes) best fityour application.

URL

  This class is an example of what can be accomplished using the other,lower-level network objects. The URL class is best suited for applications orapplets that need to access content on the World Wide Web. If all you needto use Java for is writing Web browser applets, the URL and URLConnectionclasses in all likelihood will handle your network communications needs.

 The URL class enables you to retrieve a resource from the Web by specifyingthe Uniform Resource Locator for it. The content of the URL is fetched and

turned into a corresponding Java object (such as a String containing the textof an HTML document). If you are fetching arbitrary information, theURLConnection object provides methods that will try to deduce the type of the content either from the filename in the URL or from the content streamitself.

Socket

 The Socket class provides a reliable, ordered stream connection (that is, a TCP/IP socket connection). The host and port number of the destination are

specified when the Socket is created.

 The connection is reliable because the transport layer (the TCP protocollayer) acknowledges the receipt of sent data. If one end of the connectiondoes not get an acknowledgment back within a reasonable period of time, itwill resend the unacknowledged data (a technique known as PositiveAcknowledgment with Retransmission, often abbreviated as PAR). Once youhave written data into a Socket, you can assume that the data will get to theother side (unless you receive an IOException, of course).

Ordered stream means that the data arrive at the opposite end in the exact

same order that you write the data. However, because the data are astream, write boundaries are not preserved. What this means is that if youwrite 200 characters, the other side might read all 200 at once. It might getthe first 10 characters one time and the next 190 the next time data arereceived from the socket. In either case the receiver cannot tell where eachgroup of data was written.

 The reliable stream connection provided by Socket objects is well suited forinteractive applications. Examples of protocols that use TCP as theirtransport mechanism are telnet and FTP. The HTTP protocol used to transferdata for the Web also uses TCP to communicate between hosts.

65

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 66/73

Load Detector

ServerSocket

A ServerSocket object represents what Socket-type connectionscommunicate with. Server sockets listen on a given port for connection

requests when their accept() method is called. The ServerSocket offers thesame connection-oriented, ordered stream protocol (TCP) that the Socketobject does. In fact once a connection has been established, the accept()method will return a Socket object to talk with the remote end.

DatagramSocket

A DatagramSocket provides an unreliable, connectionless, datagramconnection (that is, a UDP/IP socket connection).

Unlike the reliable connection provided by a Socket, there is no guarantee

that what you send over a UDP connection actually gets to the receiver. The TCP connection provided by the Socket class takes care retransmitting anypackets that might get lost. Packets sent through UDP simply are sent outand forgotten, which means that if you need to know that the receiver gotthe data, you will have to send back some sort of acknowledgment. Thisdoes not mean that your data will never get to the other end of a UDPconnection. If a network error happens (your cat jiggles the Ethernet plugout of the wall, for instance) then the UDP layer will not try to send it againor even know that the packet did not get to the recipient.

Connectionless means that the socket does not have a fixed receiver. Youmay use the same DatagramSocket to send packets to different hosts andports, whereas a Socket connection is only to a given host and port. Once aSocket is connected to a destination it cannot be changed. The fact that UDPsockets are not bound to a specific destination also means that the samesocket can listen for packets as well as originating them. There is no UDPDatagramServerSocket equivalent to the TCP ServerSocket.

Datagram refers to the fact that the information is sent as discrete packetsrather than a continuous ordered stream. The individual packet boundariesare preserved. It might help to think of it as dropping fixed-size postcards in

a mailbox. For example, if you send four packets, the order in which theyarrive at the destination is not guaranteed to be the same in which theywere sent. The receiver could get them in the same order they were sent orthey could arrive in reverse order. In any case, each packet will be receivedwhole.

Given the above constraints, why would anyone want to use aDatagramSocket? There are several advantages to using UDP, as follows:

•   You need to communicate with several different hosts. Because aDatagramSocket is not bound to a particular host, you may use the

66

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 67/73

Load Detector

same object to communicate with different hosts by specifying theInetAddress when you create each DatagramPacket.

•  You are not worried about reliable delivery. If the application you arewriting does not need to know that the data it sends get to the otherend, using a UDP socket eliminates the overhead of acknowledgingeach packet that TCP does. Another case would be if the protocol youare using has its own method of handling reliable delivery andretransmission.

•  The amount of data being sent does not merit the overhead of settingup a connection and the reliable delivery mechanism. An applicationthat is only sending 100 bytes for each transaction every 10 minuteswould be an example of this situation.

 The NFS (Network File System) protocol version two, originally developedby Sun with implementations available for most operating systems, is an

example application that uses UDP for its transport mechanism. Anotherexample of an application where a DatagramSocket might be appropriatewould be a multiplayer game. The central server would need tocommunicate to all of the players involved, and would not necessarily needto know that a position update got to the player.

NOTE

An actual game that uses UDP for communication is Netrek, a space combatsimulation loosely based on the Star Trek series. Information on Netrek canbe found using the Yahoo subject catalog at

http://www.yahoo.com/recreation/games/internet_games/netrek/. There isalso a Usenet newsgroup, news:rec.games.netrek.

Decisions

Now that you know what the classes are capable of, you can choose the onethat best fits your application. Table 29.1 sums up what type of connectioneach of the base networking classes creates. The direction column indicateswhere a connection originates: “Outgoing” indicates that your application isopening a connection out to another host; and “Incoming” indicates thatsome other application is initiating a connection to yours.

Low-level connection objects summarized.

Class Connection Type Direction

SocketConnected, ordered byte stream(TCP)

Outgoing

ServerSocket Connected, ordered byte stream Incoming

67

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 68/73

Load Detector

(TCP)

DatagramSocket

Connectionless datagram (UDP)Incoming orOutgoing

  You need to look at the problem you are trying to solve, anyconstraints you have, and the transport mechanism that best fits yoursituation. If you are having problems choosing a transport protocol, take alook at some of the RFCs that define Internet standards for applications(such as HTTP or SMTP). One of them might be similar to what you are tryingto accomplish. As an alternative, you could be indecisive and provide both TCP and UDP versions of your service, duplicating the processing logic andcustomizing the network logic. Trying both transport protocols with a pared-down version of your application might give you an indication that better

serves your purposes. Once you’ve looked at these factors you should beable to decide what class to use.

A Note on Java Security and the Network Classes

One of the purposes of Java is to enable executable content from anarbitrary network source to be retrieved and run securely. To enable this,the Java runtime enforces certain limitations on what classes obtainedthrough the network may do. You should be aware of these constraintsbecause they will affect the design of applets and how the applets must beloaded. You will need to take into consideration whatever security

constraints are imposed by your target environment and your developmentenvironment, as well, when designing your application or applet.

For example, Netscape Navigator 2.0 allows code loaded from local diskmore privileges than code loaded over a network connection. A class loadedfrom an HTTP daemon may only create outgoing connections back to thehost from which it was loaded. If the class had been loaded from the localhost (that is, it was located somewhere in the class search path on themachine running Navigator), it would be able to connect to an arbitrary host.Contrast this with the appletviewer provided with Sun’s Developer’s Kit. The

appletviewer can be configured to act similarly to Navigator or to enforce norestrictions on network connectivity.

If you need full access to all of Java’s capabilities, there is always the optionof writing a stand-alone application. A stand-alone application (that is, onenot running in the context of a Web browser) has no restrictions on what it isallowed to do. Sun’s HotJava Web browser is an example of a stand-aloneapplication.

NOTE

For a more detailed discussion of Java security and how it is designed into thelanguage and runtime, take a look at Chapter 40, “Java Security.”

68

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 69/73

Load Detector

In addition, Sun has several white paper documents and a collection of frequently asked questions available at http://www.javasoft.com/sfaq/.

  These checks are implemented by a subclass of   java.lang.SecurityManager. Depending on the security model, the object willallow or deny certain actions. You can check beforehand whether acapability your applet needs is present by calling the SecurityManageryourself. The java.lang.System object provides a getSecurityManager( )method that returns a reference to the SecurityManager active for thecurrent context. If your applet needs to open a ServerSocket, for instance,you can call the checkListen( ) method yourself and print an error message(or pop up a dialog box) alerting the users and referring them to installationinstructions.

Using the URL Class

 The URL class lets your Java code access resources from anywhere on theWorld Wide Web. We’ll start off by creating an applet that fetches a URL anddisplays the raw contents in a window. This first applet will use theURLConnection class method getInputStream( ) to read in the raw data.

Next, we’ll modify the applet to use the getContent( ) method to convert the

resource into an appropriately typed Java object.

Using the Socket Class

 The Socket class probably will solve most of your raw network access needs.In this section, we’ll demonstrate how to use the class with a client for astandard Internet service. The example also will lay the groundwork forwriting TCP servers with ServerSockets, as well as being the basis for the

protocol handler example in Chapter 31.

69

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 70/73

Load Detector

A Client for the Finger Protocol

  The first example of using Socket objects will be a client for the Fingerprotocol. This protocol is used to request information about users from a

multiuser system, such as the last time they accessed the system or theirreal names. Most UNIX variants provide a Finger server to handle requests,and there are programs for Windows and Macintosh platforms that providethe same service. There is a client program, usually called Finger, or theservice can be accessed by connecting to the server’s port with a telnetapplication.

 The Finger protocol is defined in RFC 762. The server listens on TCP port 79.It expects either a user name to retrieve information about, followed byASCII carriage return and linefeed characters, or just the carriage return andlinefeed characters if information is sought on all users currently logged in.

 The information will be returned as ASCII text in a system-dependent format(although most UNIX variants will give similar information).

Design

 The fingerClient class will be very simple. It will have a member to hold theSocket we use to communicate, and two String objects to hold the username and host we want information about. Because the protocol is so

simple, we’ll do all of the communication in a method called getInfo(). Thismethod will send the query and return the results to the caller as a String.Instead of throwing any exceptions, we will catch them and return an errormessage to the caller.

 To illustrate how to use the client class, we’ll have a fingerApplet that willdisplay for whom Finger is being used, what host we are querying, and a TextArea to display the results of the getInfo( ) call.

TCPServer Notes

Keep in mind that this is a single threaded server (that is, there’s only onethread handling clients). This means that only one client at a time may talkto the server. Any other clients will not receive a connection until after thecurrent client has been serviced. In a real server application, you would wantto be able to handle multiple clients simultaneously. For an example of howto do this, see the echoUDPServer example later in this chapter.

Another detail to remember is that Java’s security system will not let codeloaded over the network open a ServerSocket in an applet context. If yourapplet needs access to ServerSocket objects, it must be loaded from thelocal disk.

70

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 71/73

Load Detector

Using the DatagramSocket Class

Communicating with a DatagramSocket takes a different mindset from the TCP-based Socket and ServerSocket classes. Whereas the latter two classesfunction similarly to reading data from a file, the fixed-size messages of theUDP protocol are an entirely different matter. With a stream socket, youhave to provide some means of delineating the beginning and end of messages. But when you use UDP, each message arrives in its own discretepackage.

A Meager Beginning: The Echo Service

Our first example application using the DatagramSocket is to create a clientthat talks to a server process for the Echo Service. This service, defined inRFC 862, accepts connections through TCP and UDP. Whatever you send tothe server is copied and sent back verbatim. It is mainly a sanity-checkingmechanism. You can connect to the server and make sure that traffic isreaching the destination host.

The finished echoUDPCClient applet. 

Design

 This example will consist of two classes: a class to communicate with theecho server, and a subclass of Applet to provide a user interface.

 The first class, which we’ll call echoUDPClient, will handle all interaction withthe server. In order to display our status, the constructor will take areference to a java.awt.TextComponent. The constructor also will accept ahost name to connect to, defaulting to the local host if it is unavailable. Theclass will implement the Runnable interface so that the user interface cancontinue processing events. The run( ) method will perform the following

steps:

1. Allocate a DatagramSocket, and an InetAddress object for the host weare contacting.

2. Set a counter to zero.3. While the thread is running:4. A DatagramPacket to be sent to the destination host containing a

message This is packet #, with “#” being the current value of thecounter.

5. The send( ) method to transmit this packet to the destination.

6. Another DatagramPacket to receive the echo server’s reply.7. The receive( ) method to wait for the reply packet.

71

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 72/73

Load Detector

8. The reply into the TextContainer.9. The counter, and sleep for three seconds.10. The DatagramSocket.

 The second class, which will be called echoUDPApplet, will have three UIcomponents: a TextArea for the echoUDPClient to display its results in, aButton to stop the client object, and a second Button to start a newechoUDPClient object.

echoUDPClient Source

We’ll develop the client UDP class first. After the skeleton and constructors,the miscellaneous utility methods will be given. Next the methodsimplementing the Runnable interface and the run() method are shown.

Skeleton

We’ll start off the class with the requisite import statements. All of the I/Oand networking packages will be included, as well as the AWT TextComponent so that we know how to display results.

72

8/8/2019 Total Doc Load Detect

http://slidepdf.com/reader/full/total-doc-load-detect 73/73

Load Detector

BIBLIOGRAPHY 

1. THE COMPLETE REFERENCE JAVA 2.0 - PETER NAUGHTON.

2. THINKING IN JAVA - BRUCE ECKEL.

3. JAVA NETWORKING - OREILLY

4. JFC/SWING - OREILLY PUBLICATIONS.

5. SOFTWARE ENGINEERING - ROGER.S.PRESSMAN