Featured

    Featured Posts

ADVANCE JAVA MAY 2015 Paper Code CSE-404-E

ADVANCE JAVA
May 2010
Paper Code: CSE-404-E

Q.1. How object oriented programming language concepts are better than structured programming ? Explain inheritance with example.
Ans :  Object-oriented programming(OOP) is a programming paradigm using "objects"- data structures consisting of data fields and methods together with their interactions - to design applications and computer programs.  Programming techniques may include features such as data abstraction, encapsulation, messaging, modularity, polymorphism, and inheritance.
        Object Oriented Programming(OOP) approache binds the dat and the functions that operate on that data into a single entity.  Such as entity is called an object.  Functions of an object can only access its data.  You can't access the data directly.  For example, if you want to read a data item in an object, you call a member function in the object, it will read the data item and return the value to you.  This secures data from any changes from outside.  Thus, OOP gives more emphasis on data.
        A C++ program typically consists of a number of objects which communicate with each other by calling one another's member functions.  Calling an object's member functions is also referred to as sending a message to the object.  The organization of a C++ program is shown in fig.

figure here--------

     Objects are independent of each other.  They are responsible for managing their own state and offering services to other objects.  Therefore, new objects can be easily added whenever necessary.
OOP have the following features.
  • OOP is more data oriented.
  • Programs are made up of objects which model real-world entities.
  • Data and Functions are binded together in an object.
  • Data security exists.
  • Objects communicate through functions.
  • Objects communicate through functions.
  • Addition of new data and function(i.e. object) is easy.
  • OOP follows bottom-up approach.


Ineritace :  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: In this type of inheritance, a single sub class is derived from a single base class.
  2. Multiple Inheritance: In Multiple Inheritance, there is more than one base class from which the child class is derived.  This results in the duplication of data with the derived class.  Java does not directly support multiple inheritance.  This is because different classes may have different variables with same name that may be cotradicted and can cause confusions in JVM, thus resulting in errors.  We can extend one class only to avoid ambiguity problem with JVM.  In interface we have to define the functions.
  3. Multilevel Inheritance: In this inheritance, a class derives another class, and from the derived class, another sub class is derived.
  4. Hybrid Inheritance: There may occur situations where we need to apply two or more type of inheritance in the design of a program.  For each cases, hybrid inheritance is used.


Q.2. Explain the method of making URL connections.  Also explain how E-mails are sent.
Ans. Methods of URL Connection : A framework is provided by Java, using java.net package through several interfaces, classes, and abstract classes for handling URL(Uniform Resource Locator).  Using this framework, we can easily create sum function of web browser and can be embedded in an application.
       Before discussing the concept in-depth let's  have a description about two important classes is given below :
     (i)  Class URI : The term URI stands for Uniform Resource Identifier.  It create an instance of URL, and those are used to parse the string, and also providing various methods.  Every URL, is a URI, but not every URI, is a URL.
       On the base of conceptual difference between URIs and URLs, two different classes are given with their characteristics and functionalities.
     (ii) Class URL : Without URL, browser cannot make out the information about web.  URL identifies a resource anywhere on the Internet.  The introduction or URLs came up with WWW.
Web is a collection of protocols and different file formats.

Table: Methods of Java-net.URL class----

     (iii) Class URLConnection : The class URLConnection gives some additional information about web resource.  The class provides some methods by which you can send the request to server.  The class is actually abstract.  There is only constructor to create instance of URLConnection.
      URLConnection(URL urlString) creates a new URLConnection object for the URL urlString.  This constructor can be called only by a subclass of the URLConnection class; and subclass will gives the implementations of the various URLConnection methods for a specific protocol.
Example :
URL http_url = new URL("http://www.posthatke.com") ;
URLConnection urlc = new URL Connection(fttp_url ) ;
There is another way to create an instance of URL Connection, by invoking the openConnection() method of URL class, that return an object of URLConnection
Example :
URL http_url = new URL( "http//www.posthatke.com") ;
URLConnection urlc = http_url.openconnection() ;

Table : Method of java.net.URLConnection class

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;
     }
   }
}


Q.3. Explain the following networking concepts :
(i) Advanced connection management
(ii) Metadata.
Ans. (i) Advanced Connection Manangement : Networking means transmitting data from one device to another device on the network, but both must use the same protocol for transmission.  There is an array of stack, called protocol stack, that involves everything from giving the data to physical device by converting that in  voltage pulse to delivering data streams to applications for which it was destined to.

