Você está na página 1de 107




Submitted in the partial fulfillment of the requirement for the award of the degree of

Bachelor of Engineering In Computer Science Submitted By: Manali Gupta Priyanka Sharma Prateek Prakash Rahul D Raj
Under the Supervision of

Mr. Vivek Agrawal


This is to certify that the project entitled PHOENIX CHAT SERVER has been carried out by the team under my guidance in partial fulfillment of the degree of Bachelor of Engineering in Computer Engineering / Information Technology of Mangalayatan University, Aligarh during the academic year 2010-2011(Semester-VIII).


1. 2. 3. 4.

Manali Gupta Priyanka Sharma Prateek Prakash Rahul D Raj


Head, Computer Department

(Mr. Vivek Agrawal)

(Mr. Vikas Solanki)

External Examiner:



Before, we get into thick of things, we would like to add a few heartfelt words for all those people who were part of this report in numerous ways, and gave their unending support throughout. We wish to express our thanks and gratitude to all those who have provided the valuable support, insight and encouragement during our project work at Mangalayatan University. In the process of completing this project Phoenix Chat Server, we have received cooperation from many quarters. We express our sincere gratitude and indebtness to Mr. Vivek Agrawal, our project guide for his inspiring guidance, cooperation and for giving us an opportunity to enhance our skill and hence, carrying out our final year project successfully. We are thankful for his guidance, patience and consummate support. He came to our help when it counted and we extend our heartiest thanks to him for enlightening our path. Moreover, we would also like to acknowledge my profound sense of gratitude and indebtness for Mr. Vikas Solanki (H.O.D. Computer Science Department) for his cooperation, guidance, support and precious suggestions that motivated us in completing this project. We also feel grateful and elated in expressing our indebtedness to all those who have directly or indirectly helped us in accomplishing this research work.

Manali Gupta Priyanka Sharma Prateek Prakash Rahul D Raj

The Purpose of this Project Report is to understand the basic steps of Analysis, Design, and Implementation in my project. I have tried to comprehend the parameters and dimensions of the project at this stage. I have made use of the object based approach. I have made use of basic concepts of language Java, networking and relational database to understand the flow of Project. As we amble through the document, I can construe the major modules in the system, their relationships with each other, flow of events and messages between them and to understand the function of each module at the different states of project.

Page No. 1. Introduction About the project & its relevance JAVA Concepts Relational Database Overview 2. 3. 4. 5. System analysis Feasibility Analysis System Design System Requirement Hardware Requirements Software Requirements 6. Programming Approach Java o JFC o SWING o JAVA 2D Client & Server Architecture o Network Datagrams o Socket & Ports o Diagram Representation 7. Software Coding Chat Client GUI Chat Server GUI 8. 9. Snapshots Conclusions 92 101 68 59 29 31 33 36 7




General Concept of Chat Server:


CHAT SERVER is an online system developed for the group of members to communicate with each other over the internet. This system solves almost all the limitations of the conventional system. Both the students and teachers and the company are equally benefited by the proposed system. The system saves a lot of time and effort for both. Chat Server is an application through which end users, by the use of Chat client applications at their respective ends, can chat indirectly. We are introducing new software called CHAT SERVER for chatting purpose. We can say thoroughly that this software is very useful for the college. It is mainly designed for the college to reduce the communication gap between the different peoples in a college.

Benefits of using Chat Server:

Using this application remote communication between users is possible. The application is platform independent that is Operating System independent. Extremely large number of users can use this application. Interface is very user friendly. Communication is very fast. Front End application JAVA Back End applications Oracle 9i Networking

JFC is short for Java Foundation Classes, which encompass a group of features for building graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java applications. It is defined as containing the features shown in the table below. Features of the Java Foundation Classes Feature Description Includes everything from buttons to split panes to tables. Many components are capable of sorting, printing, and drag and drop, to name a few of the supported features.

Swing Components


The look and feel of Swing applications is pluggable, allowing a choice of look and feel. For example, the same program can use either the Java or the Windows look and Pluggable Lookfeel. Additionally, the Java platform supports the GTK+ and-Feel Support look and feel, which makes hundreds of existing look and feels available to Swing programs. Many more look-andfeel packages are available from various sources. Enables assistive technologies, such as screen readers and Braille displays, to get information from the user interface. Enables developers to easily incorporate high-quality 2D graphics, text, and images in applications and applets. Java 2D includes extensive APIs for generating and sending high-quality output to printing devices.

Accessibility API

Java 2D API

Internationalization Allows developers to build applications that can interact with users worldwide in their own languages and cultural 9

conventions. With the input method framework developers can build applications that accept text in languages that use thousands of different characters, such as Japanese, Chinese, or Korean. This trail concentrates on the Swing components. We help you choose the appropriate components for your GUI, tell you how to use them, and give you the background information you need to use them effectively. We also discuss other JFC features as they apply to Swing components. Swing text components display text and optionally allow the user to edit the text. Programs needed text components for tasks ranging from the straightforward (enter a word and press Enter) to the complex (display and edit styled text with embedded images in an Asian language). Swing provides six text components, along with supporting classes and interfaces that meet even the most complex text requirements. In spite of their different uses and capabilities, all Swing text components inherit from the same superclass, Jcomponent which provides a highly-configurable and powerful foundation for text manipulation. The following figure shows the JTextComponent hierarchy.


