ADVANCE JAVA
May 2009
Paper Code : CSE-404-E
Q.1. Explain the concept of arrays in java with suitable program. Also explain the inheritance and exception handling with examples.
Ans. Arrays : An Arrays is a (fixed length) data structures used to store multiple data elements of same type. The memory allocated to an array is consecutive. All the elements of an array are under one variable name. Every data element of an array is accessed by its position and that position in indicated by an integer value that start from 0 called index. The array size is fixed and cannot be changed at runtime of the program.
Java supports two types of arrays:
(i) One Dimensional Array.
(i) One Dimensional Array.
(ii) Multiple Dimensional Array.
In Java, arrays can be of either types, primitive data types or reference types. In primitive data type array, all elements are of a definite primitive data type. In references type array all elements are of definite reference type.
Declaration of Array Variables : The syntax to declare either type of arrays , i.e. one -dimensional or multiple dimensional array is :
<data.type>[] <array - name>; //One Dimensional Array
Or
<data.type> <array - name>[]; //One Dimensional Array
Syntax to create an array:
<array - name> = new <data-type> [<array-size>]; //One dimensional Array
Initialization of Array : Initialization means to assign the value to the array at the time of constructing and declaring in one statement simultaneously.
<data - type> [] <array - name> = { <initial value list>};
For example :
int an_Array = {1,2,3,4,5,6,7,8,9 }; //One dimensional Array
for(int i=0;i<3;i++)
System.out.println(anArray[i]); //Accessing ith index Value.
int matrix[] [] = {{1,2,3},{4,5,6,},{7,8,9}}; //Two dimensional Array
for (int i=0; i<3; i++)
{ for (int j=0; j=3; j++)
System.out.print(matrix[i][j]);
System.out.println();
}
Inheritance : Inheritance is one of the most important and useful feature of object-oriented programming. There is a main class, called base class or super class, from which a new class id derived, called derived class or sub class. Base class is also called parent class and the derived class is called child class. Inheritance provides a mechanism for deriving new classes from existing ones. In OOP, ther are several type of mechanisms:
(1) Single Inheritance
(2) Multiple Inheritance
(3) Multilevel Inheritance
(4) Hybrid Inheritance
In Java a class can be derived from another class using the general form :
access_specifier class Subclass extends Superclass
{ //Derived class data and methods
}
Example:
class A {
int x;
int y;
int get(int p, int q) {
x = p; y = q; return(0);
}
void show() {
System.out.println(x);
}
}
class B extends A {
void showb() {
System.out.println("B");
}
}
class c extends B {
void display() {
System.out.println("C");
}
}
public static void main(strings args[]) {
A a = new A();
a.get(5,6);
a.show();
}
}
Exception Handling : An exception is a run-time error or an anomalous condition that arises in the program during run time. A Java exception is an object that describes an abnormal condition in the program code. When an abnormal condition is encountered in the object code, an object representing that condition or exception is created an thrown in the method that caused the error. The method can then make the choice to handle the exception itself or pass it on. An exception may also be caught and processed. Exception can also be manually generated by your program code. Exceptions thrown by Java programs are actually the errors that violate the constraints of Java runtime. In Java, exception handling
- try
- catch
- throw
- throws
- finally
The program statements to be monitored for exceptions are kept within a 'try block'. If an exception occurs in the 'try block', then it is thrown. The statements that have to be thrown manually are kept in the 'catch block'. System generated exceptions are automatically thrown by Java runtime environment. The general form of exception handling is :
try
{ //block of code to be monitored
}
catch (Exception_TypeA obj)
{ //exception handler for Exception_TypeA
}
Finally
{ //block of code to be executed
}
All types of exceptions are the subclass of built-in class Throwable. Throwable contains two subclasses, one is exception for the abnormal conditions that the user programs must handle. Exceptions include conditions like divide by zero. This type of exception is called Arithmatic Exception. Another subclass is error that contains the conditions that are not expected to be caught under normal conditions.
Example:
class Multiple_Catch
{
Public static void main(String args[])
{
try
{
int x=0;
int y=y/x;
int a[] = {6};
a[89] = 44;
}
catch (Arithmetic Exception e1)
{
System.out.println("ERROR : Divide by Zero" +e1);
}
catch (Array Index Of Bound Exception e2)
{
System.out.println("ERROR : Array out of Bound" +e2);
}
}
}
Syntax to create an array:
<array - name> = new <data-type> [<array-size>]; //One dimensional Array
Initialization of Array : Initialization means to assign the value to the array at the time of constructing and declaring in one statement simultaneously.
<data - type> [] <array - name> = { <initial value list>};
For example :
int an_Array = {1,2,3,4,5,6,7,8,9 }; //One dimensional Array
for(int i=0;i<3;i++)
System.out.println(anArray[i]); //Accessing ith index Value.
int matrix[] [] = {{1,2,3},{4,5,6,},{7,8,9}}; //Two dimensional Array
for (int i=0; i<3; i++)
{ for (int j=0; j=3; j++)
System.out.print(matrix[i][j]);
System.out.println();
}
(1) Single Inheritance
(2) Multiple Inheritance
(3) Multilevel Inheritance
(4) Hybrid Inheritance
In Java a class can be derived from another class using the general form :
access_specifier class Subclass extends Superclass
{ //Derived class data and methods
}
Example:
class A {
int x;
int y;
int get(int p, int q) {
x = p; y = q; return(0);
}
void show() {
System.out.println(x);
}
}
class B extends A {
void showb() {
System.out.println("B");
}
}
class c extends B {
void display() {
System.out.println("C");
}
}
public static void main(strings args[]) {
A a = new A();
a.get(5,6);
a.show();
}
}
- try
- catch
- throw
- throws
- finally
The program statements to be monitored for exceptions are kept within a 'try block'. If an exception occurs in the 'try block', then it is thrown. The statements that have to be thrown manually are kept in the 'catch block'. System generated exceptions are automatically thrown by Java runtime environment. The general form of exception handling is :
try
{ //block of code to be monitored
}
catch (Exception_TypeA obj)
{ //exception handler for Exception_TypeA
}
Finally
{ //block of code to be executed
}
All types of exceptions are the subclass of built-in class Throwable. Throwable contains two subclasses, one is exception for the abnormal conditions that the user programs must handle. Exceptions include conditions like divide by zero. This type of exception is called Arithmatic Exception. Another subclass is error that contains the conditions that are not expected to be caught under normal conditions.
Example:
class Multiple_Catch
{
Public static void main(String args[])
{
try
{
int x=0;
int y=y/x;
int a[] = {6};
a[89] = 44;
}
catch (Arithmetic Exception e1)
{
System.out.println("ERROR : Divide by Zero" +e1);
}
catch (Array Index Of Bound Exception e2)
{
System.out.println("ERROR : Array out of Bound" +e2);
}
}
}
Q.2. Explain the concept of E-Mail server.
Ans. E-Mail server : A socket will be created, connect to port 25, which is SMTP port number. Simple mail transfer Protocol describes the format in which e-mail message will be sent. In UNIX OS, sendmail daemon was already implemented to support this features.
Example :
import Java.io.BufferedReader;
import Java.io.FileReader;
import Java.io.IOException;
import Java.io.InputStream;
import Java.io.InputStreamReader;
import Java.io.OutputStream;
import Java.io.OutputStreamWriter;
import Java.io.PrintWriter;
import Java.net.InetAddress;
import Java.net.Socket;
import Java.net.UnknownHostException;
public class SMTPDemo {
public static void main (String args[] throws IOException, UnknownHostException {
String msgFile = "file.txt";
String from = "java2s@java2s.com";
String to = "yourEmail@yourServer.com";
String mailHost = "yourHost";
SMTP mail = new SMTP(mailHost);
if(mail != null) {
if (mail.send(new FileReader (msgFile), from, to)) {
System.out.println("Mail sent.");
} else {
System.out.println("Connect to SMTP sever failed !");
}
}
System.out.pritnln("Done");
}
static class SMTP {
private final static int SMTP_PORT = 25;
Inetdderess mailHost;
Inetddress localHost;
BufferedReader in;
Public SMTP (String host) throws UnknownHostException {
mailHost = InetAddress.getByName (host);
localHost = InetAddress.getLocalHost ( );
System.out.println("mailhost = "+ mailHost );
System.out.println("localhost = "+ localHost);
System.out.println("SMTP construtor done\n");
}
public boolean send (FileReader msgFileReader, String from, String to ) throws IOException {
Socket smtpPipe;
InputStream inn;
OutputStream outt;
BufferedReader msg;
msg = new BufferedReader(msgFileReader);
smtpPipe = new Socket(mailHost, SMTP_PORT);
if (smtpPipe == null) {
return false; }
inn = smtpPipe.getInputStream( );
outt = smtpPipe.getOutputStream( );
in = new BufferedReader(new InputStreamReader(inn));
out = new PrintWriter(new OutputStreamWriter(outt), true);
if (inn = = null \\ out= = null) {
System.out.println("Failed to open streams to socket.");
return false;
}
StringinitialID = in.read.Line( );
System,out.println(initialID);
System.out.println("HELO " + localhost.getHostName( ));
out.println("HELO " + localhost.getHostName( ));
String welcome = in.readLine ( );
System.out.println(welcome);
System.out.println("MAIL From:<" + from + ">");
out.println("MAIL From:<" + from + ">");
String senderOK = in.readLine( );
System.out.println(senderOK);
System,out.println("RCPT TO:<" + to + ">");
out.println("RCPT TO:<" + to + ">");
String RecipientOK = in.readLine( );
System.out.println(recipientOK);
System.out.println("DATA");
out.println("DATA");
String line;
While((line = msg.readLine ( )) != null ) {
out.println(line);
}
System.out.println(".");
out.println(".");
String acceptedOK = in.readLine( );
System.out.println(acceptedOK);
System.out.println("QUIT");
out.println("QUIT");
return true;
}
}
}
(b) LDAP : The lightweight Directory Access Protocol(LDAP) was developed in the early 1990s as a standard directory protocol. LDAP is now probably the most popular directory protocol & because JNDI can access LADP.
"LDAP defines the mechanism by which clients should be able access data on the server. It does not however, gives details how the data should be stored on the server."
LADP uses the hierarchical tree structure to organize the data, called a Directory Information Tree(DIT). In DIT each leaf is an entry, and the first entry is called root entry.
An entry contains a Distinguished(DN) & attributes-value pairs related to it. The DN is a comprises the information how it is related to rest of the DIT, same as the Pathname shows how the file is related to rest of file system.
The path to a file on a system root to file. A DN reads right to left for example: uid=sujjain, oi=people, o=theweb.com The leftmost part of a DN is called a Relative Distinguished Name(RDN) his example would be uid=scarter.
LADP attributes often use mnemonics as their names.
LADP servers have other following benefits:
(i) They support references pointers to other LDAP directories where data is stored. So that just by one client request a single LDAP server could search milliones of entries.
(ii) Reliability & speed is improved by replication of LDAP data.
(iii) LDAP also has a exceptionally strong security model that contains.
(iv) ACLs to protect data inside the server.
(v) Secure Socket Layers(SSL).
(vi) Trasport Layer Security(TSL).
(vii) Simple Authentication & Security Layer (SASL) protocols.
Applications : There are basic three basic applications of LADP in Java today;
- Access Control
- White Pages Services
- Distributed Computing Directory.
LDAP Operations : Standard LADP Operations are as follows :
- Connect to the LDAP server
- Bind to the LDAP server
- Search the server
- Add a new entry
- Modify an entry
- Delete an entry
- Disconnect from the LDAP server.
Q.4. What is RMI with SOAP? Explain. (20)
Ans. RMI with SOAP : Soap stands for Simple Object Access Protocol, SOAP is a XML based protocol for communication between applications. It is used in Internet and is a W3C recommendation. CORBA uses SOAP protocol to communicate between objects. SOAP is defined by WSDL(Web Services Description Language). SOAP provides a way to mommuniate between applications running on different operating systems with different technologies and programming languages.
A SOAP message is an XML document having elements.
1. An envelop element that identifies the XML document as a SOAP message.
2. A header element that contains header information.
3. A body element contains call response information.
4. A fault element contains error and status information.
The Syntax of SOAP message is as follows:
<?xml version = "1.0"?>
soap:Envelope
<xmlns:soap = "http;//www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Header>
...
</soap:Header>
<soap:Body>
...
<soap:Fault>
...
</soap:Fault>
</soap:Body>
</soap:Envelope>
The current w3c specification and implementation of the SOAP from Apache present only HTTP binding for SOAP. Due to this, the web services have to be deployed in a web server container. The possibility of opening SOAP based interfaces to the existing RMI services may be limited by the following factor: if we convert the existing RMI services as SOAP based & deploy them in the web server container, the existing clients to those services have to be rewritten or reconfigured. We may also maintain two interfaces each for RMI & SOAP for the same set of services which is not desirable.
Q.5. How styled text components are implemented in Java ? Also explain the usage of tables. (20)
Ans. Styled text components includes Text Area, Text Field & Editor Pane components of Swing class.
(i) JTestArea : It is the subclass of JTextComponent that allows the editing of multiline text. Scrollbars can easily be added by placing JTextArea components in a JScrollPane container. The inheritance diagram for JTextArea is as follos:
(iii) JEditorPane : It enables the users to implement sophisticated editing facilities quite easily. The table below shows the constructors of JEditorPane class:
Table : Constructors of JEditorPane Class
The table below shows the methods of TableModel class:
Example :
import Java.io.BufferedReader;
import Java.io.FileReader;
import Java.io.IOException;
import Java.io.InputStream;
import Java.io.InputStreamReader;
import Java.io.OutputStream;
import Java.io.OutputStreamWriter;
import Java.io.PrintWriter;
import Java.net.InetAddress;
import Java.net.Socket;
import Java.net.UnknownHostException;
public class SMTPDemo {
public static void main (String args[] throws IOException, UnknownHostException {
String msgFile = "file.txt";
String from = "java2s@java2s.com";
String to = "yourEmail@yourServer.com";
String mailHost = "yourHost";
SMTP mail = new SMTP(mailHost);
if(mail != null) {
if (mail.send(new FileReader (msgFile), from, to)) {
System.out.println("Mail sent.");
} else {
System.out.println("Connect to SMTP sever failed !");
}
}
System.out.pritnln("Done");
}
static class SMTP {
private final static int SMTP_PORT = 25;
Inetdderess mailHost;
Inetddress localHost;
BufferedReader in;
Public SMTP (String host) throws UnknownHostException {
mailHost = InetAddress.getByName (host);
localHost = InetAddress.getLocalHost ( );
System.out.println("mailhost = "+ mailHost );
System.out.println("localhost = "+ localHost);
System.out.println("SMTP construtor done\n");
}
public boolean send (FileReader msgFileReader, String from, String to ) throws IOException {
Socket smtpPipe;
InputStream inn;
OutputStream outt;
BufferedReader msg;
msg = new BufferedReader(msgFileReader);
smtpPipe = new Socket(mailHost, SMTP_PORT);
if (smtpPipe == null) {
return false; }
inn = smtpPipe.getInputStream( );
outt = smtpPipe.getOutputStream( );
in = new BufferedReader(new InputStreamReader(inn));
out = new PrintWriter(new OutputStreamWriter(outt), true);
if (inn = = null \\ out= = null) {
System.out.println("Failed to open streams to socket.");
return false;
}
StringinitialID = in.read.Line( );
System,out.println(initialID);
System.out.println("HELO " + localhost.getHostName( ));
out.println("HELO " + localhost.getHostName( ));
String welcome = in.readLine ( );
System.out.println(welcome);
System.out.println("MAIL From:<" + from + ">");
out.println("MAIL From:<" + from + ">");
String senderOK = in.readLine( );
System.out.println(senderOK);
System,out.println("RCPT TO:<" + to + ">");
out.println("RCPT TO:<" + to + ">");
String RecipientOK = in.readLine( );
System.out.println(recipientOK);
System.out.println("DATA");
out.println("DATA");
String line;
While((line = msg.readLine ( )) != null ) {
out.println(line);
}
System.out.println(".");
out.println(".");
String acceptedOK = in.readLine( );
System.out.println(acceptedOK);
System.out.println("QUIT");
out.println("QUIT");
return true;
}
}
}
Q.3. Explain the following:
(a) Metadata
(b) LADP.
Ans. (a) Metadata : Meta means "Data About Data". As any database is created, or any table is created is a data base, then database system store some information about all these for the internal use. If there is any need then we can retrieve from system file or the tools given by database system. For example metadata describes that table structure, like column name, size, type etc.
JDBC also provides two interface by those we can get the information about the structures of a database and its relations. Supporting methods are useful to write the tool to interact with database. To explain the need of these interfaces let's take one example, only the database name and its URL is given, now the developer has to write the code to extract the stored data in the tables. So before writing the code the developer must know all the tables name, their structures, etc. In that these interfaces will provide help to developer to collect the information about the database and their components.
Let's have a look on the JDBC interfaces that facilitate the developer to work on metadata of the database and resultest. There are two interfaces as following:
(i) DatabaseMetaData : The interface java.sql.DatabaseMetaData use to provide information about the database itself. Vendor to vendor the differences are found. For example, it given data or information about the version, table name list and other functions too.
The object of DatabaseMetaData can be get from getMetaData() from Connection object.
(ii) ResultSetMetaData : The interface java.sql.ResultSetMetaData used to provide the information about the characteristics ResultSet object. For example, using this developer can collect the name of each column of the corresponding table of which ResultSet object has the reference.
The object of ResltSetMetaData can be get from getMetaData() from ResultSet object.
Let's have a look on the JDBC interfaces that facilitate the developer to work on metadata of the database and resultest. There are two interfaces as following:
(i) DatabaseMetaData : The interface java.sql.DatabaseMetaData use to provide information about the database itself. Vendor to vendor the differences are found. For example, it given data or information about the version, table name list and other functions too.
The object of DatabaseMetaData can be get from getMetaData() from Connection object.
(ii) ResultSetMetaData : The interface java.sql.ResultSetMetaData used to provide the information about the characteristics ResultSet object. For example, using this developer can collect the name of each column of the corresponding table of which ResultSet object has the reference.
The object of ResltSetMetaData can be get from getMetaData() from ResultSet object.
(b) LDAP : The lightweight Directory Access Protocol(LDAP) was developed in the early 1990s as a standard directory protocol. LDAP is now probably the most popular directory protocol & because JNDI can access LADP.
"LDAP defines the mechanism by which clients should be able access data on the server. It does not however, gives details how the data should be stored on the server."
LADP uses the hierarchical tree structure to organize the data, called a Directory Information Tree(DIT). In DIT each leaf is an entry, and the first entry is called root entry.
An entry contains a Distinguished(DN) & attributes-value pairs related to it. The DN is a comprises the information how it is related to rest of the DIT, same as the Pathname shows how the file is related to rest of file system.
The path to a file on a system root to file. A DN reads right to left for example: uid=sujjain, oi=people, o=theweb.com The leftmost part of a DN is called a Relative Distinguished Name(RDN) his example would be uid=scarter.
LADP attributes often use mnemonics as their names.
LADP servers have other following benefits:
(i) They support references pointers to other LDAP directories where data is stored. So that just by one client request a single LDAP server could search milliones of entries.
(ii) Reliability & speed is improved by replication of LDAP data.
(iii) LDAP also has a exceptionally strong security model that contains.
(iv) ACLs to protect data inside the server.
(v) Secure Socket Layers(SSL).
(vi) Trasport Layer Security(TSL).
(vii) Simple Authentication & Security Layer (SASL) protocols.
Applications : There are basic three basic applications of LADP in Java today;
- Access Control
- White Pages Services
- Distributed Computing Directory.
LDAP Operations : Standard LADP Operations are as follows :
- Connect to the LDAP server
- Bind to the LDAP server
- Search the server
- Add a new entry
- Modify an entry
- Delete an entry
- Disconnect from the LDAP server.
Q.4. What is RMI with SOAP? Explain. (20)
Ans. RMI with SOAP : Soap stands for Simple Object Access Protocol, SOAP is a XML based protocol for communication between applications. It is used in Internet and is a W3C recommendation. CORBA uses SOAP protocol to communicate between objects. SOAP is defined by WSDL(Web Services Description Language). SOAP provides a way to mommuniate between applications running on different operating systems with different technologies and programming languages.
A SOAP message is an XML document having elements.
1. An envelop element that identifies the XML document as a SOAP message.
2. A header element that contains header information.
3. A body element contains call response information.
4. A fault element contains error and status information.
The Syntax of SOAP message is as follows:
<?xml version = "1.0"?>
soap:Envelope
<xmlns:soap = "http;//www.w3.org/2001/12/soap-envelope"
<soap:Header>
...
</soap:Header>
<soap:Body>
...
<soap:Fault>
...
</soap:Fault>
</soap:Body>
</soap:Envelope>
The current w3c specification and implementation of the SOAP from Apache present only HTTP binding for SOAP. Due to this, the web services have to be deployed in a web server container. The possibility of opening SOAP based interfaces to the existing RMI services may be limited by the following factor: if we convert the existing RMI services as SOAP based & deploy them in the web server container, the existing clients to those services have to be rewritten or reconfigured. We may also maintain two interfaces each for RMI & SOAP for the same set of services which is not desirable.
Q.5. How styled text components are implemented in Java ? Also explain the usage of tables. (20)
Ans. Styled text components includes Text Area, Text Field & Editor Pane components of Swing class.
(i) JTestArea : It is the subclass of JTextComponent that allows the editing of multiline text. Scrollbars can easily be added by placing JTextArea components in a JScrollPane container. The inheritance diagram for JTextArea is as follos:
Java.lang.Object
↓
Java.awt.Component
↓
Java.awt.Container
↓
Javax.swing.JComponent
↓
Javax.swing.text.JTextComponent
↓
Javax.swing.JTextArea
|
fig. Inheritance diagram for J Test Area
(ii) JTextField : Swing test fields work like Awt test fields. The inheritance diagram for JTextField class is also follows:
Java.lang.Object
↓
Java.awt.Component
↓
Java.awt.Container
↓
Javax.swing.JComponent
↓
Javax.swing.text.JTextComponent
↓
Javax.swing.JTextField
|
Table : Constructors of JEditorPane Class
Constructors
|
Functions
|
JEditorPane ()
|
Creates a nes JEditorPane.
|
JEditorPane(String url)
|
Creates a JEditorPane based on a string containing a URL
specification.
|
JEditorPane(String type, String text)
|
Creates a JEditorPane that has been initialized to the given text.
|
JEditorPane(URL initial-Page)
|
Creates a JEditorPane based on a specified URL for input.
|
Tables : The tables are very powerful components in Swing. They were created to provide an interface to JDBC that makes programming quite flexible for the user. JTable component allows the user to show and edit tabular data. JTable components display a rectangular array of data on the screen. The items in the table can have different type of data.
We can create a JTable object directly from such an object by passing a reference of type TableModel to a JTable constructor as :
JTable table = new JTable (model);
model is a variable of type TableModel that stores a reference to an object that encapsulates the data to be displayed.
The table below shows the methods of TableModel class:
Method
|
Function
|
Void addTable ModelListener (Table ModelListener I)
|
Adds a listener to the list that is notified each time a change to
the data model occurs
|
Class<?> get ColumnClass (intcolumnIndex)
|
Return the most specific superclass for the all the cell values in
the column
|
Int getColumnCout()
|
Returns the number of columns in the model
|
String getColumname (int columnIndex)
|
Returns the name of columns at columnIndex
|
Int getRowCount()
|
Returns the number of rows in the model
|
Object getValueAt (int rowindex, int columnindex)
|
Returns the value for the cell at columnIndex and rowIndex
|
Boolean isCellEditable(int rowindex, int columnindex)
|
Returns true if the cell at rowIndex and columnIndex is editable
|
Void remove TableModelListener(TableModelListner I)
|
Removes a listener from the list that is notified each time a change
to the data model occurs
|
Void setValueAt(Object aValue, int rowIndex, int columnIndex)
|
Q.6. How images are manipulated in AWT. Explain the concept of Drag and Drop in AWT. (20)
Ans. Image Manipulation : If we have an image and we want to improve its appearance. We then need to access the individual pixels of the image and replace them with other pixels. Or perhaps we want to compute the pixels of an image from scratch, for example, to show the result of physical measurements or a mathematical computation. The BufferedImage class gives the control over the pixels in an image, and classes that implement the BufferedImageOp interface let us transform Images.
This is a major change from the image support in JDK 1.0. At that time, the image classes were optimized to support incremental rendering. The original purpose of the classes was to render GIF and JPEG images that are downloaded form the Web, a scan line at a time, as soon as partial image data is available. In fact, scan lines can be interlaced, with all even scan lines coming first, followed by the odd scan lines. This mechanism lets a browser quickly display an approximation of the image while fatching the remainder of the image data. The ImageProducer, ImageFilter, and ImageConsumer interfaces in JDK 1.0 expose all the complexities of incremental rendering. Writing an image manipulation that fit well into that framework was quite complex. Fortunately, the need for using these classes has completely gone away. JDK 1.2 replaced the "push model" of JDK 1.0 with a "direct" model that lets us access pixels directly and conveniently. The only disadvantage of the direct model is that it requires all image pixels to be in memory. Future versions of the Java Platform may support a "pull" model with which a processing pipeline can reduce memory consumption & increase speed by fetching & processing pixels only when they are actually needed.
Most of the images that we manipulate are simply read in form an image file. They were either produced by a device such as a digital camera or scanner, or constructed by a drawing program. To create an image, construct a BufferedImage object in the usual way.
Image = New BufferedImage (width, height, BufferedImage, TYPE_INT_ARGB);
Now, call the getraster method to obtain an object of type WritableRaster. You use this object to access and modify the pixels of the image.
WritableRaster raster = image.getRaster();
The setPixel method lets us set an individual pixel. The complexity here is that we can't simply set the pixel to a Color value. We must know how the buffered image specifies color values. That depends on the type of the image. If the image has type of TYPE_INT_ARGB, then each pixel is described by four values, for red, green, blue, and alpha, each of which is between o and 255. We supply them in any array of four integers.
int[] black = {0,0,0,255};
raster.setPixel (i,j,black);
Drag and Drop : Java introduced the ability to transfer data using Drag and Drop metaphor. Java 2 developed many new classes to develope D&D metaphor in the package java.awt.dnd. The figure below shows a GUI component representing the data source and destination of D&D operation that maintains an association with a java.awt.dnd. DropeSource object and java.awt.dnd.Drop Target object. It depicts a java.awt.datatransfer. Transferable object that encapsulates the data transfer between DragSource and DragTarget Objects.
When the Transferable object encapsulates data, it makes the data available to DragTarget. For a local transfer within the same JVM. Transferable provides an object reference. When invoking a Drag & Drop operation, various drag and drop operations are requested such as:
ACTION_NONE no action taken
ACTION_COPY the DragSource leaves the data intact
ACTION_MOVE the DragSource deletes the data upon successful completion of the drop.
DIGRAM HERE
Q.7. Explain the bean writing process. Explain building an application with beans. (20)
Ans. Java Bean is a softwear component written in Java, provides portability, platform-independent component model, and re-usability. You can add these components into applets, applications, or with other bean components.
By nature, beans are dynamic like other software components; these can be changed or customized.
The JavaBeans architecture was built through a collaborative industry effort and enables developers to write reusable components in the Java programming language.
With the Java Beans API you can create re useable, platform-independent components.
There are three types of benas:
(i) Visible Bean : A bean component that is visible to an end user, such as a button or any graphical component, that is used with GUI.
(ii) Invisible Bean : A bean that added with any application but not visible to the end user on GUI, for example checking the spelling of a document.
(iii) Container Bean : A bean can contain another bean component, is called the container bean for example a tree bean can contain another component like images, labels, etc.
The bean is created by combining the following components:
- Properties define the characteristics of the bean. It can be change at design time or run time if it is not read only and some mutator methods are given in its implementation.
- Events to momunicate with other beans.
- Methods can be called from other beans or from the environment or application in that it is added.
Advantages of beans : There are following advantages of Java Bean components:
(1) It supports or provide "write-once, run-anywhere" paradigm.
(2) Three component of the bean are exposed to an application builder tool.
(3) It has to run in different environment, so that, it is designed correctly.
(4) It's configuration setting is stored and helps to persist its state and can be used later.
(5) A Bean may receive events and can communicate with other by generating the events, if it is registered with events.
States of Bean : Bean is a resusable software component. So as software hs its development life cycle similarly bean component has its own states. These states defines its lifecycle, and are as following;
- Consturaction State : In this state, the bean is under coding phase. The developer busy in writing the code for it.
- Build State : Bean is in build state, where after construction, it is added with any application.
- Run State: As the container application runs, then bean is in run state.
Characteristics of bean :
(1) Communication : One bean can communicate with other bean and application in that it is build. By message passing to method, it do communication.
(2) Introspection : It is an automatic process to analyze the properties, evens and methods.
(3) Persistance : A bean persists by storing and retrieving the properties from storage. The state of component to be stored in a non-volatile place for later retrieval.
(4) Customizers : Modifiying the appearance and behaviour at the time of building, and run time.
Example :
import Java.awt.Graphics;
import Java.beans.PropertyChangeListener;
import Java.beans.PropertyChangeSupport;
import Java.io.Serializable;
import Javax.swing.JComponent;
public class MyFirstBean extends JComponent implements Serializable
{
priavate String caption;
private final PropertyChangeSupport ob = new
PropertyChangeSupport( this );
public String getCaption()
{ return this.caption; }
public void setCaption ( String caption )
{
String oldcaption = this.caption;
this.caption = caption;
this.ob.firstPropertyChange( "caption", oldcaption, caption );
}
public void addPropertyChangeListener ( PropertyChngeListener listener )
{
this.ob.addPropertyChangeListener (listener);
}
public void removePropertyChangeListener ( PropertyChangeListener listener )
{
this.ob.removePropertyChangeListner (listnere);
}
protected void paintComponent ( Graphics g )
{
g.setColor ( getForeground() );
int height = g.getFontMetrics ().getHeight ();
paintString ( g, this.caption, height );
}
private void paintString ( Graphics g, String str, int height )
{ ( str != null )
g.drawString ( str, 0, height )
}
}
Q.8. What are class loaders ? Explain encryption techniques & digital signature. (20)
Ans. Class file contains the code for all the methods of the class. These class files need to be interpreted by a program that can translate the instruction set of the virtual machine into the machine language of the target machine. The virtual machine interpreter loads only those class files that are needed for the execution of a program.
The steps that the virtual machine carries out are:
1. The virtual machine has a mechanizm for loading class files, for example, by reading the files from disk or by requesting them from the web. It uses this mechanism to load the contents of the NewProgram class file.
2. If the NewProgram class has instance variables or superclasses of another class type, these class files are loaded as well. The process of loading all the classes that a given class depends on is called resolving the class.
3. The virtual machine then executes the main() method in NewProgram.
4. If the main() method requires additional classes, then other methods that the main () calls are loaded next. The architecture of class loader is shown below:
Fig. Flow of data and control.
The class loading mechanism uses at least three class loaders:
(1) The bootstrap class loader : The bootstrap class loader loads the system classes. It is an integral part of the virtual machine and is usually implemented in C. There is no ClassLoader object corresponding to the bootstrap class loader. For example, String.class.getClassLoader( ) returns null.
(2) The extension class loader : The extension class loader loads a standard extension from the jre/lib/ext directory. The extension class loader is implemented in Java.
(3) The system class loader : The system class loader loads the application classes. It locates classes in the directories. This class loader is also implemented in Java.
Encryption : Encryption is the process of encoding a text so that its original meaning is lost. Decryption is the opposite process, a mechanism to reveal the original message from the encrypted one. The term encipher and decipher are used respectively. The original or unaltered version of the message is termed as plain text and the encrypted message is called cipher text.
- Symmetric Encryption : It is the simplest but very efficient form of encryption. Here one secret key is shared between the communicating parties say sender and receiver with encrption and procedures being mirror images of each other.
- Asymmetric Encryption/Public key Encryption : Unlike the symmetric encryption it uses two separate keys for encryption and decryption called private-public key pair. The sender encrypts the message with his private key. Prior to this operation sender must sent its corresponding public key to the receiver. On receiving the encrypted text, the public key is used to decipher the original plain text. The major advantage in asymmetric encryption lies with the fact that it incurs quite high computational expense for an attacker. But on the other hand its applications is limited both security and efficiency are desired. RSA is an example of public key encryption.
Digital Signatures : Digital signature is an important cryptographic primitives used for authentication, authorization and non-repudiation. An asymmetric encryption algorithm such as RSA can be used to create and verify digital signature. The simplest form of the protocol works as follows.
1.) Sender encrypts the document with its private key, thereby singing the document
2.) Sender sends the signed document to receiver.
3.) Receiver deciphers the document with Sender's public key, thereby verifying the signature.
The strength of the digital signature lies with the fact that although the public-private key pair for asymmetric encryption is mathematically related, it is computationally infeasible to derive the private key from the corresponding public key.
A digital signature must meet the following two properties :
(1.) It must be unforgeable : If an entity sings a document M with signature S(M), it is not possible for other entity to produce the same pair (M, S(M)>.
(2.) It must be authentic : If someone R receives a digital signature from S, R must be able to verify that the signature is really from S.
In reality digital signature creation & verification are performed using the combination of hash function and asymmetric encryption. To create a digital signature the sender first computers the message authentication code(MAC) or hash of the original message & append the code with the message. Then the hash code is encrypted using asymmetric encryption. On the reception end the receiver uses the same hash algorithm to compute the hash code of the message decryption the encrypted message using the corresponding public key and compares the hash value.
If the message is altered, then the finger print of the altered message will not match the fingerprint of the original message. If the message & its fingerprint are delivered separately, then the recipient can check whether the message has been tampered or not. Public key cryptography is based on the notion of public key & private key. Even though everyone knows your public key, the can't compute your private key in your lifetime, no matter how many computing resources they have available. It may seem difficult to believe that nobody can compute the private key from the public keys, but nobody has ever found an algorithm to do this for the encryption algorithms. If the keys are sufficiently long brute force would require more computations. There are two kinds of public/private key pairs : for encryption and for authentication. If anyone sends you a message that was encrypted with your public encryption key, then you can decrypt it with your private decryption key. The verification passes only for messages that you signed and it fails if anyone else used his key to sign the message
When the Transferable object encapsulates data, it makes the data available to DragTarget. For a local transfer within the same JVM. Transferable provides an object reference. When invoking a Drag & Drop operation, various drag and drop operations are requested such as:
ACTION_NONE no action taken
ACTION_COPY the DragSource leaves the data intact
ACTION_MOVE the DragSource deletes the data upon successful completion of the drop.
DIGRAM HERE
Q.7. Explain the bean writing process. Explain building an application with beans. (20)
Ans. Java Bean is a softwear component written in Java, provides portability, platform-independent component model, and re-usability. You can add these components into applets, applications, or with other bean components.
By nature, beans are dynamic like other software components; these can be changed or customized.
The JavaBeans architecture was built through a collaborative industry effort and enables developers to write reusable components in the Java programming language.
With the Java Beans API you can create re useable, platform-independent components.
There are three types of benas:
(i) Visible Bean : A bean component that is visible to an end user, such as a button or any graphical component, that is used with GUI.
(ii) Invisible Bean : A bean that added with any application but not visible to the end user on GUI, for example checking the spelling of a document.
(iii) Container Bean : A bean can contain another bean component, is called the container bean for example a tree bean can contain another component like images, labels, etc.
The bean is created by combining the following components:
- Properties define the characteristics of the bean. It can be change at design time or run time if it is not read only and some mutator methods are given in its implementation.
- Events to momunicate with other beans.
- Methods can be called from other beans or from the environment or application in that it is added.
Advantages of beans : There are following advantages of Java Bean components:
(1) It supports or provide "write-once, run-anywhere" paradigm.
(2) Three component of the bean are exposed to an application builder tool.
(3) It has to run in different environment, so that, it is designed correctly.
(4) It's configuration setting is stored and helps to persist its state and can be used later.
(5) A Bean may receive events and can communicate with other by generating the events, if it is registered with events.
States of Bean : Bean is a resusable software component. So as software hs its development life cycle similarly bean component has its own states. These states defines its lifecycle, and are as following;
- Consturaction State : In this state, the bean is under coding phase. The developer busy in writing the code for it.
- Build State : Bean is in build state, where after construction, it is added with any application.
- Run State: As the container application runs, then bean is in run state.
Characteristics of bean :
(1) Communication : One bean can communicate with other bean and application in that it is build. By message passing to method, it do communication.
(2) Introspection : It is an automatic process to analyze the properties, evens and methods.
(3) Persistance : A bean persists by storing and retrieving the properties from storage. The state of component to be stored in a non-volatile place for later retrieval.
(4) Customizers : Modifiying the appearance and behaviour at the time of building, and run time.
Example :
import Java.awt.Graphics;
import Java.beans.PropertyChangeListener;
import Java.beans.PropertyChangeSupport;
import Java.io.Serializable;
import Javax.swing.JComponent;
public class MyFirstBean extends JComponent implements Serializable
{
priavate String caption;
private final PropertyChangeSupport ob = new
PropertyChangeSupport( this );
public String getCaption()
{ return this.caption; }
public void setCaption ( String caption )
{
String oldcaption = this.caption;
this.caption = caption;
this.ob.firstPropertyChange( "caption", oldcaption, caption );
}
public void addPropertyChangeListener ( PropertyChngeListener listener )
{
this.ob.addPropertyChangeListener (listener);
}
public void removePropertyChangeListener ( PropertyChangeListener listener )
{
this.ob.removePropertyChangeListner (listnere);
}
protected void paintComponent ( Graphics g )
{
g.setColor ( getForeground() );
int height = g.getFontMetrics ().getHeight ();
paintString ( g, this.caption, height );
}
private void paintString ( Graphics g, String str, int height )
{ ( str != null )
g.drawString ( str, 0, height )
}
}
Q.8. What are class loaders ? Explain encryption techniques & digital signature. (20)
Ans. Class file contains the code for all the methods of the class. These class files need to be interpreted by a program that can translate the instruction set of the virtual machine into the machine language of the target machine. The virtual machine interpreter loads only those class files that are needed for the execution of a program.
The steps that the virtual machine carries out are:
1. The virtual machine has a mechanizm for loading class files, for example, by reading the files from disk or by requesting them from the web. It uses this mechanism to load the contents of the NewProgram class file.
2. If the NewProgram class has instance variables or superclasses of another class type, these class files are loaded as well. The process of loading all the classes that a given class depends on is called resolving the class.
3. The virtual machine then executes the main() method in NewProgram.
4. If the main() method requires additional classes, then other methods that the main () calls are loaded next. The architecture of class loader is shown below:
Fig. Flow of data and control.
The class loading mechanism uses at least three class loaders:
(1) The bootstrap class loader : The bootstrap class loader loads the system classes. It is an integral part of the virtual machine and is usually implemented in C. There is no ClassLoader object corresponding to the bootstrap class loader. For example, String.class.getClassLoader( ) returns null.
(2) The extension class loader : The extension class loader loads a standard extension from the jre/lib/ext directory. The extension class loader is implemented in Java.
(3) The system class loader : The system class loader loads the application classes. It locates classes in the directories. This class loader is also implemented in Java.
Encryption : Encryption is the process of encoding a text so that its original meaning is lost. Decryption is the opposite process, a mechanism to reveal the original message from the encrypted one. The term encipher and decipher are used respectively. The original or unaltered version of the message is termed as plain text and the encrypted message is called cipher text.
- Symmetric Encryption : It is the simplest but very efficient form of encryption. Here one secret key is shared between the communicating parties say sender and receiver with encrption and procedures being mirror images of each other.
- Asymmetric Encryption/Public key Encryption : Unlike the symmetric encryption it uses two separate keys for encryption and decryption called private-public key pair. The sender encrypts the message with his private key. Prior to this operation sender must sent its corresponding public key to the receiver. On receiving the encrypted text, the public key is used to decipher the original plain text. The major advantage in asymmetric encryption lies with the fact that it incurs quite high computational expense for an attacker. But on the other hand its applications is limited both security and efficiency are desired. RSA is an example of public key encryption.
Digital Signatures : Digital signature is an important cryptographic primitives used for authentication, authorization and non-repudiation. An asymmetric encryption algorithm such as RSA can be used to create and verify digital signature. The simplest form of the protocol works as follows.
1.) Sender encrypts the document with its private key, thereby singing the document
2.) Sender sends the signed document to receiver.
3.) Receiver deciphers the document with Sender's public key, thereby verifying the signature.
The strength of the digital signature lies with the fact that although the public-private key pair for asymmetric encryption is mathematically related, it is computationally infeasible to derive the private key from the corresponding public key.
A digital signature must meet the following two properties :
(1.) It must be unforgeable : If an entity sings a document M with signature S(M), it is not possible for other entity to produce the same pair (M, S(M)>.
(2.) It must be authentic : If someone R receives a digital signature from S, R must be able to verify that the signature is really from S.
In reality digital signature creation & verification are performed using the combination of hash function and asymmetric encryption. To create a digital signature the sender first computers the message authentication code(MAC) or hash of the original message & append the code with the message. Then the hash code is encrypted using asymmetric encryption. On the reception end the receiver uses the same hash algorithm to compute the hash code of the message decryption the encrypted message using the corresponding public key and compares the hash value.
If the message is altered, then the finger print of the altered message will not match the fingerprint of the original message. If the message & its fingerprint are delivered separately, then the recipient can check whether the message has been tampered or not. Public key cryptography is based on the notion of public key & private key. Even though everyone knows your public key, the can't compute your private key in your lifetime, no matter how many computing resources they have available. It may seem difficult to believe that nobody can compute the private key from the public keys, but nobody has ever found an algorithm to do this for the encryption algorithms. If the keys are sufficiently long brute force would require more computations. There are two kinds of public/private key pairs : for encryption and for authentication. If anyone sends you a message that was encrypted with your public encryption key, then you can decrypt it with your private decryption key. The verification passes only for messages that you signed and it fails if anyone else used his key to sign the message
1 comments:
I have read your blog its very attractive and impressive. I like it your blog.
ReplyJavaEE Training in Chennai JavaEE Training in Chennai
Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai
Java Online Training Java Online Training Core Java 8 Training in Chennai Java 8 Training in Chennai
Post a Comment