Fig : Stack of layer

     Each layer provides an abstraction  and dedicated to a specific fix set of job.  The intermediate layers also work as an interface between its upward and downward layer, first and then the last.
     Each layer communicates only with its immediate above and below layers.  Encapsulation and decapsulation are two mechanism, that embed each layer's packets into the immediately below layer packet, and reverse the process at the data moves up at the receiving machine, respectively.
     As internet is a bunch of networks of different types of environments.  The internet is exclusively the worldwide set of connections of TCP/IP networks which use IP address and protocols under the

Q.5. What are Java swing ? How to implement a tree using Java swing.    (20)
 Ans. Java swing : Swing is a set of packages that are built on top of AWT which provides a large number of inbuilt predefined classes.
       Swing class provides a large set of components such as toolbars, progressbar, text fields and timers.  Swings provides a large set of built-in controls such as tree, image buttons, sliders, tabbed panes, toolbars, tables, color choosers etc.
       Swing provides several UI components of which, few are:
  • JOptionPane : Mkes it easy to pop up a standard dialog box.
  • JPanel : A generic lightweight container.
  • JpasswordField : It allows the editing of a line of text where the user views some special characters in place of original characters.
  • JPopupMenu : It provides a pop-up menu.
  • JProgressBar : It is a component that displays an integer value within an interval.
  • JRadioButton : A radio button cn be selected or deselected displaying its state.
  • JScrollBar : It gives an implementation of the scrollbar.
  • JSeparator : It provides a menu separator.
  • JSlider : It is a component that lets the user select a value by sliding knob.
  • JTable : It presents the data in a two-dimensional format.
Program to implement a tree using Java swing.

import Java.awt.*;
import Javax.swing.*;
import Javax.swing.tree.*;
import Java.awt.event.*;
public class SimpleTree extends JFrame {
public static void main(string[] args) {
new simple tree();
public SimpleTree() {
super("Creating a Simple JTree") ;
WindowUtilities.setNativeLookAndFeel() ;
addWindowListener(new ExitListener()) ;
Container content = getContentPane() ;
Object[] hierarchy = {"1. CHAPTER 1",
new Object[] { "1.1 INTRODUCTION TO JAVA",
"1.1.1 History of JAVA",
"1.1.2 JAVA and Internet",
"1.1.3 JAVA Virtual Machine",
"1.1.4 JAVA's Magic : The Byte Code",
"1.1.5 Features of JAVA',
"1.1.6 JAVA Environment"},
new Object[]{ "1.2 DATA TYPES & OPERATORS"},
new Object[] { "1.3 ARRAYS",
"1.3.1 Declaration of Array Variables",
"1.3.2 Array Construction",
"1.3.3 Initialization of Array",
"1.3.4 Array Access",
"1.3.5 Arrays of Characters"},
new Object[] { "1.4 CONTROL STATEMENTS"},
new Object[] { "1.5 A SAMPLE PROGRAM IN JAVA"},
new Object[] { "1.6 CLASSES & METHODS",
"1.6.1 Constructor",
"1.6.2 Garbage Collection"},
new Object[] {"1.7 INHERITANCE",
"1.7.1 Single Inheritance",
"1.7.2 Multiple Inheritance",
"1.7.3 Multilevel Inheritance",
"1.7.4 Hybrid Inheritance",
new Object[] {"1.8 INTERFACE"},
new Object[] {"1.9 PACKAGES"},
new Object[] {"1.10 EXCEPTION HANDLING",
"1.10.1 try and catch with multiple catch clause,"
"1.10.2 throw and throws",
"1.10.3 finally"},
new Object[] {"1.11 MULTITHREADING",
"1.11.1 States of Thread"},
new Object[] {"1.12 COLLECTIONS"},
new Object[] {"1.13 I/O STREAMS",
"1.13.1 Working with InputStream and OutputStream",
"1.13.2 Working with Reader and Writer"},
new Object[] {"1.14 AWT"},
new Object[] {1.15 APPLET PROGRAMMING",
DefaultMutableTreeNode root = processHierarchy(hierarchy) ;
JTree tree = new JTree(root) ;
content.add(new JScrollPane(tree), BorderLayout.CENTER ;
setSize(275, 300) ;
setVisible(true) ;
}
private DefaultMutableTreeNode processHierarchy (object[] hierarchy) {
DefaultMutableTreeNode node = new
DefaultMutableTreeNode(hierarchy[0]) ;
DefaultMutableTreeNode child;
for(int i=1; i<hierarchy,length; i++) {
object nodeSpecifier = hierarchy[i] ;
if (nodSpecifier instanceofobject[])  // Ie node with children
child = processHierarchy((object[]) nodeSpecifier) ;
else
child = new DefaultMutableTreeNode(nodeSpecifier) ;  // le Leaf
node.add(child) ;
}
return(node) ;
}}
import Javax.swing.*;
import Java.awt.;
public class WindowUtilities {
public static void setNativeLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) ;
} catch(Exception e) {
System.out.println(" Error setting native LAF : " +e) ;
} }
public static void setJavaLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getCross PlatformLookAndFeelClassName());
} catch(Exception e) {
system.out.println("Error setting Java LAF : "+e) ;
} }
public static void setMotifLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel") ;
} catch(Exception e) {
System.out.println("Error setting MotifLAF : "+e ) ;
}
  }