JDBC Introduction:
The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database. JDBC helps you to write java applications that manage these three programming activities: 1. Connect to a data source, like a database 2. Send queries and update statements to the database 3. Retrieve and process the results received from the database in answer to your query. The following simple code fragment gives a simple example of these three steps: Connection con = DriverManager.getConnection ( "jdbc:myDriver:wombat", "myLogin","myPassword"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1"); while (rs.next()) { int x = rs.getInt("a"); String s = rs.getString("b"); float f = rs.getFloat("c"); } This short code fragment instantiates a DriverManager object to connect to a database driver and log into the database, instantiates a Statement object that carries your SQL language query to the database; instantiates a ResultSet object that retrieves the results of your query, and executes a simple while loop, which retrieves and displays those results. It's that simple. 11

JDBC Product Components:

JDBC includes four components: 1. JDBC-API: The JDBC API provides programmatic access to relational data from the Java programming language. Using the JDBC API, applications can execute SQL statements, retrieve results, and propagate changes back to an underlying data source. The JDBC API can also interact with multiple data sources in a distributed, heterogeneous environment. The JDBC API is part of the Java platform, which includes the Java Standard Edition (Java SE ) and the Java Enterprise Edition (Java EE). The JDBC 4.0 API is divided into two packages: java.sql and javax.sql. Both packages are included in the Java SE and Java EE platforms. 2. JDBC-DRIVER-MANAGER: The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC architecture. It is quite small and simple. The Standard Extension packages javax.naming and javax.sql let you use a DataSource object registered with a Java Naming and Directory Interface (JNDI) naming service to establish a connection with a data source. You can use either connecting mechanism, but using a DataSource object is recommended whenever possible. 3. JDBC-TEST-SUITE: The JDBC driver test suite helps you to determine that JDBC drivers will run your program. These tests are not comprehensive or exhaustive, but they do exercise many of the important features in the JDBC API. 4. JDBC-ODBC-BRIDGE: The Java Software Bridge provides JDBC access via ODBC drivers. Note that you need to load ODBC binary code onto each client machine that uses this driver. As a result, the ODBC driver is most appropriate on a


corporate network where client installations are not a major problem, or for application server code written in Java in three-tier architecture. This Trail uses the first two of these four JDBC components to connect to a database and then build a java program that uses SQL commands to communicate with a test Relational Database. The last two components are used in specialized environments to test web applications, or to communicate with ODBC-aware DBMSs.

JDBC Architecture:
Two-tier and three-tier Processing Models The JDBC API supports both two-tier and three-tier processing models for database access.
Figure 1: Two-tier Architecture for Data Access.

In the two-tier model, a Java applet or application talks directly to the data source. This requires a JDBC driver that can communicate with the particular data source being accessed. A user's commands are delivered to the database or other data source, and the results of those statements are sent back to the user. The data source may be located on another machine to which the user is connected via a network. This is referred to as a client/server configuration, with the user's machine as the client, and the machine housing the data source as the server. The network can be an intranet, which, for example, connects employees within a corporation, or it can be the Internet. In the three-tier model, commands are sent to a "middle tier" of services, which then sends the commands to the data source. The data source processes the commands and sends the results back to the middle tier, which then sends them to the user. MIS directors find the three-tier model very attractive 13

because the middle tier makes it possible to maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is that it simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can provide performance advantages.
Figure 2: Three-tier Architecture for Data Access.

Until recently, the middle tier has often been written in languages such as C or C++, which offer fast performance. However, with the introduction of optimizing compilers that translate Java bytecode into efficient machinespecific code and technologies such as Enterprise JavaBeans, the Java platform is fast becoming the standard platform for middle-tier development. This is a big plus, making it possible to take advantage of Java's robustness, multithreading, and security features. With enterprises increasingly using the Java programming language for writing server code, the JDBC API is being used more and more in the middle tier of three-tier architecture. Some of the features that make JDBC a server technology are its support for connection pooling, distributed transactions, and disconnected row sets. The JDBC API is also what allows access to a data source from a Java middle tier.

Processes and Threads:

In concurrent programming, there are two basic units of execution: processes and threads. In the Java programming language, concurrent programming is mostly concerned with threads. However, processes are also important.


A computer system normally has many active processes and threads. This is true even in systems that only have a single execution core, and thus only have one thread actually executing at any given moment. Processing time for a single core is shared among processes and threads through an OS feature called time slicing. It's becoming more and more common for computer systems to have multiple processors or processors with multiple execution cores. This greatly enhances a system's capacity for concurrent execution of processes and threads but concurrency is possible even on simple systems, without multiple processors or execution cores.

An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays. Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways. No matter how they work internally, all streams present the same simple model to programs that use them: A stream is a sequence of data. A program uses an input stream to read data from a source, one item at a time:

DATA SOURCE 0011010000 1001000011 1001010101 1001010101 PROGRAM


A program uses an output stream to write data to a destination, one item at time: STREAM


0011010000 1001000011 1001010101 DATA DESTINATION

Basic Input and Output Classes:

The java.io package contains a fairly large number of classes that deal with Java input and output. Most of the classes consist of: * Byte streams that are subclasses of InputStream or OutputStream * Character streams that are subclasses of Reader and Writer The Reader and Writer classes read and write 16-bit Unicode characters. InputStream reads 8-bit bytes, while OutputStream writes 8-bit bytes. As their class name suggests, ObjectInputStream and ObjectOutputStream transmit entire objects. ObjectInputStream reads objects; ObjectOutputStream writes objects. Unicode is an international standard character encoding that is capable of representing most of the world's written languages. In Unicode, two bytes make a character. Using the 16-bit Unicode character streams makes it easier to internationalize your code. As a result, the software is not dependent on one single encoding.

Creating Streams:
Here is an example of how to create a stream that reads and writes characters using a TCP/IP socket as the sink and source. The classes themselves are explained later. 16

First, we create a TCP/IP socket object that is connected to www.ibm.com and port 80. This is the Web server port. The method getInputStream() in the Socket class returns an InputStream, which represents byte-by-byte reading of the socket. The InputStream is used to create an InputStreamReader, which transforms the bytes read from the socket into characters. A BufferedReader class is created which reads from the InputStreamReader and buffers the characters into its own internal buffer. The object named in then reads characters from that buffer, but the ultimate source of the characters is the Web server at www.ibm.com. On the other hand, the getOutputStream() method of the Socket class returns a reference to an OutputStream, which writes a byte at a time. The PrinterWriter constructor uses that OutputStream as the sink for the characters it writes out. When a character is written to the object named out, it is ultimately sent to the Web server atwww.ibm.com. This example treats the data stream as character data: Socket a_socket = new Socket (www.ibm.com, 80); InputStreamReader isr = new InputStreamReader (a_socket.getInputStream ());

Data Input and Data Output:

The DataInput and DataOutput classes define the methods required for streams that can read Java primitive data types in a machine-independent binary format. They are implemented by Random Access File. The ObjectInput interface extends the DataInput interface and adds methods for deserializing objects and reading bytes and arrays of bytes. You can learn more about serialization in Object serialization on page 46. The ObjectOutputStream class creates a stream of objects that can be deserialized by the ObjectInputStream class. The ObjectOutput interface extends the DataOutput interface and adds methods for serializing objects and writing bytes and arrays of bytes. ObjectOutputStream is used to serialize objects, arrays, and other values to a stream.


Data I/O:
This section introduces data input and output: * DataInputStream * DataOutputStream Several classes implement the DataInput and DataOutput interfaces. Let's talk about how they work. The primitive data types, such as ints, may be represented differently on the various platforms that Java code runs on. For example, an int may be represented with the most significant byte first (called Big Endian), as on an IBM mainframe, or with the least significant byte first (called Little Endian), as on an IBM PC. If you wrote out an int in binary form with a C program on one platform and tried to read it in on the other platform, the values would not agree. That's where DataInput and DataOutput come in. Now you can take a primitive, like an int, and write it out. It is written in a platform-independent form. You can read that int back in on any other Java virtual machine and, regardless of where it was produced; it will be turned back into an int of the proper value. All the primitives, such as doubles, ints, shorts, longs, and so forth, can be written in a system platform-independent manner using the methods in DataOutput. Likewise, they can be read using the methods in DataInput.

Unicode Text Format:

A String object is written in Unicode Text Format or UTF for short. Strings are composed of two-byte Unicode characters. UTF is a method forcompressing the most common Unicode values. If the String contains just ASCII characters, the values between 1 and 127 are written as a single byte. Values 128 - 2047 are written as two bytes. For some uncommon Unicode values, three bytes are used to represent their value. This expansion of some values is much rarer than the compression of ASCII values, so using UTF to represent a String is a net gain.


Data InputStream and Data OutputStream:

Two classes, DataInputStream and DataOutputStream, implement DataInput and DataOutput. Their methods include implementations for readInt(), writeInt(), and the other methods in the interfaces. You wrapper a DataInputStream around an InputStream. When readInt() is called, four bytes are read from the underlying stream and the resulting int is returned. Correspondingly, you wrapper a DataOutputStream around an OutputStream. The code example below shows a DataOutputStream that uses a FileOutputStream as its underlying stream. The file is opened using a FileInputStream, which has a DataInputStream wrappered around it. The data.dat could be written on an IBM mainframe and read.



A database is a means of storing information in such a way that information can be retrieved from it. In simplest terms, a relational database is one that presents information in tables with rows and columns. A table is referred to as a relation in the sense that it is a collection of objects of the same type (rows). Data in a table can be related according to common keys or concepts, and the ability to retrieve related data from a table is the basis for the term relational database. A Database Management System (DBMS) handles the way data is stored, maintained, and retrieved. In the case of a relational database, a Relational Database Management System (RDBMS) performs these tasks. DBMS as used in this book is a general term that includes RDBMS.

Integrity Rules:
Relational tables follow certain integrity rules to ensure that the data they contain stay accurate and are always accessible. First, the rows in a relational table should all be distinct. If there are duplicate rows, there can be problems resolving which of two possible selections is the correct. For most DBMSs, the user can specify that duplicate rows are not allowed, and if that is done, the DBMS will prevent the addition of any rows that duplicate an existing row. A second integrity rule of the traditional relational model is that column values must not be repeating groups or arrays. A third aspect of data integrity involves the concept of a null value. A database takes care of situations where data may not be available by using a null value to indicate that a value is missing. It does not equate to a blank or zero. A blank is considered equal to another blank, a zero is equal to another zero, but two null values are not considered equal. When each row in a table is different, it is possible to use one or more columns to identify a particular row. This unique column or group of columns is called a primary key. Any column that is part of a primary key cannot be null; if it were, the primary key containing it would no longer be a complete identifier. This rule is referred to as entity integrity.


Table illustrates some of these relational database concepts. It has five columns and six rows, with each row representing a different employee. Table: Employees Employee_Number First_name Last_Name Date_of_Birth Car_Number 10001 10083 10120 10005 10099 10035 Axel Arvid Jonas Florence Sean Elizabeth Washington Sharma Ginsberg Wojokowski Washington Yamaguchi 28-Aug-43 24-Nov-54 01-Jan-69 04-Jul-71 21-Sep-66 24-Dec-59 5 null null 12 null null

The primary key for this table would generally be the employee number because each one is guaranteed to be different. (A number is also more efficient than a string for making comparisons.) It would also be possible to use First_Name and Last_Name because the combination of the two also identifies just one row in our sample database. Using the last name alone would not work because there are two employees with the last name of "Washington." In this particular case the first names are all different, so one could conceivably use that column as a primary key, but it is best to avoid using a column where duplicates could occur. If Elizabeth Taylor gets a job at this company and the primary key is First_Name, the RDBMS will not allow her name to be added (if it has been specified that no duplicates are permitted). Because there is already an Elizabeth in the table, adding a second one would make the primary key useless as a way of identifying just one row. Note that although using First_Name and Last_Name is a unique composite key for this example, it might not be unique in a larger database. Note also that Table 1.2 assumes that there can be only one car per employee.


SELECT Statements:
SQL is a language designed to be used with relational databases. There is a set of basic SQL commands that is considered standard and is used by all RDBMSs. For example, all RDBMSs use the SELECT statement. A SELECT statement, also called a query, is used to get information from a table. It specifies one or more column headings, one or more tables from which to select, and some criteria for selection. The RDBMS returns rows of the column entries that satisfy the stated requirements. A SELECT statement such as the following will fetch the first and last names of employees who have company cars: SELECT First_Name, Last_Name FROM Employees WHERE Car_Number IS NOT NULL The result set (the set of rows that satisfy the requirement of not having null in the Car_Number column) follows. The first name and last name are printed for each row that satisfies the requirement because the SELECT statement (the first line) specifies the columns First_Name and Last_Name. The FROM clause (the second line) gives the table from which the columns will be selected. FIRST_NAME -------------------Axel Florence LAST_NAME ------------------Washington Wojokowski

The following code produces a result set that includes the whole table because it asks for all of the columns in the table Employees with no restrictions (no WHERE clause). Note that SELECT * means "SELECT all columns." SELECT * FROM Employees


WHERE Clauses:
WHERE clause in SELECT statement provides the criteria for selecting values. For example, in the following code fragment, values will be selected only if they occur in a row in which the column Last_Name begins with the string 'Washington'. SELECT First_Name, Last_Name FROM Employees WHERE Last_Name LIKE 'Washington%' The keyword LIKE is used to compare strings, and it offers the feature that patterns containing wildcards can be used. For example, in the code fragment above, there is a percent sign (%) at the end of 'Washington', which signifies that any value containing the string 'Washington' plus zero or more additional characters will satisfy this selection criterion. So 'Washington' or 'Washingtonian' would be matches, but 'Washing' would not be. The other wildcard used in LIKE clauses is an underbar (_), which stands for any one character. For example, WHERE Last_Name LIKE 'Ba_man' would match 'Batman', 'Barman', 'Badman', 'Balman', 'Bagman', 'Bamman', and so on. The code fragment below has a WHERE clause that uses the equal sign (=) to compare numbers. It selects the first and last name of the employee who is assigned car 12. SELECT First_Name, Last_Name FROM Employees WHERE Car_Number = 12 The next code fragment selects the first and last names of employees whose employee number is greater than 10005: SELECT First_Name, Last_Name FROM Employees WHERE Employee_Number > 10005


WHERE clauses can get rather elaborate with multiple conditions and in some DBMSs or in nested conditions. This overview will not cover complicated WHERE clauses, but the following code fragment has a WHERE clause with two conditions; this query selects the first and last names of employees whose employee number is less than 10100 and who do not have a company car. SELECT First_Name, Last_Name FROM Employees WHERE Employee_Number < 10100 and Car_Number IS NULL

A distinguishing feature of relational databases is that it is possible to get data from more than one table in what is called a join. Suppose that after retrieving the names of employees who have company cars, one wanted to find out who has which car, including the make, model, and year of car. This information is stored in another table, Cars, shown in Table 1.3. Table: Cars Car Number 5 12 Make Honda Toyota Model Civic DX Corolla Year 1996 1999

There must be one column that appears in both tables in order to relate them to each other. This column, which must be the primary key in one table, is called the foreign key in the other table. In this case, the column that appears in two tables is Car_Number, which is the primary key for the table Cars and the foreign key in the table Employees. If the 1996 Honda Civic were wrecked and deleted from the Cars table, then Car_Number 5 would also have to be removed from the Employees table in order to maintain what is called referential integrity. Otherwise, the foreign key column (Car_Number) in Employees would contain an entry that did not refer to anything in Cars. A foreign key must either be null or equal to an existing primary key value of the table to which it refers. This is different from a primary key, which may not be 24

null. There are several null values in the Car_Number column in the table Employees because it is possible for an employee not to have a company car. The following code asks for the first and last names of employees who have company cars and for the make, model, and year of those cars. Note that the FROM clause lists both Employees and Cars because the requested data is contained in both tables. Using the table name and a dot (.) before the column name indicates which table contains the column. SELECT Employees.First_Name, Employees.Last_Name, Cars.Make, Cars.Model, Cars.Year FROM Employees, Cars WHERE Employees.Car_Number = Cars.Car_Number This returns a result set that will look similar to the following: FIRST_NAME LAST_NAME ------------------- ------------------Axel Washington Florence Wojokowski MAKE MODEL YEAR --------------------- --------Honda CivicDX 1996 Toyota Corolla 1999

Common SQL Commands:

SQL commands are divided into categories, the two main ones being Data Manipulation Language (DML) commands and Data Definition Language (DDL) commands. DML commands deal with data, either retrieving it or modifying it to keep it up-to-date. DDL commands create or change tables and other database objects such as views and indexes. A list of the more common DML commands follows:

SELECT - used to query and display data from a database. The SELECT statement specifies which columns to include in the result set. The vast majority of the SQL commands used in applications are SELECT statements. INSERT - adds new rows to a table. INSERT is used to populate a newly created table or to add a new row (or rows) to an already-existing table. 25

DELETE - removes a specified row or set of rows from a table UPDATE - changes an existing value in a column or group of columns in a table

The more common DDL commands follow:

CREATE TABLE - creates a table with the column names the user provides. The user also needs to specify a type for the data in each column. Data types vary from one RDBMS to another, so a user might need to use metadata to establish the data types used by a particular database. CREATE TABLE is normally used less often than the data manipulation commands because a table is created only once, whereas adding or deleting rows or changing individual values generally occurs more frequently. DROP TABLE - deletes all rows and removes the table definition from the database. A JDBC API implementation is required to support the DROP TABLE command as specified by SQL92, Transitional Level. However, support for the CASCADE and RESTRICT options of DROP TABLE is optional. In addition, the behavior of DROP TABLE is implementationdefined when there are views or integrity constraints defined that reference the table being dropped. ALTER TABLE - adds or removes a column from a table. It also adds or drops table constraints and alters column attributes.

Result Sets and Cursors:

The rows that satisfy the conditions of a query are called the result set. The number of rows returned in a result set can be zero, one, or many. A user can access the data in a result set one row at a time, and a cursor provides the means to do that. A cursor can be thought of as a pointer into a file that contains the rows of the result set, and that pointer has the ability to keep track of which row is currently being accessed. A cursor allows a user to process each row of a result set from top to bottom and consequently may be used for iterative processing. Most DBMSs create a cursor automatically when a result set is generated.


Earlier JDBC API versions added new capabilities for a result set's cursor, allowing it to move both forward and backward and also allowing it to move to a specified row or to a row whose position is relative to another row.

When one user is accessing data in a database, another user may be accessing the same data at the same time. If, for instance, the first user is updating some columns in a table at the same time the second user is selecting columns from that same table, it is possible for the second user to get partly old data and partly updated data. For this reason, DBMSs use transactions to maintain data in a consistent state (data consistency) while allowing more than one user to access a database at the same time (data concurrency). A transaction is a set of one or more SQL statements that make up a logical unit of work. A transaction ends with either a commit or a rollback, depending on whether there are any problems with data consistency or data concurrency. The commit statement makes permanent the changes resulting from the SQL statements in the transaction, and the rollback statement undoes all changes resulting from the SQL statements in the transaction. A lock is a mechanism that prohibits two transactions from manipulating the same data at the same time. For example, a table lock prevents a table from being dropped if there is an uncommitted transaction on that table. In some DBMSs, a table lock also locks all of the rows in a table. A row lock prevents two transactions from modifying the same row, or it prevents one transaction from selecting a row while another transaction is still modifying it.

Stored Procedures:
A stored procedure is a group of SQL statements that can be called by name. In other words, it is executable code, a mini-program that performs a particular task that can be invoked the same way one can call a function or method. Traditionally, stored procedures have been written in a DBMS-specific programming language. The latest generation of database products allows stored procedures to be written using the Java programming language and the JDBC API. Stored procedures written in the Java programming language are 27

bytecode portable between DBMSs. Once a stored procedure is written, it can be used and reused because a DBMS that supports stored procedures will, as its name implies, store it in the database.

Databases store user data, and they also store information about the database itself. Most DBMSs have a set of system tables, which list tables in the database, column names in each table, primary keys, foreign keys, stored procedures, and so forth. Each DBMS has its own functions for getting information about table layouts and database features. JDBC provides the interface DatabaseMetaData, which a driver writer must implement so that its methods return information about the driver and/or DBMS for which the driver is written. For example, a large number of methods return whether or not the driver supports a particular functionality. This interface gives users and tools a standardized way to get metadata. In general, developers writing tools and drivers are the ones most likely to be concerned with metadata.





System Analysis is a detailed study of the various operations performed by a system and their relationships within and outside of the system. Here the key question isWhat all problems exist in the present system? What must be done to solve the problem? Analysis begins when a user or manager begins a study of the program using existing system. During analysis, data collected on the various files, decision points and transactions handled by the present system. The commonly used tools in the system are Data Flow Diagram, interviews, etc. Training, experience and common sense are required for collection of relevant information needed to develop the system. The success of the system depends largely on how clearly the problem is defined, thoroughly investigated and properly carried out through the choice of solution. A good analysis model should provide not only the mechanisms of problem understanding but also the frame work of the solution. Thus it should be studied thoroughly by collecting data about the system. Then the proposed system should be analyzed thoroughly in accordance with the needs. System analysis can be categorized into four parts. System planning and initial investigation Information Gathering Applying analysis tools for structured analysis Feasibility study Cost/ Benefit analysis





Whatever we think need not be feasible .It is wise to think about the feasibility of any problem we undertake. Feasibility is the study of impact, which happens in the organization by the development of a system. The impact can be either positive or negative. When the positives nominate the negatives, then the system is considered feasible. Here the feasibility study can be performed in two ways such as technical feasibility and Economical Feasibility.

Technical Feasibility: We can strongly say that it is technically feasible, since

there will not be much difficulty in getting required resources for the development and maintaining the system as well. All the resources needed for the development of the software as well as the maintenance of the same is available in the organization here we are utilizing the resources which are available already.

Economical Feasibility: Development of this application is highly

economically feasible .The organization needed not spend much m money for the development of t he system already available. The only thing is to be done is making an environment for the development with an effective supervision. If we are doing so, we can attain the maximum usability of the corresponding resources. Even after the development, the organization will not be in a condition to invest more in the organization. Therefore, the system is economically feasible.





Input design is the process of converting user-oriented input to a computer based format. Input design is a part of overall system design, which requires very careful attention .Often the collection of input data is the most expensive part of the system. The main objectives of the input design are: Produce cost effective method of input Achieve highest possible level of accuracy Ensure that the input is acceptable to and understood by the staff.

Input Data:
The goal of designing input data is to make entry easy, logical and free from errors as possible. The entering data entry operators need to know the allocated space for each field; field sequence and which must match with that in the source document. The format in which the data fields are entered should be given in the input form. Here data entry is online; it makes use of processor that accepts commands and data from the operator through a keyboard. The input required is analyzed by the processor. It is then accepted or rejected. Input stages include the following processes: Data Recording Data Transcription Data Conversion Data Verification Data Control Data Transmission Data Correction


One of the aims of the system analyst must be to select data capture method and devices, which reduce the number of stages so as to reduce both the changes of errors and the cost. Input types, can be characterized as: External Internal Operational Computerized Interactive

Input files can exist in document form before being input to the computer. Input design is rather complex since it involves procedures for capturing data as well as inputting it to the computer.

Outputs from computer systems are required primarily to communicate the results of processing to users. They are also used to provide a permanent copy of this result for latter consultation. Computer output is the most important and direct source of information to the users. Designing computer output should proceed in an organized well throughout the manner. The right output must be available for the people who find the system easy o use. The outputs have been defined during the logical design stage. If not, they should defined at the beginning of the output designing terms of types of output connect, format, response etc. Various types of outputs are: External outputs Internal outputs Operational outputs Interactive outputs Turn around outputs

All screens are informative and interactive in such a way that the user can fulfill his requirements through asking queries.





This management system can be used in Microsoft Windows 98, Windows 2000, Windows NT, Windows XP, Windows Vista, Windows 7, supported for other platform such as Macintosh and UNIX. The system must be running Windows 98, Windows 98 or Windows NT4.0 operating system and must meet the following hardware requirements. For Windows 95 based computers, a 486/66MHz or higher processor with 8MB For Windows 98 based computers, a 500/88MHz or higher processor with 32 MB of RAM For Windows NT based computers, a 488 / 66 MHz or higher processor with 16 MB of RAM For Windows 200 based computers, a 700/850 MHz or higher processor with 512 MB of Ram And so on.


Hardware Requirements:

Processor RAM Hard Disk Display Keyboard

: : : : :

Pentium III 630MHz or above. Minimum 128 MB Minimum 20GB 15 Color monitor 122 Keys

Software Requirements:

Operating System Language

: Windows 98 or above. : Java 2 Runtime Environment





Java is a programming language originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Java is a general-purpose, concurrent, class-based, object-oriented language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere". Java is currently one of the most popular programming languages in use, and is widely used from application software to web applications. The original and reference implementation Java compilers, virtual machines, and class libraries were developed by Sun from 1995. As of May 2007, in compliance with the specifications of the Java Community Process, Sun relicensed most of its Java technologies under the GNU General Public License. Others have also developed alternative implementations of these Sun technologies, such as the GNU Compiler for Java, GNU Classpath, and Dalvik. Compared to other programming languages, Java are most similar to C. C++ certainly helps us to learn Java more quickly, but you don't need to know C to learn Java. Unlike C++ Java is not a superset of C. What's most special about Java in relation to other programming languages is that it lets you write special programs called applets that can be downloaded from the Internet and played safely within a web browser. Traditional computer programs have far too much access to your system to be downloaded and executed willy-nilly. Although you generally trust the maintainers of various ftp archives and bulletin boards to do basic virus


checking and not to post destructive software, a lot still slips through the cracks. Even more dangerous software would be promulgated if any web page you visited could run programs on your system. You have no way of checking these programs for bugs or for out-and-out malicious behavior before downloading and running them. Java solves this problem by severely restricting what an applet can do. A Java applet cannot write to your hard disk without your permission. It cannot write to arbitrary addresses in memory and thereby introduce a virus into your computer. It should not crash your system.

Principles of Java language:

There were five primary goals in the creation of the Java language: It should be "simple, object oriented and familiar". It should be "robust and secure". It should have "an architecture-neutral and portable environment". It should execute with "high performance". It should be "interpreted, threaded, and dynamic".

Java Platform:
One characteristic of Java is portability, which means that computer programs written in the Java language must run similarly on any supported hardware/operating-system platform. This is achieved by compiling the Java language code to an intermediate representation called Java bytecode, instead of directly to platform-specific machine code. Java bytecode instructions are analogous to machine code, but are intended to be interpreted by a virtual machine (VM) written specifically for the host hardware. End-users commonly use a Java Runtime Environment (JRE) installed on their own machine for standalone Java applications, or in a Web browser for Java applets.


Standardized libraries provide a generic way to access host-specific features such as graphics, threading, and networking. A major benefit of using bytecode is porting. However, the overhead of interpretation means that interpreted programs almost always run more slowly than programs compiled to native executables would. Just-in-Time compilers were introduced from an early stage that compiles bytecode to machine code during runtime.

Sun Microsystems officially licenses the Java Standard Edition platform for Linux, Mac OS X, and Solaris. Although in the past Sun has licensed Java to Microsoft, the license has expired and has not been renewed. Through a network of third-party vendors and licensees, alternative Java environments are available for these and other platforms. Sun's trademark license for usage of the Java brand insists that all implementations be "compatible". This resulted in a legal dispute with Microsoft after Sun claimed that the Microsoft implementation did not support RMI or JNI and had added platform-specific features of their own. Sun sued in 1997 and in 2001 won a settlement of US$20 million, as well as a court order enforcing the terms of the license from Sun. As a result, Microsoft no longer ships Java with Windows, and in recent versions of Windows, Internet Explorer cannot support Java applets without a third-party plug-in. Sun, and others, has made available free Java run-time systems for those and other versions of Windows. Platform-independent Java is essential to the Java EE strategy, and an even more rigorous validation is required to certify an implementation. This environment enables portable server-side applications, such as Web services, Java Servlets, and Enterprise JavaBeans, as well as with embedded systems based on OSGi, using Embedded Java environments. Through the new GlassFish project, Sun is working to create a fully functional, unified open source implementation of the Java EE technologies. 42

Sun also distributes a superset of the JRE called the Java Development Kit (commonly known as the JDK), which includes development tools such as the Java compiler, Javadoc, Jar, and debugger.

Programs written in Java have a reputation for being slower and requiring more memory than those written in C. However, Java programs' execution speed improved significantly with the introduction of Just-in-time compilation in 1997/1998 for Java 1.1, the addition of language features supporting better code analysis (such as inner classes, StringBuffer class, optional assertions, etc.), and optimizations in the Java Virtual Machine itself, such as HotSpot becoming the default for Sun's JVM in 2000. Currently, Java code has approximately half the performance of C code. Some platforms offer direct hardware support for Java; there are microcontrollers that can run java in hardware instead of a software JVM, and ARM based processors can have hardware support for executing Java bytecode through its Jazelle option.

Automatic Memory Management:

Java uses an automatic garbage collector to manage memory in the object lifecycle. The programmer determines when objects are created, and the Java runtime is responsible for recovering the memory once objects are no longer in use. Once no references to an object remain, the unreachable memory becomes eligible to be freed automatically by the garbage collector. Something similar to a memory leak may still occur if a programmer's code holds a reference to an object that is no longer needed, typically when objects that are no longer needed are stored in containers that are still in use. If methods for a nonexistent object are called, a "null pointer exception" is thrown. One of the ideas behind Java's automatic memory management model is that programmers can be spared the burden of having to perform manual memory management. In some languages, memory for the creation of objects is implicitly allocated on the stack, or explicitly allocated and de-allocated from the heap. 43

In the latter case the responsibility of managing memory resides with the programmer. If the program does not de-allocate an object, a memory leak occurs. If the program attempts to access or de-allocate memory that has already been de-allocated, the result is undefined and difficult to predict, and the program is likely to become unstable and/or crash. This can be partially remedied by the use of smart pointers, but these add overhead and complexity. Note that garbage collection does not prevent "logical" memory leaks, i.e. those where the memory is still referenced but never used. Garbage collection may happen at any time. Ideally, it will occur when a program is idle. It is guaranteed to be triggered if there is insufficient free memory on the heap to allocate a new object; this can cause a program to stall momentarily. Explicit memory management is not possible in Java. Java does not support C/C++ style pointer arithmetic, where object addresses and unsigned integers (usually long integers) can be used interchangeably. This allows the garbage collector to relocate referenced objects and ensures type safety and security. As in C++ and some other object-oriented languages, variables of Java's primitive data types are not objects. Values of primitive types are either stored directly in fields (for objects) or on the stack (for methods) rather than on the heap, as commonly true for objects (but see Escape analysis). This was a conscious decision by Java's designers for performance reasons. Because of this, Java was not considered to be a pure object-oriented programming language. However, as of Java 5.0, autoboxing enables programmers to proceed as if primitive types were instances of their wrapper class. Java contains multiple types of garbage collectors. By default, HotSpot uses the Concurrent Mark Sweep collector, also known as the CMS Garbage Collector. However, there are also several other garbage collectors that can be used to manage the Heap. For 90% of applications in Java, the CMS Garbage Collector is good enough.


The syntax of Java is largely derived from C++. Unlike C++, which combines the syntax for structured, generic, and object-oriented programming, Java was built almost exclusively as an object-oriented language. All code is written inside a class, and everything is an object, with the exception of the primitive data types (integers, floating-point numbers, boolean values, and characters), which are not classes for performance reasons. Unlike C++, Java does not support operator overloading and multiple inheritance for classes in order to simplify the language and to prevent possible errors and anti-pattern design. Java uses similar commenting methods to C++. There are three different styles of comment: a single line style marked with two slashes (//), a multiple line style opened with a slash asterisk (/*) and closed with an asterisk slash (*/), and the Javadoc commenting style opened with a slash and two asterisks (/**) and closed with an asterisk slash (*/). The Javadoc style of commenting allows the user to run the Javadoc executable to compile documentation for the program.



Using the Java programming language, Java Foundation Classes (JFC) are prewritten code in the form of class libraries (coded routines) that give the programmer a comprehensive set of graphical user interface (GUI) routines to use. The Java Foundation Classes are comparable to the Microsoft Foundation Class (MFC) library. JFC is an extension of the original Java Abstract Windowing Toolkit (AWT). JFC is short for Java Foundation Classes, which encompass a group of features for building graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java applications. JFC consists of the Abstract Window Toolkit (AWT), Swing and Java 2D. Together, they provide a consistent user interface for Java programs, regardless whether the underlying user interface system is Windows, Mac OS X or Linux.

Features of the Java Foundation Classes:

The JFC is combinations of AWT, Swing and Java 2D. The descriptions about these are given below: The Abstract Window Toolkit (AWT) is Java's original platform-independent windowing, graphics, and user-interface widget toolkit. The AWT is now part of the Java Foundation Classes (JFC) the standard API for providing a graphical user interface (GUI) for a Java program. AWT is also the GUI toolkit for a number of Java ME profiles. For example, Connected Device Configuration profiles require Java runtimes on mobile telephones to support AWT. Architecture The AWT provides two levels of APIs: A general interface between Java and the native system used for windowing, events and layout managers. This API is at the core of Java GUI programming and is also used by Swing and Java 2D. 46

It contains: The interface between the native windowing system and the Java application; The core of the GUI event subsystem; Several layout managers; The interface to input devices such as mouse and keyboard; and A java.awt.datatransfer package for use with the Clipboard and Drag and Drop. AWT also makes some higher level functionality available to applications, such as: Access to the system tray on supporting systems; and The ability to launch some desktop applications such as web browsers and email clients from a Java application. Neither AWT nor Swing are inherently thread safe. Therefore, code that updates the GUI or processes events should execute on the Event dispatching thread. Failure to do so may result in a deadlock or race condition. To address this problem, a utility class called SwingWorker allows applications to perform time-consuming tasks following user-interaction events in the event dispatching thread.

As AWT is a bridge to the underlying native user interface, its implementation on a new operating system may involve a lot of work, especially for the set of AWT GUI widgets, which require the development from scratch of native peers for each of the AWT widgets. Since the opening of Java, a project called Caciocavallo has been created. It aims to provide a Java API based on the OpenJDK to ease AWT implementation on new systems.. The project has successfully experimented the implementation of AWT widgets using Java2D. All the needed core JDK modifications have since been pushed on OpenJDK 7.


Swing is the primary Java GUI widget toolkit. It is part of Sun Microsystems' Java Foundation Classes (JFC) an API for providing a graphical user interface (GUI) for Java programs. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit. Swing provides a native look and feel that emulates the look and feel of several platforms, and also supports a pluggable look and feel that allows applications to have a look and feel unrelated to the underlying platform.

The Swing Architecture:

Swing is a platform-independent, Model-View-Controller GUI framework for Java. It follows a single-threaded programming model, and possesses the following traits:

Foundations- Swing is platform independent both in terms of expression

(Java) and implementation (Look-and-Feel).

Extensible- Swing is a highly partitioned architecture, which allows for the

"plugging" of various custom implementations of specified framework interfaces: Users can provide their own custom implementation(s) of these components to override the default implementations. In general, Swing users can extend the framework by extending existing (framework) classes and/or providing alternative implementations of core components. Swing is a component-based framework. The distinction and components is a fairly subtle point: concisely, a component is a well-behaved object with a known/specified characteristic pattern of behavior. Swing objects asynchronously fire events, have "bound" properties, and respond to a wellknown set of commands (specific to the component.) Specifically, Swing components are Java Beans components, compliant with the Java Beans Component Architecture specifications.


Customizable- Given the programmatic rendering model of the Swing

framework, fine control over the details of rendering of a component is possible in Swing. As a general pattern, the visual representation of a Swing component is a composition of a standard set of elements, such as a "border", "inset", decorations, etc. Typically, users will programmatically customize a standard Swing component (such as a JTable) by assigning specific Borders, Colors, Backgrounds, opacities, etc., as the properties of that component. The core component will then use these properties (settings) to determine the appropriate renderers to use in painting its various aspects. However, it is also completely possible to create unique GUI controls with highly customized visual representation.

Configurable- Swing's heavy reliance on runtime mechanisms and indirect

composition patterns allows it to respond at runtime to fundamental changes in its settings. For example, a Swing-based application can change its look and feel at runtime. Further, users can provide their own look and feel implementation, which allows for uniform changes in the look and feel of existing Swing applications without any programmatic change to the application code.

Lightweight UI- Swing's configurability is a result of a choice not to use the

native host OS's GUI controls for displaying itself. Swing "paints" its controls programmatically through the use of Java 2D APIs, rather than calling into a native user interface toolkit. Thus, a Swing component does not have a corresponding native OS GUI component, and is free to render itself in any way that is possible with the underlying graphics APIs. However, at its core every Swing component relies on an AWT container, since (Swing's) JComponent extends (AWT's) Container. This allows Swing to plug into the host OS's GUI management framework, including the crucial device/screen mappings and user interactions, such as key presses or mouse movements. Swing simply "transposes" its own (OS agnostic) semantics over the underlying (OS specific) components. So, for example, every Swing component paints its rendition on the graphic device in response to a call to component.paint(), which is defined in (AWT) Container. But unlike AWT


components, which delegated the painting to their OS-native "heavyweight" widget, Swing components are responsible for their own rendering. This transposition and decoupling is not merely visual, and extends to Swing's management and application of its own OS-independent semantics for events fired within its component containment hierarchies. Generally speaking, the Swing Architecture delegates the task of mapping the various flavors of OS GUI semantics onto a simple, but generalized, pattern to the AWT container. Building on that generalized platform, it establishes its own rich and complex GUI semantics in the form of the JComponent model.

Loosely-Coupled and MVC- The Swing library makes heavy use of the
Model/View/Controller software design pattern, which conceptually decouples the data being viewed from the user interface controls through which it is viewed. Because of this, most Swing components have associated models (which are specified in terms of Java interfaces), and the programmer can use various default implementations or provide their own. The framework provides default implementations of model interfaces for all of its concrete components. The typical use of the Swing framework does not require the creation of custom models, as the framework provides a set of default implementations that are transparently, by default, associated with the corresponding JComponent child class in the Swing library. In general, only complex components, such as tables, trees and sometimes lists, may require the custom model implementations around the application-specific data structures. To get a good sense of the potential that the Swing architecture makes possible, consider the hypothetical situation where custom models for tables and lists are wrappers over DAO and/or EJB services. Typically, Swing component model objects are responsible for providing a concise interface defining events fired, and accessible properties for the (conceptual) data model for use by the associated JComponent. Given that the overall MVC pattern is a loosely-coupled collaborative object relationship pattern, the model provides the programmatic means for attaching event listeners to the data model object. Typically, these events are model centric (ex: a "row inserted" event in a table model) and are mapped by the JComponent specialization into a meaningful event for the GUI component. 50

For example, the JTable has a model called TableModel that describes an interface for how a table would access tabular data. A default implementation of this operates on a two-dimensional array. The view component of a Swing JComponent is the object used to graphically "represent" the conceptual GUI control. A distinction of Swing, as a GUI framework, is in its reliance on programmatically-rendered GUI controls (as opposed to the use of the native host OS's GUI controls). Prior to Java 6 Update 10, this distinction was a source of complications when mixing AWT controls, which use native controls, with Swing controls in a GUI (see Mixing AWT and Swing components). Finally, in terms of visual composition and management, Swing favors relative layouts (which specify the positional relationships between components) as opposed to absolute layouts (which specify the exact location and size of components). This bias towards "fluid"' visual ordering is due to its origins in the applet operating environment, that frame the design and development of the original Java GUI toolkit. (Conceptually, this view of the layout management is quite similar to that which informs the rendering of HTML content in browsers, and addresses the same set of concerns that motivated the former.)

Relationship to AWT:
AWT and Swing Class Hierarchy Since early versions of Java, a portion of the Abstract Window Toolkit (AWT) has provided platform-independent APIs for user interface components. In AWT, each component is rendered and controlled by a native peer component specific to the underlying windowing system. By contrast, Swing components are often described as lightweight because they do not


require allocation of native resources in the operating system's windowing toolkit. The AWT components are referred to as heavyweight components. Much of the Swing API is generally a complementary extension of the AWT rather than a direct replacement. In fact, every Swing lightweight interface ultimately exists within an AWT heavyweight component because all of the top-level components in Swing (JApplet, JDialog, JFrame, and JWindow) extend an AWT top-level container. Prior to Java 6 Update 10, the use of both lightweight and heavyweight components within the same window was generally discouraged due to Z-order incompatibilities. However, later versions of Java have fixed these issues, and both Swing and AWT components can now be used in one GUI without Z-order issues. The core rendering functionality used by Swing to draw its lightweight components is provided by Java 2D, another part of JFC. The following interfaces and its descriptions to be used by the Java swing. Action This interface performed the action with the ActionListener where the multiple controls are used for same purposes BoundedRangeModel This interface defines the data model of components like: sliders and progressBars. ButtonModel It defines the state model for the buttons like: radio buttons, check boxes etc. CellEditor This interface used by the developer for creating the new editor and it has the new components implement interfaces. The CellEditor implements the wrapper based approach. ComboBoxEditor In this interface, the editor component uses JComboBox components. 52

ComboBoxModel This interface represents the data model in a list model with the selected items. DesktopManager This interface has JDesktopPane object. The JInternalFrame implements in the JDesktopPane, with the help of DesktopManager. Icon This interface used to graphical representation of the components. It has fixed size picture. JComboBox.KeySelectionManager This interface has KeySelectionManager and used for the combo box data model. ListCellRenderer This interface used for paint the cell in the list with the help of "rubber stamps". ListModel This interface used for JList components method. It gets the value of each cell of list. ListSelectionModel This interface indicates the components, which are stable or not. MenuElement This interface used where the any components are implements in the menu. MutableComboBoxModel This interface extends from the ComboBoxModel. It is a mutable version of ComboBoxModel. 53

Renderer It defines the requirements of an object for displaying the values. RootPaneContainer This interface uses the RootPane properties and it has the components like: JFrame, JInternalFrame and JWindow etc. Scrollable This interface provides the scrolling to show the large amount of data with the help of JScrollPane. ScrollPaneConstants This interface used for JScrollPane components. SingleSelectionModel This interface used to select the one index in a model. SwingConstants You can set the components on the screen to own requirements. UIDefaults.ActiveValue It constructs the DefaultListCellRenderer. UIDefaults.LazyValue This enables one to store an entry in the default table. The entered value is not constructed until first time is a real value is created through it using LazyValue.createValue() method. WindowConstants This interface has two methods setDefaultCloseOperation getDefaultCloseOperation and provides the window close opration. and


In computing, Java 2D is an API for drawing two-dimensional graphics using the Java programming language. Every Java 2D drawing operation can ultimately be treated as filling a shape using a paint and compositing the result onto the screen.

The Java 2D API and its documentation are available for download as a part of JDK 6. Java 2D API classes are organised into the following packages in JDK 6: java.awt: The main package for the Java Abstract Window Toolkit. java.awt.geom: The Java standard library of two dimensional geometric shapes such as lines, ellipses, and quadrilaterals. java.awt.font: The library for manipulating glyphs in Java. java.awt.color: The library dealing with the many different ways that color can be represented. java.awt.image: The library for manipulating graphical images. java.awt.print: The library of tools for writing to paper.

Basic Concepts:
These objects are a necessary part of every Java 2D drawing operation. Shapes A shape in Java 2D is a boundary which defines an inside and an outside. Pixels inside the shape are affected by the drawing operation, those outside are not. Trying to fill a straight line segment will result in no pixels being affected, as such a shape does not contain any pixels itself. Instead, a thin rectangle must be used so that the shape contains some pixels.


Paints A paint generates the colors to be used for each pixel of the fill operation. The simplest paint is java.awt.Color, which generates the same color for all pixels. More complicated paints may produce gradients, images, or indeed any combination of colors. Filling a circular shape using the color yellow results in a solid yellow circle, while filling the same circular shape using a paint that generates an image produces a circular cutout of the image. Composites During any drawing operation, there is a source (the pixels being produced by the paint) and a destination (the pixels already onscreen). Normally, the source pixels simply overwrite the destination pixels, but the composite allows this behavior to be changed. The composite, given the source and destination pixels, produces the final result that ultimately ends up onscreen. The most common composite is java.awt.AlphaComposite, which can treat the pixels being drawn as partially transparent, so that the destination pixels show through to some degree. Filling To fill a shape, the first step is to identify which pixels fall inside the shape. These pixels will be affected by the fill operation. Pixels that are partially inside and partially outside the shape may be affected to a lesser degree if antialiasing is enabled. The paint is then asked to generate a color for each of the pixels to be painted. In the common case of a solid-color fill, each pixel will be set to the same color. The composite takes the pixels generated by the paint and combines them with the pixels already onscreen to produce the final result.

Advanced Objects:
These objects can be viewed as performing their duties in terms of the simpler objects described above.


Transform Every Java 2D operation is subject to a transform, so that shapes may be translated, rotated, sheared, and scaled as they are drawn. The active transform is most often the identity transform, which does nothing. Filling using a transform can be viewed as simply creating a new, transformed shape and then filling that shape. Stroke In addition to the fill operation, Java 2D provides a draw operation. While fill draws the interior of a shape, draw draws its outline. The outline can be as simple as a thin line, or as complicated as a dashed line with each dash having rounded edges. The object responsible for generating the outline is the stroke. Given an input shape, the stroke produces a new shape representing its outline. For instance, an infinitely thin line segment (with no interior) might be stroked into a onepixel-wide rectangle. A draw operation can therefore be described as creating a new, stroked object and then filling that object. Technically speaking, the stroke is only required to accept an input shape and produce a new shape. The stroke implementation provided with Java 2D implements the outline rules described above, but a custom-written stroke could produce any shape it wished. Optimizations Conceptually, drawing a straight black line in Java 2D can be thought of as creating a line segment, transforming it according to the current transform, stroking it to create a thin rectangle, querying this shape to compute the pixels being affected, generating the pixels using java.awt.Color.BLACK, and then compositing the results onto the screen. However, performing this entire sequence of steps for each drawing operation would be very inefficient. Java 2D therefore optimizes common drawing 57

operations so that many of these steps can be skipped. If the paint is a simple solid color, for instance, there is no need to actually command it to generate a list of colors to be painted. Likewise, if the default fully-opaque composite is in use, actually asking it to perform the compositing operation is unnecessary and would waste effort. Java 2D performs the minimum amount of work necessary to make it seem as if it is performing all of these steps for each operation, therefore retaining both great flexibility and high performance.





Client-server architecture can be considered as a network environment that exchanges information between a server machine and a client machine where server has some resources that can be shared by different clients. In Client-server architecture individual computers known as clients are connected to a central computer this is known as a server. Lets take an example of a file server to understand the core process of a client/server network, the file server acts as a storage space on the network for the files, spreadsheets, databases, etc. Instead of storing these records on every individual computer, the file server allows the clients to store their files on one central computer and make them sharable. The client-server architecture is beneficial in reducing the multiple iterations of a single file and allowing the organization to have one centralized point for every computer to access the same file.

The interaction between a lamp and an electrical socket can be considered as a interaction between client and server is just like. In the example the electrical socket is just like a server and the lamp works like a client. 60

Overview Of Networking Through Java:

The Java platform is extremely preferable to write an application program require to communicate with the resources on network. Java, mainly focuses on the networking relating the description of the networking capabilities of the Java platform and second one is describes a brief summary of networking in a very simple manner that how to use URLs, sockets, and datagrams. In Java, there is a java.net package provides the network support. All the classes for making a network program are defining in the java.net package. Through TCP we can communicate over the network.

Client-Server Architecture:
Client-server architecture can be considered as a network environment that exchanges information between a server machine and a client machine where server has some resources that can be shared by different clients.

Socket And Ports:

In common language we can say that the socket is one of the most primal technologies of computer networking. Sockets are just like an end-point of two-way communication, which allow applications to communicate using network hardware and operating systems. Server Sockets In common language we can say that the sockets are just like an end-point of two-way communication link over the network between two programs. Socket classes are used to establish a connection between client program and a server program. URL in term of Java Network Programming A URL (Uniform Resource Locator) is the address of a resource on the Internet. In java network programming we can use URLs to connect and retrieve information over the Internet.


In a network environment the client and the server communicate with eachother by reliable channel like TCP socket which have dedicated point-to-point channel between client and server. All data sent over the channel is received and sent in the same order.

Networking in Java
In this section we are exploring the java.net package which provides the support for networking in java with a generic style. All the java classes for developing a network program are defined in the java.net package.

Datagram in Network Environment

In a network environment the client and the server communicate with eachother by reliable channel like TCP socket which have dedicated point-to-point channel between client and server. All data sent over the channel is received and sent in the same order. In other case the application, which communicate by datagrams sends and receives completely independent packets of information and they also dont need a dedicated point-to-point channel.


Datagrams are simply bundles of information data passed between machines. Java implements datagrams on top of the UDP protocol by using three classes which are in java.net package as well as define as under: Datagram Socket Datagram Packet Multicast Socket In which the Datagram Packet is used to contain data for sent and receive by a application and the Datagram Socket is used to send or receive the Datagram Packets over the network environment. Whereas the Multicast socket is used to broadcast the Datagram Packets to multiple recipients.



In common language we can say that the socket is one of the most primal technologies of computer networking. Sockets are just like an end-point of two-way communication, which allow applications to communicate using network hardware and operating systems. However in case of java never get confused with a socket. Socket classes are used to establish a connection between client program and a server program. In java there is a java.net package, which provides two types of classes- first is ordinary socket, which implement the client side connection and second is server socket, which implement the server side connection.

The main purpose of the server socket is to listen an incoming connection request and ordinary socket is used to ask to server for the connection. Once a connection between client and server established, both the connected socket can communicate with each other. In other hand we can consider the work of port in connection-based communication is like a medium through which, an application establish a connection with another application by binding a socket by a port number. Addressing the information and the port no., accompanied the data transfer 64

over the network. The Ports are used by TCP and UDP to deliver the data to the right application, are identified by a 16-bit number. It will take effect of registering the application with the system to receive all data bound for that port. There is a limitation for the port that no port can be bound by two applications at the same time.

Introduction of Networking Ports

In computer networking of connection-based communication port is like a medium through which, an application establish a connection with another application by binding a socket by a port number. Addressing the information and the port no., accompanied the data transfer over the network. The Ports are used by TCP and UDP to deliver the data to the right application, are identified by a 16-bit number present in the header of a data packet. Ports are typically used to map data to a particular process running on a client. If we consider a letter (data packet) sent to a particular apartment (IP) with house no. (port no), at this time the port no. is the most important part for the delivery of the letter. In order for the delivery to work, the sender needs to include an house number along with the address to ensure the letter gets to the right destination. If we consider the client-server architecture, a server application binds a socket to a specific port number in connection-based communication. It registered the server with the system where all the data destined for that port. Now we are aware of the importance of the port number. In the same order there are some ports which are predefine and called reserved ports.


Some of them are given below:Reserved Port Numbers Service echo daytime ftp telnet smtp finger http pop3 Port no. 7 13 21 23 25 79 80 110

If we consider the range of the port numbers, there are 0 to 65,535 ports available. The port numbers ranging from 0 - 1023 are reserved ports or we can say that are restricted ports. All the 0 to 1023 ports are reserved for use by well-known services such as FTP, telnet and http and other system services. These ports are called well-known ports.










import java.awt.*; import java.awt.event.*; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.*; import javax.swing.border.*; import java.net.*; import java.io.*;

public class ChatClientGUI extends JFrame implements ActionListener { JLabel header; JButton send,clear,connect,disconnect; JTextField ip,port,username; Socket S; threadrecieve tr; JTextArea msg=new JTextArea(),main=new JTextArea(); public ChatClientGUI() {

setTitle("ChatClient"); 69

JPanel panel = new JPanel(); JPanel msgP = new JPanel(new BorderLayout()); JPanel mains = new JPanel(new FlowLayout()); JPanel Head = new JPanel(new BorderLayout()); JPanel sends = new JPanel(new BorderLayout()); JScrollPane mainscroll = new JScrollPane(main); JScrollPane msgscroll = new JScrollPane(msg); panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); panel.setLayout(new BorderLayout()); main.setLineWrap(true); msg.setLineWrap(true); mains.add(new JLabel("Host")); mains.add(ip=new JTextField(10)); mains.add(new JLabel("Port")); mains.add(port=new JTextField(5)); mains.add(new JLabel("Username:")); mains.add(username = new JTextField(5)); port.setText("27000"); port.setEditable(false); mains.add(connect=new JButton("Connect")); mains.add(disconnect=new JButton("Disconnect")); Head.add(mains,BorderLayout.SOUTH); 70

Head.add(header=newJLabel("ChatClient"),BorderLayout.NORTH); panel.add(Head,BorderLayout.NORTH); msgP.add(mainscroll,BorderLayout.CENTER); panel.add(msgP,BorderLayout.CENTER); sends.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); sends.add(msgscroll,BorderLayout.CENTER); sends.add(send=new JButton("Send"),BorderLayout.EAST); panel.add(sends,BorderLayout.SOUTH);

sends.setPreferredSize(new Dimension(100,100));

main.setEditable(false); disconnect.setEnabled(false); connect.addActionListener(this); send.addActionListener(this); disconnect.addActionListener(this);

addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { try{ 71

PrintWriter pw = new PrintWriter(S.getOutputStream()); pw.println("0x007"); pw.flush(); System.exit(0); } catch(Exception E) {} } } ); add(panel); setSize(640, 480); this.setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public void actionPerformed(ActionEvent ae) { String str = ae.getActionCommand(); if(str.equals("Connect") && username.getText().length()>=1) { try 72

{ S = new Socket(ip.getText(),27000); PrintWriter pw = new PrintWriter(S.getOutputStream()); pw.println(username.getText()); pw.flush(); BufferedReader br = new BufferedReader(new InputStreamReader(S.getInputStream())); String ms=br.readLine(); if(ms.equals("ok")) { tr = new threadrecieve(S); tr.start(); connect.setEnabled(false); disconnect.setEnabled(true); username.setEditable(false); ip.setEditable(false); } else { S.close(); JOptionPane.showMessageDialog(null, "Username already in use","Error", JOptionPane.ERROR_MESSAGE); } 73

} catch(Exception E) { JOptionPane.showMessageDialog(null, E.toString(),"Error", JOptionPane.ERROR_MESSAGE); } } if(str.equals("Disconnect")) { try { PrintWriter pw = new PrintWriter(S.getOutputStream()); pw.println("0x007"); pw.flush(); connect.setEnabled(true); disconnect.setEnabled(false); username.setEditable(true); ip.setEditable(true); } catch(Exception E) { } }


if(str.equals("Send")) { try { PrintWriter pw = new PrintWriter(S.getOutputStream()); pw.println(msg.getText()); pw.flush(); msg.setText(""); } catch(Exception E) { } } } public class threadrecieve extends Thread { Socket S; String msg; BufferedReader br; threadrecieve(Socket r) { S=r; 75

} public void run() { try { System.out.println("rock"); br = new BufferedReader(new InputStreamReader(S.getInputStream())); while((msg=br.readLine())!=null) { System.out.println(msg); ChatClientGUI.this.main.append(msg+"\n"); if(msg.equals("Server is Shutting Down")) { username.setEditable(true); ip.setEditable(true); disconnect.setEnabled(false); connect.setEnabled(true); break; } } S.close(); br.close(); } 76

catch(Exception E){ } } } public static void main(String[] args) { new ChatClientGUI(); } }



import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import java.net.*; import java.io.*; import java.util.*;

public class ChatServerGUI extends JFrame implements ActionListener { private static final long serialVersionUID = 7526472295622776147L; JLabel header; JButton send,clear,start,stop; JTextField port; JList userListBox; DefaultListModel userList; threadserver ts; int no_of_users; boolean serverState = false; String com; Vector<Socket> SocketClients = new Vector<Socket>(); 78

JTextArea msg=new JTextArea(),main=new JTextArea(); ServerSocket SS; Socket C; public ChatServerGUI() { setTitle("ChatServer"); JPanel panel = new JPanel(); JPanel msgP = new JPanel(new BorderLayout()); JPanel mains = new JPanel(new FlowLayout()); JPanel Head = new JPanel(new BorderLayout()); JPanel sends = new JPanel(new BorderLayout()); JPanel userPane = new JPanel(new BorderLayout()); userList = new DefaultListModel(); userListBox = new JList(userList); JPanel msgbuttons = new JPanel(new GridLayout(0,2,5,5)); JScrollPane mainscroll = new JScrollPane(main); JScrollPane msgscroll = new JScrollPane(msg);

userPane.add(new JScrollPane(userListBox),BorderLayout.CENTER); userPane.add(new JLabel("USER LIST",JLabel.CENTER),BorderLayout.NORTH); panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); panel.setLayout(new BorderLayout()); 79

panel.add(userPane,BorderLayout.EAST); main.setLineWrap(true); msg.setLineWrap(true); mains.add(new JLabel("Port")); mains.add(port=new JTextField(5)); mains.add(start=new JButton("StartService")); mains.add(stop=new JButton("StopService")); stop.setEnabled(false); port.setText("27000"); port.setEditable(false); Head.add(mains,BorderLayout.SOUTH); Head.add(header=new JLabel("Chat Server"),BorderLayout.NORTH); panel.add(Head,BorderLayout.NORTH); msgP.add(mainscroll,BorderLayout.CENTER); panel.add(msgP,BorderLayout.CENTER); sends.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); sends.add(msgscroll,BorderLayout.CENTER); sends.add(msgbuttons,BorderLayout.EAST); msgbuttons.add(send=new JButton("Send"));