public static JFrame openInJFrame(Container content, int Width, int height, String title, Color bgColor) {
JFrame frame = new JFrame(title) ;
frame.setBackground(bgColor) ;
content.setBackground(bgColor);
frame.setSize(width, height);
frame.setContentPane(content) ;
frame.addWindowListener(new ExitListener() ) ;
frame.setVisible(true) ;
return(frame) ;
}
public static JFrame openInJFrame(Container content, int width, int height, String title ;
{
   return (openInJFrame( content, width, height, title, color.white ) ) ;
}
public static JFrame openInJFrame(Container content, int width, int height) {
  return(openInJFrame(content, width, height, content.getClass().getName(), Color.white)) ;
    }
}
import Java.awt.* ;
import Java.awt.event.* ;
public class ExitListner extends WindoAdapter {
public void windowClosing(WindowEvent event) {
System.exit(0) ;
   }
}
The output interface would look like :
Figure here---------


Q. What are digital Signatures ?  Explain.
Ans. Digital signature is an important cryptographic primitives used for uthentication, authoriztionand 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 in feasible to derive the private key from the corresponding public key.
     A digital signature must meet the following two properties.
  1. It must be unforgettable :  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 and 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 and append the code with the message.  Then hash code is encrypted using asymmetric encryption.  On the reception end the receiver users 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 and 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 and private key.  Even though everyone knows your public key, they won'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 to sign the message.


  1. Java threads and Interrupts in Java programming language
  2. Abstract classes and Generic function in Java
  3. Callback functions in Java Programming language
  4. Constructors in programming language
  5. Static components and constants concept in programming language
  6. Data encapsulation in programming language.
  7. Java threads and Interrupts in Java programming language

MDU ADVANCE JAVA Dec 2016 CSE-404-F SAMPLE PAPER





Q.1. Explain the following with examples :           (20)
(a) Control statements in in JAVA.
(b) Multithreading in JAVA.
Ans. (a) Control statements in JAVA : Java programs is a set of statements that either executes sequentially or in the order in which they appear. There may arise situations in which a program breaks the normal sequential flow and jumps to another part of the code. This condition is called branching.  Branching can either be conditional or unconditional. Conditional branching occurs on a particular situation or a statement in the program code while unconditional branching occurs without any particular decision. Java deals with different control and iterative statements listed below. The control statements are :
(i) if-else loop
(ii) switch statement
(iii) while loop
(iv) do-while loop
(v) for loop
(i) if-else loop : It is a powerful decision making statement that is used to control the flow of execution of statements. The syntax for if loop is :
if (expression)
(ii) Switch Statement : Switch is an another decision-making statement that can be used as an alternative to if statement. It is a special multi-way decision maker that checks whether an expression matches one of the given values. The syntax is:
switch (expression )
{
case value 1:
statement 11;
statement 12;
break;
case value 2:
statement 21;
statement 22;
break;
.
.
.
case value n :
statement n;
break;
default:
statement;
}
(ii) While loop : While loop is used when we are not sure if a loop will execute or not. If the condition is true, then loop will continue until the condition satisfies.
Its syntax is:
while (expression)
{
    //Block of statements;
}
(iv) do-while loop : do-while loop is a repetitive loop supported by Java. It's an exit condition loop i.e. the set of statement will execute first, and then at the exit time the condition will be checked for repetition. If the condition return true then the loop will re-execute the statements otherwise it will terminate.
Its syntax is:
do
{
    Block of statements
    .............
}      while (expression)
(v) for loop : for loop is the simplest loop in Java. It contains three expressions :
- initial expression : used to initialize the counter of the loop
- termination expression : used to give a termination condition on the loop
- steps expression : used to either increase or decrease the value of the counter
All above three expressions are optional, according to need of the logic, we will add in for loop.
The syntax for loop is :
for (initial expression; termination expression; steps expression)
{
   Body of the loop;
}


(b) Multithreading in JAVA : A thread is a stream of code execution. This means that a single program can perform more than one task at the same time. Thread-based multitasking deals with the application program. A thread can be loosely defined as a separate stream of execution that takes place simultaneously. Every thread has a name for identification.
Initially, when a Java program starts, it has only one thread, i.e. main thread. Threads can be created in two ways : one method is to create a class as the subclass of thread class. The example related to the first method is explained :
class New_Thread extends Thread
{
   New_Thread()
{
  start();
}
Public void exec ()
{
   \\ Block of code
}
}
We can create and start a thread of this type as :
New_Thread th1 = new New_Thread();
Another method to create a thread is to declare a class that implements a Runnable interface. The example related to this method explained below:
class New_Thread implements Runnables
{
  Thread th1;
   New_Thread()
{
th1 = new Thread (this, "Second");    //this is used to pass class reference
thread start();
}
public void exec()
{
  //Block of code
}
}
This code would then create a thread and start it as :
New_Thread th1 = new New_Thread ();

States of a Thread : A thread is a small part of the process dedicated to perform certain job. The process has its own lifecycle, & at any instant of time a process will be in any of the state. Similarly, a thread will also have a life cycle & will be in any of the following state at any instant of time :
(i) New Thread
(ii) Runnable
(iii) Blocked
(iv) Waiting
(v) Terminated
The figure shows five states of the thread.

             figure             States of a Thread

  1. New State : When a thread object is created, a thread is born. This state is called New state. At this stage, the new thread can start & move to Runnable state or this new thread can be killed immediately. Then it is called Dead thread. 
  2. Runnable : It means that the thread is ready for execution and is waiting for the availability of the processor for execution.  
  3. Blocked : A thread is in a blocked state when it is not allowed to enter the Runnable state.  This can happen when a thread is either suspended or sleeping.  At this stage, the thread is not considered dead. 
  4. Waiting : This is the state when a thread is waiting for the processor either to its newborn state or due to to the round-robin scheduling of the processor. 
  5. Terminated : A thread is considered terminated when it has been killed.




Q.2. How servers are implemented ? Give suitable example of advanced socket programming.    (20)
Ans. To implement networking in Java, java.net package classes, these give access to IP address, & a range of methods related to TCP, UDP, & URL, I/O stream classes are also used to read and write data from and to communication channel.
The virtual-stream supports IO stream to transport data from & to either of the connection. There are two important classes, participates in communication. InetAddress class using to provides IP address of target connection.  Socket class using to creates TCP connection.  Once a connection has been created, we bind the both end socket with their streams, and communication will start by writing & reading data on these streams to and from remote application.
     Before looking at how to implement to server, let's have a look on the classes of java.net that are used to implement a server, are given below :
(i) Class InetAddress : Computer on internet is identified by IP address, that is currently in two version with different size, in IPv4 it is 32-bit long and in IPv6 it is 128-bit long.  InetAddress provides an abstraction to access IP address.

fig here

There is no constructor of this class.  The class provides some static methods to create the instance of the class i.e. an object.

(ii) Class Server Socket :  The ServerSocket class provides the facility by which a server accepts a connections requested from clients across the network.  The class creates a Socket for individual client connection.  After socket creation, an InputStream and an OutputStream will be created for communicating with client.

Fig. ServerScocket

The fundamental mechanism for implementing a server is to open a ServerSocket with a specific and certain local port number.  The ServerSocket will start to wait for connection.  As client generates the request to connect to this port, the connection will be established.
           ServerSocket is constructed by choosing a port on the local machine. This port number should be in the range 1-65536; however, ports 1-1023 are reserved for system services and can be used only by the machine administrator.
         A server accepts the explicitly connection request from a ServerSocket to obtain a client's Socket connection. As the ServerSocket is created, operating system started to accept the connections from clients, & insert in a queue, & delete one-by-one as the server call the accept() method.
ServerSocket(int portNumber) throws IOException creates a ServerSocket that listen on the specified port portNumber and countValue specified the number of outstanding connection requests.
ServerSocket ssckt = new ServerSocket(1889,40);

(iii) Class Socket : A Socket represents a TCP connection with a machine on network.  This class facilitate in establishing the stream-based channel with a remote machine.
 For TCP/IP communication, there is a need to create a Socket with the remote machine. The class Socket class creates a socket & automatically established a TCP connection, & throws an exception if it fails.  Socket address is the combination of two components : one is host id, which can be referring with the host name. IP address, and the port number.  The port no. is an integer value lie between 1 & 65536.  In fact, on every host there are 65536 different addresses.  But there must be a server, and dynamically listening on the specified port.

                                                        Fig. Socket

There are two constructor of the Socket class.  Creating a Socket object automatically connects to the given host and port.
Socket(String hostName, int portNumber) throws IOException creates a Socket object and connects to the given host on the given port number.
Socket sckt = new Scoket("mymac", 1889);
Socket(InetAddress hostAddress, int portNumber) throws IOException creates a Socket Object and connects to the given host address on the given port number.