msgbuttons.add(clear=new JButton("Clear")); panel.add(sends,BorderLayout.SOUTH); sends.setPreferredSize(new Dimension(50,50)); main.setEditable(false); add(panel); setSize(640, 480); this.setResizable(false); start.addActionListener(this); stop.addActionListener(this); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { try{ Socket dummy; PrintWriter pw; for(int i=0;i<SocketClients.size();i++) { dummy=(Socket)SocketClients.get(i); pw = new PrintWriter(dummy.getOutputStream()); 81

pw.println("Server is Shutting Down"); pw.flush(); } System.exit(0); } catch(Exception E) {} } } ); setVisible(true); try{ Thread.sleep(1000); main.append("Welcome to Phoenix, \n"); main.append("please wait...\n"); Thread.sleep(2000); main.append("Click StartService to Start Listening on port 27000\n"); } catch(Exception E) { send.addActionListener(this); }


public void actionPerformed(ActionEvent ae) { String str=ae.getActionCommand();

if(str.equals("StartService")) { try {

JOptionPane.showMessageDialog(null, "Running!", "Ready to accept new clients", JOptionPane.INFORMATION_MESSAGE); serverState=true; SS = new ServerSocket(27000); ts = new threadserver(SS); ts.start(); stop.setEnabled(true); start.setEnabled(false); } catch(Exception E) { } } if(str.equals("StopService")) { try


{ Socket dummy; PrintWriter pw; serverState=false; main.setText(main.getText()+"\n===SERVER CLOSED===\n"); for(int i=0;i<SocketClients.size();i++) { dummy=(Socket)SocketClients.get(i); pw = new PrintWriter(dummy.getOutputStream()); pw.println("Server is Shutting Down"); pw.flush(); } userList.clear(); SocketClients.clear(); SS.close(); start.setEnabled(true); stop.setEnabled(false); } catch(Exception E) { } } 84

if(str.equals("Send")) { PrintWriter pw; try { Socket dummy; for(int i=0;i<SocketClients.size();i++) { dummy=(Socket)SocketClients.get(i); pw=new PrintWriter(dummy.getOutputStream()); pw.println(">>>>>>>>SERVER:"+msg.getText()); main.append(">>>>>>>>SERVER:"+msg.getText()+"\n"); msg.setText(""); pw.flush(); } } catch(Exception E) { } } }