InetAddress mac =  InetAddress.getByName("127.0.0.1");
Socket sckt   =  new Socket(mac.getAddress, 1889);
Socket sckt  = new Scoket ( mac.getAddress, 1889);
OR Socket sckt = new Socket " 127.0.0.1",1889);


Example of advantage socket programming
// Create a socket without a timeout
try {
        InetAddress addr = InetAddress.getByName("java.sun.com");
        int port = 80;
// This constructor will block until the connection succeeds
Socket socket = new Socket( addr, port);
}catch ( UnknownHostException e ) {
} catch ( IOException e ) {
}
// Create a socket with a timeout
try {
       InetAddress addr = InetAddress.getByName("java.sun.com");
       int port = 80 ;
       SocketAddress sockaddr = new InetSocketAddress (addr, port);
// Create an unbound socket
Socket sock = new Socket ();
// This method will block no more than timeoutMs.
// If the timeout occurs, SocketTimeoutException thrown.
int timeoutMs = 2000 ;   //2 seconds
sock.connect (sockaddr, timeoutMs);
} catch ( UnknownHostException e) {
} catch ( SocketTimeoutException e) {
} catch ( IOException e) {
}

Q.3. Explain the following :
(a) Design of JDBC
(b) LDAP.                      (20)
Ans. (a) Design of JDBC : JDBC is a set of Java API for executing SQL statements.  It's a collection of classes and interfaces : those facilitate to easy of the database & perform operations on the database.  Just by using few methods calls, we can easily interact with database.  The program design a good GUI interface then with knowing back processing of the database, without writing complex SQL statement, communication with database will become effortless.
      Types of JDBC Drivers :  There are various vendors of DBMS. Each vendor provides own API's (vendor specific APIs) to interact with Database.  It's a big problem to the developer to handle all these.  It has removed the need to access native APIs of specific vendor; it's the responsibility of the intermediate layer to make the native calls.

Figure Types of JDBC drivers

1. JDBC-ODBC Bridge-Type 1 : The type 1 driver provides a bridge between the JDBC API and the ODBC API.  The bridge is responsible to convert the JDBC calls to the corresponding ODBC calls and finally request to data source using ODBC libraries, that must be required on client tier.

Fig Type 1 driver

J2SE contains the classes for the JDBC-ODBC bridge & so that there is no need to install any other packages.  Though, you have to create Data Source Name (DNS) using ODBC manager.

2.  Native-API Partly Java Driver-Type 2 : Type 2 driver works on a combination of vendor-specific and Java implemented APIs to communicate with data source.  Here, the client makes the JDBC calls & these calls are interpreted into vendor-specific APIs, finally from vendor-specific APIs to database to perform the operation on it.  Database process the request & send the results back through the vendor-specific API, which will be forwarded back to the JDBC driver.  Now, here JDBC driver will convert the response to the JDBC standards and send to Java application.  The driver can be used where there is the need of, high-performance and large transaction volume.
Type 2 driver fig.


3. JDBC-Net Pure Java Driver-Type 3 : The type 3 driver works as middleware server between a numbers of Java clients to multiple vendor databases.  Type 2 is a multitier and vendor-neutral driver.  To connect with database server, client (Java client application) uses a server component in-between the client and database, that works as a gateway for multiple database servers.  The client application sends the request to intermediate data access server, by making the JDBC call through a JDBC driver.  The intermediate data access server completes the request to the Database using native driver.
Type 3 driver....fig.

4. Native-protocol Pure Java Driver-Type 4 :- Type 4 drivers converts JDBC API request directly to networking protocols of vendor-specific.  By making the socket connections with databse they communicate with database.  There is no need of other libraries or any middleware interface to deploy it.
Type 4 driver fig.

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:
  1. 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.
  2. Reliability & speed is improved by replication of LDAP data.
  3. LDAP also has a exceptionally strong security model that contains.
  4. ACLs to protect data inside the server. 
  5. Secure Socket Layers(SSL).
  6. Trasport Layer Security(TSL).
  7. Simple Authentication & Security Layer (SASL) protocols.
Applications : There are basic three basic applications of LADP in Java today;
  1. Access Control
  2. White Pages Services
  3. 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 the concept of :