public class threadserver extends Thread { ServerSocket s; Socket C; threadserver(ServerSocket k) { s=k; } public void run() { boolean proceed=true; no_of_users=0; try { ChatServerGUI.this.main.append(">Ready to accept clients\n"); while(true) { C = s.accept(); no_of_users++; BufferedReader br = new BufferedReader(new InputStreamReader(C.getInputStream())); PrintWriter pw = new PrintWriter(C.getOutputStream());


String ms = br.readLine(); for(int i=0;i<userList.size();i++) { if(ms.equalsIgnoreCase((String)userList.get(i))) { pw.println("not ok"); pw.flush(); C.close(); proceed=false; break; } proceed=true; } if(proceed) { pw.println("ok"); pw.flush(); SocketClients.add(C); threadclient client; client = new threadclient(C); client.setName(ms); client.start(); 87

} } } catch(Exception E) { } } } public class threadclient extends Thread { Socket c; Socket dummy; String msg; BufferedReader br; PrintWriter pw; boolean clientStatus; threadclient(Socket S) { c=S; } public void run() { 88

try { System.out.println("texting"); br = new BufferedReader(new InputStreamReader(c.getInputStream())); pw = new PrintWriter(c.getOutputStream()); pw.println("Welcome to Phoenix"); pw.println("Your Username:"+this.getName()); pw.flush();

for(int j=0;j<SocketClients.size();j++) { dummy=(Socket)SocketClients.get(j); pw = new PrintWriter(dummy.getOutputStream()); pw.println(this.getName()+" has joined the chat"); pw.flush();

} System.out.println(c); userList.addElement((String)this.getName()); while(ChatServerGUI.this.serverState) { if((msg=br.readLine())!=null)


if(msg.equals("0x007")) { pw.println("You have been Disconnected from the Chat"); pw.flush(); com = this.getName(); SocketClients.removeElement(c); for(int i=0;i<SocketClients.size();i++) { dummy=(Socket)SocketClients.get(i); pw=new PrintWriter(dummy.getOutputStream());

pw.println(ChatServerGUI.this.com+" has left the chat"); pw.flush(); } break; } else if(msg.equals("**users")) { pw.println("\n****USERS****"); for(int i=0;i<userList.size();i++) 90

{ pw.println((String)userList.get(i)); } pw.println(); pw.flush(); } else { System.out.println(msg); msg = this.getName()+": "+msg; System.out.println(msg); ChatServerGUI.this.main.append(msg+"\n"); for(int i=0;i<ChatServerGUI.this.SocketClients.size();i++) { dummy=(Socket)SocketClients.get(i); pw=new PrintWriter(dummy.getOutputStream()); pw.println(msg); //System.out.println(msg); pw.flush(); } } } 91

} System.out.println("exiting "+this.getName()); c.close(); br.close();

ChatServerGUI.this.main.append(">>"+this.getName()+" has left the chat\n"); for(int j=0;j<SocketClients.size();j++) System.out.println(SocketClients.get(j)); userList.removeElement(this.getName()); } catch(Exception E) { E.printStackTrace(); } } } public static void main(String[] args) { new ChatServerGUI(); } }



Running ChatServer GUI:


The Output Server Window:


Running ChatClient GUI:


The Output Client Window:


Enter host name and a user name and connect to server:

The user now has been connected to the server and ready to chat.


Final Chat Client Window:


Final Chat Server Window:


Chat Server Window with multiple users:


Disconnection Of Client: Click on "Disconnect" tab in your chat window.


Disconnecting the Server:





Our project is only a humble venture to satisfy the needs in a library. Several user friendly coding have also adopted. This package shall prove to be a powerful package in satisfying all the requirements of the organization. The objective of software planning is to provide a frame work that enables the manager to make reasonable estimates made within a limited time frame at the beginning of the software project and should be updated regularly as the project progresses. Last but not the least it is not the work that played the ways to success but ALMIGHTY.




Head First Java 2nd Edition APress, Java and Software Design Concepts Cay S. Horstmann Gary Cornell, Core Java Volume 1- Fundamentals Khalid A. Mughal, Java Certification http://java.sun.com http://www.roseindia.net/jdbc/jdbc-access/CreateTable.shtml http://www.jdbc-tutorial.com/