a) Remote method invocation. 
b) Explain Java IDL.
 Ans. (a) Remote Method Invocation : Remote method invocation (RMI) frameworks provides a mechanism by which a Java object running in one JVM and call method of another Java object running in another JVM.  It provides object-to-object communication regardless of their location.  This allows an application to access and make the call to object method located remotely.
         In RMI jargon, the client object makes a remote call to the remote object located at server machine, called server object.  The computer running the application or a process that calls the remote method is called client, and the computer running the object that processes the call request from client, is called server.  If the server generates a remote call to an object resides on another machine JVM then the server becomes the client and the remote computer will become server.
       If we want two Java applications executing within different virtual machines to communicate with each other there are a couple of other Java-based approaches that can be taken besides RMI :
- Sockets
- Java Message Service(JMS)
       RMI is different with JMS in such a way that the object stays local at one JVM, but in JMSthe object (message) pass through across the network from one JVM to another JVM.
REMOTE METHOD INVOCATION FIG...

Architecture of RMI : Transparency is the one of the most important aspect of RMI designn. A method invocation on a remote has the same syntax as method invocation on a local object.  The RMI architecture supports to create a distributed application, in which one object call the method of remote object.
           Specifically, in RMI, the definition of a remote service is coded using a java interface.  The implementation of the remote service is coded in a class.  Therefore, the key to understanding RMI is to remember that interfces define behaviour and classes define implementation.
RMI system fig.
         The RMI architecture is high-level of abstraction.  It is constructed using three layer architecture.  The layered architecture gives a transparency for application architecture, mean implementation gives flexibility.
         The RMI is constructed using the following three abstract layers :
- The Stub-Skeleton Layer : The responsibility of this layer is to intercept and redirect the client request for method calls to remote object.
- The remote Reference Layer : It inter-prates and  manages between references, those are made by client to the remote object.
- Transport Layer : It provides the connectivity to machines.

Ans. (b) Java IDL : Java IDL (java Interface Definition Language) is a technology design for distributed objects; those are communicating with each other and running on different platform across the network.  It is similar to RMI but with one advantage that interaction among the object written in any programming language like C, C++ etc. including Java.
      IDL-Java Bridge Data Type Mapping : When data moves between IDL and a Java object, IDL automatically converts variable data types.
The java IDL, development Process are as know :
  1. Define the remote interface.
  2. Compile the remote interface.
  3. Implement the server.
  4. Implement the client.
  5. Start the applications.


Q.5. What are the progress indications? Explain. Wap implementing trees in JAVA. (20)
Ans. Progress indicators or progress bars are the new controls that gives the users some indications of the progress of an operation.  They were originally developed to cheek the progress of installation processes but are now frequently used for all time-consuming operations.  When we call JProgressBar, we can set the maximum and minimum value for the progress bar.  The inheritance diagram for JProgressBar class is as follow :
            

Java.lang.Object
                
Java.awt.Component
                
Java.awt.Container
                
Javax.swing.JComponent
                
Javax.swing.JProgressBar
               
Fig : Inheritance diagram for J Progress Bar

Table : Fields of JProgressBar class

Table : Constructors of JProgressBar class

Wap to implement trees in Java :
import Java.awt.*;
import Javax.swing.*;
import Javax.swing.tree.*;
import Java.awt.event.*;
public class SimpleTree extends JFrame {
public static void main(string[] args) {
new simple tree();
public SimpleTree() {
super("Creating a Simple JTree") ;
WindowUtilities.setNativeLookAndFeel() ;
addWindowListener(new ExitListener()) ;
Container content = getContentPane() ;
Object[] hierarchy = {"1. CHAPTER 1",
new Object[] { "1.1 INTRODUCTION TO JAVA",
"1.1.1 History of JAVA",
"1.1.2 JAVA and Internet",
"1.1.3 JAVA Virtual Machine",
"1.1.4 JAVA's Magic : The Byte Code",
"1.1.5 Features of JAVA',
"1.1.6 JAVA Environment"},
new Object[]{ "1.2 DATA TYPES & OPERATORS"},
new Object[] { "1.3 ARRAYS",
"1.3.1 Declaration of Array Variables",
"1.3.2 Array Construction",
"1.3.3 Initialization of Array",
"1.3.4 Array Access",
"1.3.5 Arrays of Characters"},
new Object[] { "1.4 CONTROL STATEMENTS"},
new Object[] { "1.5 A SAMPLE PROGRAM IN JAVA"},
new Object[] { "1.6 CLASSES & METHODS",
"1.6.1 Constructor",
"1.6.2 Garbage Collection"},
new Object[] {"1.7 INHERITANCE",
"1.7.1 Single Inheritance",
"1.7.2 Multiple Inheritance",
"1.7.3 Multilevel Inheritance",
"1.7.4 Hybrid Inheritance",
new Object[] {"1.8 INTERFACE"},
new Object[] {"1.9 PACKAGES"},
new Object[] {"1.10 EXCEPTION HANDLING",
"1.10.1 try and catch with multiple catch clause,"
"1.10.2 throw and throws",
"1.10.3 finally"},
new Object[] {"1.11 MULTITHREADING",
"1.11.1 States of Thread"},
new Object[] {"1.12 COLLECTIONS"},
new Object[] {"1.13 I/O STREAMS",
"1.13.1 Working with InputStream and OutputStream",
"1.13.2 Working with Reader and Writer"},
new Object[] {"1.14 AWT"},
new Object[] {1.15 APPLET PROGRAMMING",
DefaultMutableTreeNode root = processHierarchy(hierarchy) ;
JTree tree = new JTree(root) ;
content.add(new JScrollPane(tree), BorderLayout.CENTER ;
setSize(275, 300) ;
setVisible(true) ;
}
private DefaultMutableTreeNode processHierarchy (object[] hierarchy) {
DefaultMutableTreeNode node = new
DefaultMutableTreeNode(hierarchy[0]) ;
DefaultMutableTreeNode child;
for(int i=1; i<hierarchy,length; i++) {
object nodeSpecifier = hierarchy[i] ;
if (nodSpecifier instanceofobject[])  // Ie node with children
child = processHierarchy((object[]) nodeSpecifier) ;
else
child = new DefaultMutableTreeNode(nodeSpecifier) ;  // le Leaf
node.add(child) ;
}
return(node) ;
}}
import Javax.swing.*;
import Java.awt.;
public class WindowUtilities {
public static void setNativeLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) ;
} catch(Exception e) {
System.out.println(" Error setting native LAF : " +e) ;
} }
public static void setJavaLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getCross PlatformLookAndFeelClassName());
} catch(Exception e) {
system.out.println("Error setting Java LAF : "+e) ;
} }
public static void setMotifLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel") ;
} catch(Exception e) {
System.out.println("Error setting MotifLAF : "+e ) ;
}
  }
public static JFrame openInJFrame(Container content, int Width, int height, String title, Color bgColor) {
JFrame frame = new JFrame(title) ;
frame.setBackground(bgColor) ;
content.setBackground(bgColor);
frame.setSize(width, height);
frame.setContentPane(content) ;
frame.addWindowListener(new ExitListener() ) ;
frame.setVisible(true) ;
return(frame) ;
}
public static JFrame openInJFrame(Container content, int width, int height, String title ;
{
   return (openInJFrame( content, width, height, title, color.white ) ) ;
}
public static JFrame openInJFrame(Container content, int width, int height) {
  return(openInJFrame(content, width, height, content.getClass().getName(), Color.white)) ;
    }
}
import Java.awt.* ;
import Java.awt.event.* ;
public class ExitListner extends WindoAdapter {
public void windowClosing(WindowEvent event) {
System.exit(0) ;
   }
}
The output interface would look like :
Figure here---------



Q.6.Explain the following :
(a) Transparency and compositions    (20)
(b) Clipboard

Ans: (a) Transparency :-  Java 2D allows you to give transparency value to drawing operations, so that the graphic to be drawn, partially shows that underlying images.  AlphaComposite object has to create by Alphacomposite.getInstance to provide and set the transparency.  The object of AlphaComposite will be passed to setComposite method of Graphics2D object.  There are 8 built-in mixing rules, but the one normally used for drawing with transparency settings is AlphaComposite. SRC_OVER.  Alpha values range from 0.0F (completely transparent) to 1.0F (completely opaque).
Example :
import Java.awt.AlphaComposite ;
import Java.awt.Color ;
import Java.awt.Graphics ;
import java.awt.Graphics2D ;
import Java.swing.JFrame ;
import Java.swing.JPanel ;
public class TransparentRectangles extends Jpanel {
public void paint(Graphics g) {
super.paint(g) ;
Graphics2D g2d = (Graphics2D) g ;
g2d.setColor(Color.BLUE) ;
for (int i = 1; i<= 10; i++) {
g2d.setComposite(AlphaComposite.getInstance ( AlphaComposite.SRC_OVER, i*0. If)) ;
g2d.fillRect (50*i, 20, 40, 40) ;
    }
}
public static void main (String[] args) {
JFrame frame = new JFrame ("Transparent Rectangles") ;
frame.add(new TransparentRectangles() ) ;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
frame.setSize(590, 120) ;
frame.setLocationRelativeTo(null) ;
frame.setVisible(true) ;
   }
}

Ans. (b) Clipboard : In Java, there are actually two kinds of Clipboard-system and local.  The system clipboard corresponds to the usual idea of sharing data between otherwise independent applications running on the same computer.  Local Clipboards are visible only with a single Java application.  They are created by simply passing a name of the Clipboard constructor. A clipboard acts as a temporary staging area where application users store cut or copied information, including text, graphics, objects, and other data types.  It is a heavily exploited data sharing facility.  Therefore, when developing new applications, it makes sense to expend extra effort to support the clipboard, Netlecting clipboard functionallity can resulting in an application that gets complaints, requires new development, or-worst of all-never gets used.


Q.7. What are bean ?  Explain the naming pattern for bean components with suitable example.
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:
  1. 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. 
  2. 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.  
  3. 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. Does Java has security constraints ? Explain byte code verification and code signing.  (20)
Ans.  Yes, Java has security constraints.
Byte code verification :  When a class loader presents the bytecodes of a newly loaded Java platform class to the virtual machine, the bytecodes are first inspected by a verifier.  All classes except system classes are verified.  We can deactivate verification with the undocumented-noverify option.  For exaple:
       java -noverify NewProgram
The bytecode verifier traverses the bytecodes, constructs the type state information, and verifies the types of the parameters to all the bytecode instructions.  The figure shows the flow of data and control from the source code to the class loader and bytecode verifier and finally on to the Java virtual machine, which contains the interpreter and runtime system.  The bytecode verifier acts gatekeeper as it ensures that code passed to the Java interpreter is in a good state to be executed and can run without the fear of breaking the Java interpreter.  Imported code is not allowed to execute by any means until after it has passed the verifier's tests.
           Once the verifier is done, a number of important properties are known.  Knowing these properties makes the Java interpreter much faster, because it doesn't have to check anything.  There are no operand type checks and no stack overflow checks.  The interpreter can thus function at full without compromising reliability.  The properties are :
> There are no operand stack overflows or underflows.
> The type of the parameters of all bytecode instructions are known to always be correct.  Object field accesses are known to be legal -- private, public or protected.

Flow of data and control.......fig.-----

           The verifier permits only some bytecode sequences in valid programs and the verifier ensures that any given instruction operates on a fixed stack location that allows the JIT compiler to transform stack accesses into fixed register accesses.  Due to this, the JVM does not imply a speed penalty for emulation on register-based architectures when using a JIT compiler.  In the face of the code-verified JVM archetecture, it makes no difference to a JIT compiler whether it gets named imaginary registers or imaginary stack positions that need to be allocated to the target architecture's registers.  Code verification makes the JVM different from a classic stack architecture whose efficient emulation with a JIT compiler is more complicated and is carried out by a slow interpreter.

   The following verification checks are performed by the bytecode verifier.  It verifies that
  • > The byte stream is either truncated nor padded with extra bytes.
  • > The class bytes adhere to the correct format for the class itself, methods, fields and other components.
  • > There are no overflows of operands on the stack.
  • > There are no underflows of operands on the stack.
  • > The proper access specifiers of methods and field variables is defined.
  • > final classes are not subclassed.
  • > final methods are not overridden.
  • > final variables are assigned an initial value and not modified.
  • > methods are invoked with the correct number and types of arguments.
  • > final variables of the class are assigned with values of the correct type.
  • > no local variables is accessed before it has an assigned value.
  • > the class has one superclass.

Code signing :  One of the most important uses of authentication technology is signing executable programs.  If a program is downloaded, then we are concerned about damage that a program can do.  For example, the program could have been infected by a virus.  If we know where the code comes from and that it has not been tempered then we can be comfortable in using the program.  For this, we use authentication to verify where the code came from and then run the code with  a security policy that enforces the permissions that you want to grant the program, depending on its origin.  The most common use of code signing is to provide security when deploying.  Almost every code signing implementation will provides some sort of digital signature mechanism to verify the identity of the author or build system, and a checksum to verify that the object has not been modified.  Code signing is done on JAR files.
              The Java Archive(JAR) file format enables you to pile multiple files into a single archive file.  A JAR file contains the class files and auxiliary resources associated with applets and applications.  The general steps involved with code signing process are :
  1. Compile the code to the signed into class files.
  2. Creates a JAR files.
  3. Sign the JAR file.
  4. Export a public key certificate.
          The Java application that wants to accept the code only from a trusted source that has signed the code follows these steps :
  1. Import the certificate as a trusted certificate.
  2. Create a policy file indicating that such a principal should be trusted for certain permissions.
  3. Load the trusted code with your Java application.

ADVANCE JAVA

 

 

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.
(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);
}
}
}

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;
     }
   }
}

www.CodeNirvana.in

www.posthatke.com. Powered by Blogger.
Copyright © www.posthatke.com | Blogger Templates | Designed By posthatke.com