Vous êtes sur la page 1sur 62

CS606 JAVA PROGRAMMING LAB

Ex. No. : 1 Date Aim Objective : 01-08-11

Title: Study of Simple Java Program Using Threading.

: To write a program for thread concept using java. : 1. To understand the concept of thread in java program. 2. To demonstrate how to create a thread using java program. 3. To appreciate each threads priority. 4. To identify the status of each thread during program execution.

Pre lab

The procedure for creating threads based on the Runnable interface is as follows: 1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object. 2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method. 3. The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned. 4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception. Syntax: The Runnable Interface Signature public interface Runnable { void run(); }

Problem Description: Page No: 1

CS606 JAVA PROGRAMMING LAB

Audio clips are relatively easy to use in an applet. I created an AudioClip object using the applet getAudioClip() method, giving it the URL of the sound file located on the server. The clip can then be played using that object's play() or loop() methods. The buttons are initially disabled. When the corresponding sound clip, loading in a separate thread, finishes downloading, the button is enabled. Pseudo Code: 1. 2. 3. 4. Import Applet & AWT Packages into the program. Create a class and inherit applet class, and also implement an interface called runnable. Create an Audio clip variable & initialize a playing state variable as stopped as false. Initialize the init() method 4.1 Using getAudioClip() method - get the audio file. 4.2 If audiofile !=NULL then Create a thread and start a thread. 5. In start() method stopped:=false; 6. In Stop() method Stopped:=false; 7. In run() method 7.1 Set priority of a current thread as minimum. 7.2 Using while if its true If !stopped then Play an audio file. 7.3 Using try and catch statement Using sleep() method, it should sleep every 5secs of the audio file. Test Case: Since its a user level thread, in program itself we will give the resources such as audio file and thread execution.

Coding: Page No: 2

CS606 JAVA PROGRAMMING LAB

import java.applet.*; import java.awt.*; import java.net.*; /* <applet code="ex01.class" width=400 height=500> <param name="audio" value="beep.au"> </applet> */ public class ex01 extends Applet implements Runnable { private AudioClip beep; private boolean stopped=false; public void init() { beep=this.getAudioClip(this.getDocumentBase(), this.getParameter("audio")); if(beep!= null) { Thread t=new Thread(this); t.start(); } } public void start() { this.stopped=false; } public void stop() { this.stopped=false; } public void run() { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); while(true) { if(!stopped) beep.play(); try { Thread.sleep(5000); } catch(InterruptedException e){ } } } }

Output: D:\java\java lab>javac ex01.java Page No: 3

CS606 JAVA PROGRAMMING LAB

D:\java\java lab>appletviewer ex01.java

Result: Thus the program for simple thread using java is done & output is verified.

THREADING Review Questions: Page No: 4

CS606 JAVA PROGRAMMING LAB

1. How to create a thread? In the most general sense, you create a thread by instantiating an object of type Thread. Java defines two ways in which this can be accomplished.

You can implement the Runnable Interface You can extend the Thread class itself.

2. What is threaded programming and when it is used? Threaded programming is normally used when a program is required to do more than one task at the same time. Threading is often used in applications with graphical user interfaces; a new thread may be created to do some processor-intensive work while the main thread keeps the interface responsive to human interaction. The Java programming language has threaded programming facilities built in, so it is relatively easy to create threaded programs. However, multi-threaded programs introduce a degree of complexity that is not justified for most simple command line applications. 3. Differentiate threads start() and run() methods. The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns. The Thread class' run() method calls the run() method of the Runnable type class passed to its constructor. Subclasses of Thread should override the run() method with their own code to execute in the second thread. Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method. Howevever, the code will only be executed in a new thread if the start() method is used. 4. Can a class have more than one thread? Any Java class may be loaded and instantiated as part of a multi-threaded program. Since Java is fundamentally a multi-threaded programming language all classes should be designed with this possibility in mind, with a judgment whether it is likely and what its consequences would be.

Page No: 5

CS606 JAVA PROGRAMMING LAB

You should normally have enough information to judge whether your own classes are likely to be used in a multi-threaded context. If there is the no immediate requirement, avoid thread-proofing your class until that time comes. The Java API is used for general programming purposes that cannot be anticipated in advance, so thread safety considerations are usually noted in classes' API documentation. Many data storage and management classes in the java.util package are distinguished by their thread safety status because safety is usually a trade-off against the time-performance of key operations. 5. Why not override Thread to make a Runnable? There is little difference in the work required to override the Thread class compared with implementing the Runnable interface, both require the body of the run() method to be implemented. However, it is much simpler to make an existing class hierarchy runnable because any class can be adapted to implement the run() method. A subclass of Thread cannot extend any other type, so application-specific code would have to be added to it rather than inherited. Separating the Thread class from the Runnable implementation also avoids potential synchronization problems between the thread and the run() method. A separate Runnable generally gives greater flexibility in the way that runnable code is referenced and executed. 6. What are the ways to determine whether a thread has finished? isAlive join Determine if the thread is still running. Wait for a thread to terminate.

Ex. No. : 2 Date : 08-08-11

Title: Create a Simple Application using Applet. Page No: 6

CS606 JAVA PROGRAMMING LAB

Aim Objective

: To write a program for Applet using Java. : 1. To understand the need of an Applet in java program. 2. To demonstrate the life cycle of an Applet. 3. To recognize how to develop an Applet 4. To comprehend how to deploy the Applet.

Pre lab

A Java applet is a special kind of Java program that a browser enabled with Java technology can download from the internet and run. An applet is typically embedded inside a web page and runs in the context of a browser. An applet must be a subclass of the java.applet.Applet class. The Applet class provides the standard interface between the applet and the browser environment. Syntax: /* <applet code =MyApplet width=200 height=60> </applet> */ This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200 pixels wide and 60 pixels high.

Problem Description: Ultimate aim to play a audio file by click on a play button. The sound can be shut off with a call to stop() or once it time will be over.

Page No: 7

CS606 JAVA PROGRAMMING LAB

Pseudo Code: Import Applet & AWT Packages into the program. Create a class and inherit Applet class. Create a button as b Initialize the init() method 4.1. Set the bound for b to place a button in an applet. 4.2. Add the button in an applet. 5. Create an action () method with parameter e as Event. 5.1 if e.target():=b then Get the Audio URL & Play it. 5.2 if not Print Error Message. 1. 2. 3. 4.

Test Case: Sl # 1. Test Case Code TC01 Test Case Description If the user clicks out of play button in an applet window If the user exactly clicks on play button. Expected Result It wont play an audio file It will play an audio file from the given audio URL. It will play an audio just gives a error message Actual Result Not played Pass / Fail Pass

2.

TC02

Played at given audio URL.

Pass

3.

TC03

If given URL is not valid

Empty Applet Screen.

Fail

Coding: import java.applet.*; import java.net.*; import java.awt.*; /* <applet code="ex02.class" width=400 height=500> Page No: 8

CS606 JAVA PROGRAMMING LAB

<param name="audio" value="beep.au"> </applet> */ public class ex02 extends Applet { Button b=new Button("PLAY"); public void init() { b.setBounds(10,10,10,10); add(b); } public boolean action(Event e,Object o) { if(e.target==b) { try { URL u=new URL(this.getCodeBase(), this.getParameter("audio")); this.play(u); } catch(MalformedURLException me) { System.err.println("\n MalFormed URL Exception" +me); } return true; } return false; } }

Output: D:\java\java lab>javac ex02.java D:\java\java lab>appletviewer ex02.java

Page No: 9

CS606 JAVA PROGRAMMING LAB

Result: Thus the simple program for applet using java is done & output is verified.

APPLET Review Questions: 1. Which classes can an applet extend?

Page No: 10

CS606 JAVA PROGRAMMING LAB

An applet can extend the java.applet.Applet class or the java.swing.JApplet class. The java.applet.Applet class extends the java.awt.Panel class and enables you to use the GUI tools in the AWT package. The java.swing.JApplet class is a subclass of java.applet.Applet that also enables you to use the Swing GUI tools.

2. For what do you use the start() method? You use the start() method when the applet must perform a task after it is initialized, before receiving user input. The start() method either performs the applet's work or (more likely) starts up one or more threads to perform the work. 3. True or false: An applet can make network connections to any host on the Internet. False: An applet can only connect to the host that it came from. 4. How do you get the value of a parameter specified in the JNLP file from within the applet's code? You use the getParameter("Parameter name") method, which returns the String value of the parameter. 5. Which class enables applets to interact with JavaScript code in the applet's web page? The netscape.javascript.JSObject class enables applets to interact with JavaScript code in the applet's web page. 6. True or False: Applets can modify the contents of the parent web page. True:Applets can modify the contents of the parent web page by using the getDocument method of the com.sun.java.browser.plugin2.DOM class and the Common DOM API.

Ex. No. : 3 Date : 29.08.11

Title: Create a Simple Application using UDP and TCP Sockets. Page No: 11

CS606 JAVA PROGRAMMING LAB

Aim Objective

: To write a program for UDP & TCP using java. : 1. To know what is a socket in Java Program. 2. To demonstrate reading from and writing to a Socket. 3. To understand writing a Client/Server pair. 4. To know how to close the streams and sockets.

Pre lab Syntax:

1. Socket(String hostname, int port) Creates a socket connecting the local host to the named host and port; can throw an UnknownHostException or an IOException. 2. Socket(InetAddress ipAddress, int port) Creates a socket using a preexisting InetAddress object and a port; can throw an IOException. 3. InetAddress getInetAddress() Returns the InetAddress associated with the Socket object. 4. InputStream getInputStream() Returns the InputStream associated with the invoking socket. 5. OutputStream getOutputStream() Returns the OutputStream associated with the invoking socket.

Transmission Control Protocol


Problem Description: TCP (Transmission Control Protocol), which provides a reliable, connection-oriented service to the invoking application. It offers several additional services to applications, it provides reliable data transfer. TCP ensures that data is delivered from sending process to receiving process Page No: 12

CS606 JAVA PROGRAMMING LAB

correctly and in order. TCP thus converts IPs unreliable service between end systems into a reliable data transport service between processes. Pseudo Code: Client Side: 1. Import network package.
2. Create a class and throws Exception in main function. 3. CreateSocket method and initialize an object (cilentSocket).

4. Using While loop do the protocol procedure. 4a. Initialize FromServer & ToServer variable using BufferedReader class. 4b. Initialize outToClient variable using PrintWriter class. 5. Get the transactions information using the sockets. 6. Until type q transaction proceeds. 6a. If input is q it ends/quit using close() method. Server Side: 1. Import network package.
2. Create a class and throws Exception in main function. 3. Create ServerSocket method and initialize an object (Server).

4. Using While loop do the protocol procedure. 4a. Accept the server object through Socket method via connected object. 4b. Get the Internet Address using getPort() method. 4c. Initialize inFromUser & inFromClient variable using BufferedReader class. 4d. Initialize outToClient variable using PrintWriter class. 5. Get the transactions information using the sockets. 6. Until type q transaction proceeds. 6a. If input is q it ends/quit, using close() method.

Test Case: Sl # Test Case Code Test Case Description Expected Result Actual Result Pass / Fail

Page No: 13

CS606 JAVA PROGRAMMING LAB

1. 2. 3.

TC01 TC02 TC03

When some characters to be sent When some numbers to be sent When the client wants to quit by typing q.

Sent without any loss Sent without any data loss Closed

To be sent as it is. To be sent as it is. Closed

Pass Pass Pass

Coding: //ts.java import java.io.*; import java.net.*; class ts { public static void main(String argv[]) throws Exception { Page No: 14

CS606 JAVA PROGRAMMING LAB

String fromclient; String toclient; ServerSocket Server = new ServerSocket (5000); System.out.println ("TCPServer Waiting for client on port 5000"); while(true) { Socket connected = Server.accept(); System.out.println( " THE CLIENT"+" "+ connected.getInetAddress() +":"+connected.getPort()+" IS CONNECTED "); BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connected.getInputStream())); PrintWriter outToClient = new PrintWriter(connected.getOutputStream(),true); while ( true ) { System.out.println("SEND(Type q to Quit):"); toclient = inFromUser.readLine(); if ( toclient.equals ("q") ) { outToClient.println(toclient); connected.close(); break; } else { outToClient.println(toclient); fromclient = inFromClient.readLine(); if ( fromclient.equals("q") ) { connected.close(); break; } else System.out.println( "RECIEVED:" + fromclient ); } } } }} //tc.java import java.io.*; import java.net.*; class tc { public static void main(String argv[]) throws Exception { Page No: 15

CS606 JAVA PROGRAMMING LAB

String FromServer; String ToServer; Socket clientSocket = new Socket("localhost", 5000); BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(),true); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); while (true) { FromServer = inFromServer.readLine(); if ( FromServer.equals("q") || FromServer.equals("Q")) { clientSocket.close(); break; } else { System.out.println("Received: " +FromServer); System.out.println("SEND(Type q to Quit):"); ToServer = inFromUser.readLine(); if (ToServer.equals("q")) { outToServer.println (ToServer) ; clientSocket.close(); break; } else outToServer.println(ToServer); } } } } Output: Client System D:\java\java lab>javac tc.java D:\java\java lab>java tc Received: hi Page No: 16

CS606 JAVA PROGRAMMING LAB

SEND(Type q to Quit): hello Received: hw r u? SEND(Type q to Quit): am 5n :) Received: hw do u do? SEND(Type q to Quit): okay ll catch u later! bye D:\java\java lab>

Server System D:\java>javac ts.java D:\java>java ts TCPServer Waiting for client on port 5000 THE CLIENT /127.0.0.1:49182 IS CONNECTED SEND(Type q to Quit): hi RECIEVED:hello SEND(Type q to Quit): hw r u? RECIEVED:am 5n :) SEND(Type q to Quit): hw do u do? RECIEVED:okay ll catch u later! bye SEND(Type q to Quit): q Page No: 17

CS606 JAVA PROGRAMMING LAB

D:\java\java lab>

User Datagram Protocol (UDP)


Problem Description: UDP (User Datagram Protocol), which provides an unreliable, connectionless service to the invoking application. How might you go about doing this? sending side, you might consider using a vacuous transport protocol. In particular, on the sending side, you might consider taking the messages from the application process and passing them directly to the network layer; and on the receiving side, you might consider taking the messages arriving from the network layer and passing them directly to the application process. Page No: 18

CS606 JAVA PROGRAMMING LAB

Pseudo Code: Client Side: 1. Import network package.


2. Create a class and throws IOException in main function.

3. Initialize required variables. 4. Initialize DatagramSocket with the client port and initialize an object (cilentsocket). 5. Get the local host name using ia variable. 6. Using While loop do the protocol procedure. 6a. Get the data interms of bytes. 6b. If data will be bye then quit it using close() method. 6c. If data is not bye then clientsocket.send(new DatagramPacket(buffer,length of the string to be send, internet address ,server port)); 7. Receive the server information through receive() method.

Server Side: 1. Import network package.


2. Create a class and throws Exception in main function.

3. Initialize required variables. 4. Initialize DatagramSocket with the server port and initialize an object (serversocket). 5. Get the local host name using ia variable. 6. Receive the client information through receive() method. 7. Using While loop do the protocol procedure. 7a. Get the data interms of bytes. 7b. If data will be bye then quit it using close() method. 7c. If data is not bye then serversocket.send(new DatagramPacket(buffer,length of the string to be send, internet address ,client port)); Test Case: Sl # 1. 2. 3. Test Case Code TC01 TC02 TC03 Test Case Description When some characters to be sent When some numbers to be sent Expected Result Sent without any loss Sent without any data loss Actual Result To be sent as it is. To be sent as it is. Closed Pass / Fail Pass Pass Pass

When the client wants to Closed Page No: 19

CS606 JAVA PROGRAMMING LAB

quit by typing bye.

Coding: //UDPClient import java.io.*; import java.net.*; class UDPClient { public static DatagramSocket clientsocket; public static DatagramPacket dp; public static BufferedReader dis; public static InetAddress ia; Page No: 20

CS606 JAVA PROGRAMMING LAB

public static byte buf[]=new byte[1024]; public static int cport=789,sport=790; public static void main(String a[]) throws IOException { clientsocket=new DatagramSocket(cport); dp=new DatagramPacket(buf,buf.length); dis=new BufferedReader(new InputStreamReader(System.in)); ia=InetAddress.getLocalHost(); System.out.println("Client is Running.... Type 'STOP' to Quit"); while(true) { String str=new String(dis.readLine()); buf=str.getBytes(); if(str.equals("bye")) { System.out.println("Terminated..."); clientsocket.send(new DatagramPacket(buf,str.length(),ia,sport)); break; } clientsocket.send(new DatagramPacket(buf,str.length(),ia,sport)); clientsocket.receive(dp); String str2=new String(dp.getData(),0,dp.getLength()); System.out.println("Server: "+str2); } } } //UDPServer.java import java.io.*; import java.net.*; class UDPServer Page No: 21

CS606 JAVA PROGRAMMING LAB

{ public static DatagramSocket serversocket; public static DatagramPacket dp; public static BufferedReader dis; public static InetAddress ia; public static byte buf[]=new byte[1024]; public static int cport=789, sport=790; public static void main(String a[]) throws IOException { serversocket=new DatagramSocket(sport); dp=new DatagramPacket(buf,buf.length); dis=new BufferedReader(new InputStreamReader(System.in)); ia=InetAddress.getLocalHost(); System.out.println("Server is Running...."); while(true) { serversocket.receive(dp); String str=new String(dp.getData(),0, dp.getLength()); if(str.equals("bye")) { System.out.println("Terminated..."); break; } System.out.println("Client: "+str); String str1=new String(dis.readLine()); buf=str1.getBytes(); serversocket.send(new DatagramPacket(buf,str1.length(),ia,cport)); } } }

Page No: 22

CS606 JAVA PROGRAMMING LAB

Output: Server Side D:\java\java lab>javac UDPServer.java D:\java\java lab>java UDPServer Server is Running.... Client: hi deepu hw r u? am dng gr8 argata, den wassup? Client: nothing spl here, over thr? Page No: 23

CS606 JAVA PROGRAMMING LAB

no dude, shall v go muttukadu dis sunday? Client: okay nice, ll go dakshinachitra also wat do u say? okay no prob at al, den? Client: okay ll catch u later, okay bye Terminated... D:\java\java lab> Client Side: D:\java\java lab>javac UDPClient.java D:\java\java lab>java UDPClient Client is Running.... Type 'bye' to Quit hi deepu hw r u? Server: am dng gr8 argata, den wassup? nothing spl here, over thr? Server: no dude, shall v go muttukadu dis sunday? okay nice, ll go dakshinachitra also wat do u say? Server: okay no prob at al, den? okay ll catch u later, Server: okay bye bye Terminated... D:\java\java lab>

Page No: 24

CS606 JAVA PROGRAMMING LAB

Result: Thus the program for Transmission Control Protocol & User Datagram Protocol using Java is done & output is verified.

UDP AND TCP SOCKETS Review Questions: 1. What does a socket consists of ? The combination of an IP address and a port number is called a socket. 2. Differentiate TCP and UDP? TCP and UDP are both transport-level protocols. TCP is designed to provide reliable communication across a variety of reliable and unreliable networks and internets. UDP provides a connectionless service for application-level procedures. Thus, UDP is basically an unreliable service; delivery and duplicate protection are not guaranteed. 3. How do you make a connection to a URL?. URLConnection openConnection() Page No: 25

CS606 JAVA PROGRAMMING LAB

It returns a URLConnection object associated with the invoking URL object. It may throws an IOException. 3. Should I use ServerSocket or DatagramSocket in my applications? DatagramSocket allows a server to accept UDP packets, whereas ServerSocket allows an application to accept TCP connections. It depends on the protocol we're trying to implement. If we're creating a new protocol. DatagramSockets communciate using UDP packets. These pacur kets don't guarantee delivery - we'll need to handle missing packets in our client/server. ServerSockets communicate using TCP connections. TCP guarantees delivery, so all we need to do is have our applications read and write using a socket's InputStream and OutputStream. 5. How do I perform a hostname lookup for an IP address. InetAddress getAddress() Returns the destination InetAddress, typically used for sending. 7. True or False: Applet can connect via Sockets and can bind to a local port. True Applet can connect via sockets and can bind to a local port.

Ex. No. : 4 Date Aim Objective : 05-09-11

Title: Implement the Concept of Java Message Services

: To write a program for Java Messaging Services. : 1. To understand what is a Messaging System. 2. To demonstrate types of Messaging Services. 3. To create a connection to the messaging system provider. 4. To create sessions, for sending and receiving messages.

Pre lab

: Page No: 26

CS606 JAVA PROGRAMMING LAB

Syntax: A TextMessage wraps a simple String object. This is useful in situations where only strings are being passed. Creation of a TextMessage object is simple, as these two lines of code indicate: TextMessage message = session.createMessage(); message.setText("hello world"); An ObjectMessage, as its name implies, is a message wrapping a Java object. Any serializable Java object can be used as an ObjectMessage. This is how an Object message is created: ObjectMessage message = session.createObjectMessage(); message.setObject(myObject);

Problem Description: Java Messaging System is incorporate both SMTP (Simple Mail Transfer Protocol) and POP3 (Post Office Protocol Version 3). Here SMTP will be performed over here. SMTP gets the sender and receiver address then transfers the content given by sender to receiver.

Pseudo Code: Client Side: 1. Import network package.


2. Create a class and throws IOException in main function.

3. Initialize required variables. 4. Initialize Socket with the client port and initialize an object (s). 5. Using while loop do the protocol procedure. Page No: 27

CS606 JAVA PROGRAMMING LAB

Server Side: 1. Import network package.


2. Create a class and throws IOException in main function.

3. Initialize required variables. 4. Initialize DatagramSocket with the server port and initialize an object (serversocket). 5. Using while loop do the protocol procedure. .

Test Case: Sl # 1. 2. Test Case Code TC01 TC02 Test Case Description When some characters to be sent When some numbers to be sent Expected Result Sent without any loss Sent without any data loss Actual Result To be sent as it is. To be sent as it is. Pass / Fail Pass Pass

Coding: //SMTPClient. package SMTPcli; import java.io.*; import java.net.*; public class SMTPcli { public static void main(String arg[])throws IOException { Socket s=new Socket("localhost",8080); DataInputStream m=new DataInputStream(System.in); DataInputStream n=new DataInputStream(System.in); PrintStream p=new PrintStream(s.getOutputStream()); p.println("ready"); System.out.println("Enter from address:"); String str=m.readLine(); Page No: 28

CS606 JAVA PROGRAMMING LAB

p.println(str); System.out.println("Enter to address:"); String str1=n.readLine(); p.println(str1); System.out.println("Enter the message"); while(true) { String cmd=m.readLine(); p.println(cmd); if(cmd.equals("send")) { System.out.println("Client message has been sent"); break; } } } }

//SMTPServer package SMTPser; import java.io.*; import java.net.*; import java.util.*; public class SMTPser { public static void main(String arg[])throws IOException { ServerSocket ss=new ServerSocket(8080); Socket s=ss.accept(); ServerClient(s); } public static void ServerClient(Socket s)throws IOException { DataInputStream ds=null; Page No: 29

CS606 JAVA PROGRAMMING LAB

PrintStream ps=null; ds=new DataInputStream(s.getInputStream()); ps=new PrintStream(s.getOutputStream()); FileWriter f=new FileWriter("abcEmail.doc"); FileInputStream f1; String tel=ds.readLine(); if(tel.equals("ready")) { System.out.println("Ready signal received:ClIENT ACCEPTED"); System.out.println("From address"); String from=ds.readLine(); System.out.println(from); f.write("FROM"+from+"\n"); System.out.println("To address"); String to=ds.readLine(); System.out.println(to); f.write("TO:"+to+"\n"); System.out.println("Client Msg"); f.write("message"); while(true) { String cmd=ds.readLine(); if(cmd.equals("send")) { cmd="SERVER message received"; System.out.println(cmd); break; } f.write("\n"); System.out.println(cmd); f.write(cmd+"\n"); } f.close(); } } }

Page No: 30

CS606 JAVA PROGRAMMING LAB

Page No: 31

CS606 JAVA PROGRAMMING LAB

Output:

Result: Thus the program for Java Messaging System (SMTP) is done & output is verified. Page No: 32

CS606 JAVA PROGRAMMING LAB

JAVA MESSAGE SERVICES Review Questions: 1. What is JMS? Java Messaging System is used mail services through SMTP and POP3. 2. Differentiate Byte Message and Stream Message. A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system. All streams behave in the same manner, even if the actual physical devices to which they are linked differ. Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data. 3. Can you remember the three components of a message? Sender, Intermediate Buffer & Receiver. 4. Does Tomcat support JMS (Java Messaging Service)? Yes, its support for Messaging System. 5. True or False: JMS can support e-mail operations. True, it handles such a protocol to function messaging system.

Page No: 33

CS606 JAVA PROGRAMMING LAB

Ex. No. : 5 Date Aim Objective : 26-09-11

Title: Create a Simple Application using Swing.

: To write a program for swing using java. : 1. To understand the concept of Swing in Java. 2. To know about Java Foundation Classes. 3. To comprehend the Swing Class Hierarchy. 4. To demonstrate the different Swing components.

Pre lab : Swing labels are instances of the JLabel class which extends JComponent: It can display text and/or an icon. Syntax: Some of the Swing label constructors are mentioned below: JLabel(Icon i) JLabel(String s) JLabel(String s, Icon I, int align). Here, s and i are the text and icon used for the label. The align argument is either LEFT, RIGHT, CENTER, LEADING, or TRAILING. Listeners register and un-register for these events via the methods shown here: void addActionListener(ActionListener al) void removeActionListener(ActionListener al) Here, al is the action listener.

Problem Description: Page No: 34

CS606 JAVA PROGRAMMING LAB

Swing is implementing for Look & Feel interface, basically java will not give such an impact on user interface level. Hence Swing is introducing for such sort of problem. javax.swing.* is an advance enhanced for Look & Feel point of view.

Pseudo Code:

1. Import the javax.swing package. 2. Create a Button and provide the URL for the image to be display. 3. Create an Exit Button and if its clicks then window will be close.
4. Using actionperfomed method to get the action.

4a. if user clicks the Button then it could display image on the give space.

Test Case:

Sl No 1. 2.

Test Case Code TCO1 TC02

Test Case Description If Click Here to be Click If Clicks Exit Button

Expected Result Displayed Image Close the window

Actual Result Image Displayed Window Closed

Pass / Fail Pass Pass

Coding: package image; Page No: 35

CS606 JAVA PROGRAMMING LAB

import java.awt.Color; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; public class image implements ActionListener { public JLabel l1=new JLabel("SWING CONCEPT"); public JButton b1=new JButton("Click Here"); ImageIcon someIcon = new ImageIcon("D:/fagneesh.jpg"); public JButton b2= new JButton(); public JButton EXIT=new JButton("EXIT"); public JFrame f1; public Container c; image() { f1=new JFrame("SWING"); c=f1.getContentPane(); c.setLayout(null); f1.setSize(500, 500); f1.show(); l1.setBounds(200,35,100,50); b1.setBounds(200,85,100,50); b2.setBounds(200,185,200,140); EXIT.setBounds(210,385,80,50); l1.setForeground(Color.BLUE); b1.setForeground(Color.MAGENTA); c.add(l1); c.add(b1); c.add(b2); c.add(EXIT); b1.addActionListener(this); b2.addActionListener(this); EXIT.addActionListener(this); } public void actionPerformed(ActionEvent e) Page No: 36

CS606 JAVA PROGRAMMING LAB

{ if(e.getSource()==b1) { b2.setIcon(someIcon); f1.setTitle("CRESCENT"); } if (e.getSource()== EXIT) { System.exit(0); } } public static void main(String args[]) { new image(); } }

Output:

Page No: 37

CS606 JAVA PROGRAMMING LAB

Result: Thus the program for Swing using java is done & output is verified.

SWING Review Questions: 1. What is a swing? Page No: 38

CS606 JAVA PROGRAMMING LAB

Swing is a set of classes that provides more powerful and flexible components than are possible with the AWT.

2. Name a few Container classes. Applet provides all necessary support for applet execution. Applet extends a AWT class Panel, in turn Panel extends Container which extends Component. The Container class is a subclass of Component. The Panel class is a concrete class of container. 4. Can you run Swing under a browser? No, its only for application purpose. 5. Differentiate a Window and a Frame. The Window class creates a top- level window. A top-level window is not contained within any other object; it sits directly on the desktop. Frame encapsulates what is commonly thought of as a window. It is a subclass of Window. If you create a Frame object from within an applet, it will contain a warning message, such as Java Applet Window. 6. What is the difference between Swing and AWT components? Swing is a set of classes that provides more powerful and flexible components than are possible with the AWT. AWT is a base of swing.

Ex. No. : 6 Date :

Title: Remote Method Invocation

Page No: 39

CS606 JAVA PROGRAMMING LAB

Aim Objective

: To write a program for Remote Method Invocation. : 1. To understand the concept of Remote Method Invocation (RMI) in Java. 2. To know how to build distributed applications. 3. To comprehend RMI way of communication between client and server. 4. To locate remote objects.

Pre lab : To know about serialization in java. All remote interfaces must extend the Remote interface, which is part of java.rmi. Syntax: All remote methods can throw a Remote Exception Import java.rmi.*; Public interface AddServerIntf extends Remote { Double add(double d1, double d2) throws RemoteException; }

Problem Description: Remote method invocation allows applications to call object methods located remotely, sharing resources and processing load across systems. Unlike other systems for remote execution which require that only simple data types or defined structures be passed to and from methods, RMI allows any Java object type to be used - even if the client or server has never encountered it Page No: 40

CS606 JAVA PROGRAMMING LAB

before. RMI allows both client and server to dynamically load new object types as required. In this article, you'll learn more about RMI.

Pseudo Code: 1. Create a Client program which request to their interface. 2. Create a Server program which implements the request from interface. 3. Stub interface (used by the client so that it knows what functions it can access on the server side) 4. Skeleton interface (used by the server as the interface to the stub on the client side) 5. The information flows as follows: the client talks to the stub, the stub talks to the skeleton and the skeleton talks to the server. Test Case: Sl No 1. 2. Test Case Code TC01 TC02 Test Case Description If the registry is properly registered. If the stub is not created Expected Result Connection Established Throws an Exception in Client side. Throws an Exception in Server side. Actual Result Connection Established Throws an Exception in Client side. Throws an Exception in server side. Pass / Fail Pass Pass

3.

TC03

If the skeleton is not created

Pass

Coding: //ReceiveMessageInterface.java import java.rmi.*; public interface ReceiveMessageInterface extends Remote { void receiveMessage(String x) throws RemoteException; } Page No: 41

CS606 JAVA PROGRAMMING LAB

//RmiServer.java import java.rmi.*; import java.rmi.registry.*; import java.rmi.server.*; import java.net.*; public class RmiServer extends java.rmi.server.UnicastRemoteObject implements ReceiveMessageInterface { int thisPort; String thisAddress; Registry registry; public void receiveMessage(String x) throws RemoteException { System.out.println(x); } public RmiServer() throws RemoteException { try { thisAddress= (InetAddress.getLocalHost()).toString(); } catch(Exception e) { throw new RemoteException("can't get inet address."); } thisPort=3232; System.out.println("this address="+thisAddress+",port="+thisPort); try { registry = LocateRegistry.createRegistry( thisPort ); registry.rebind("rmiServer", this); } catch(RemoteException e) { throw e; } } static public void main(String args[]) Page No: 42

CS606 JAVA PROGRAMMING LAB

{ try { RmiServer s=new RmiServer(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } //RmiClient.java import java.rmi.*; import java.rmi.registry.*; import java.net.*; public class RmiClient { static public void main(String args[]) { ReceiveMessageInterface rmiServer; Registry registry; String serverAddress=args[0]; String serverPort=args[1]; String text=args[2]; System.out.println("sending "+text+" to "+serverAddress+":"+serverPort); try { registry=LocateRegistry.getRegistry(serverAddress,(new Integer(serverPort)).intValue()); rmiServer=(ReceiveMessageInterface)(registry.lookup("rmiServer")); rmiServer.receiveMessage(text); } catch(RemoteException e) { e.printStackTrace(); } catch(NotBoundException e) Page No: 43

CS606 JAVA PROGRAMMING LAB

{ e.printStackTrace(); } } }

Output: Server side: C:\Program Files\Java\jdk1.6.0_23\bin>javac RmiServer.java C:\Program Files\Java\jdk1.6.0_23\bin>rmic RmiServer C:\Program Files\Java\jdk1.6.0_23\bin>java RmiServer this address=admin/192.168.1.2,port=3232 crescent Page No: 44

CS606 JAVA PROGRAMMING LAB

Client side C:\Program Files\Java\jdk1.6.0_23\bin>javac RmiClient.java C:\Program Files\Java\jdk1.6.0_23\bin>java RmiClient 192.168.1.2 3232 crescent sending crescent to 192.168.1.2:3232

Result: Thus the program Remote Method Invocation (RMI) using java is done and output is verified.

REMOTE METHOD INVOCATION Review Questions:


1. What is the functionality UnicastRemoteObject?

UnicastRemoteObject which provides functionality that is needed to make objects available from remote machine. 2. Does RMI require use of an HTTP server? No, it allows a java object that executes on one machine to invoke a method of a java object that executes on other machine. 2. How will you create Client Program? Page No: 45

CS606 JAVA PROGRAMMING LAB

Stub interface (used by the client so that it knows what functions it can access on the server side)

Ex. No. : 7 Date Aim Objective : 15-10-11

Title: JavaScript

: To write a program for JavaScript using HTML. : 1. To understand the concept JavaScript. 2. To know the different data types, variables, and operators. 3. To comprehend how to interact with the users. 4. To work with forms and objects. Page No: 46

CS606 JAVA PROGRAMMING LAB

Prelab: Simple recursive function example: function factorial(n) { if (n == 0) { return 1; } return n * factorial(n - 1); }

Problem Description: Script will trigger a small set of segment/function as to give an effective operation along with the web application. Here scripting will use for validating the field and ease to avoid some sort of redundancy & to sustain the consistency level.

Pseudo Code: 1. Create a main page for authentication. 2. Get the username and password & validate using javascript. 3. If given data is correct and continue with the test else say Login Failed 4. In test module, using radio button get the answer for the given question. Page No: 47

CS606 JAVA PROGRAMMING LAB 5. And Compute at last for the set questions and print the total score using javascript.

Test Case:

Sl No 1. 2

Test Case Code TC01 TC02

Test Case Description On Authentication if given input is proper.

Expected Result It transfers to Test Page

Actual Result Displayed a Test Page Login Failed, Message will be Displayed Total Score is displayed

Pass / Fail Pass Pass

On Authentication if given input It gives error is not proper. message Total Score based scripting routine. Gives a Total Score

TC03

Pass

Coding: //login.htm <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>LOGIN</title> </head> <body> <HR> <p align="center"> <font color="#0000FF" size="6"> AUTHENTICATION ENTRY </font> </p> <hr> <form> Page No: 48

CS606 JAVA PROGRAMMING LAB

<center> <p align="center"> CRESCENT ID &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="t1" id="name"> <br><br> CRESCENT PWD &nbsp;&nbsp;&nbsp; <input type="password" name="t2" id="pass"> <br><br> </p> <p align="center"> <input type="button" value="login" onclick="login();"> </p> </center> </form> </body> <script type="text/javascript"> function login() { x=document.getElementById("name"); y=document.getElementById("pass"); if(x.value=="a" && y.value=="a") { window.open("test.html"); window.close("login.html"); } else if(x.value==" " && y.value==" ") { alert("enter your name and password "); } else alert("incorrect entrty"); } </script> </html> Page No: 49

CS606 JAVA PROGRAMMING LAB

// test.htm <html> <title> Aptitude test </title> <body bgcolor="green"> <hr> <p align="center"> <font color="#0000FF" size="6">Test Session</font> </p> <hr> <form> <center> <input type="radio" name="radio1" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="button" value="GO" onclick="go();"> </center> </form> </body> <script type="text/javascript"> function go() { if(document.getElementById("radio1").checked==true) { window.open("english.html"); } if(document.getElementById("radio2").checked==true) { window.open("maths.html"); } } </script> </html> Page No: 50 id="radio1"> English Section

<input type="radio" name="radio1" id="radio2"> Mathematics Section <br><br>

CS606 JAVA PROGRAMMING LAB

//English.htm <html> <title> English Cognitive Section </title> <body bgcolor="tan"> <p align="center"> <font color="#0000FF" size="6"> English Section <font> </p> <form> <br> &nbsp;&nbsp;&nbsp;&nbsp; 1. Nonversation? &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="radio" name="radio10" id="radio1"> Meaningful Conversation &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="radio" name="radio10" id="radio2"> Meaningless Conversation <br><br><br> &nbsp;&nbsp;&nbsp;&nbsp; 2. Reprimand? &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="radio" name="radio11" id="radio3"> Express Strong Disapproval &nbsp;&nbsp; <input type="radio" name="radio11" id="radio4"> Express Strong Approval <br><br> <center> <input type="button" value="SUBMIT" name="b1" onclick="validate();"> </center> </form> </body> <script type="text/javascript"> function validate() { var a=0; if(document.getElementById("radio2").checked==true) a=a+1; if(document.getElementById("radio3").checked==true) a=a+1; total=a; prec=total*100/2; if(a==1) alert("yor score : 1 out of 2"); Page No: 51

CS606 JAVA PROGRAMMING LAB

else if(a==2) alert("yor score 2 out of 2"); else if(a==0) alert("yor score 0 out of 2"); } </script> </html> //maths.htm <html> <title> Maths Section </title> <body bgcolor="tan"> <p align="center"> <font color="#0000FF" size="6"> Mathematics Section </font></p> <form> <br><br> &nbsp;&nbsp;&nbsp;&nbsp; id="radio1"> id="radio2"> 0.01744 0.17449 1. sin(cos(tan(45))) in degree mode? &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="radio" name="radio10" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="radio" name="radio10" <br><br>&nbsp;&nbsp;&nbsp;&nbsp;

2. ln(log(45)) ? &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n bsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="radio" name="radio11" id="radio3"> 0.7098 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="radio" name="radio11" id="radio4"> 0.5027 <br><br> <center> <input type="button" value="SUBMIT" name="b1" onclick="validate();"></center> </form> </body> <script type="text/javascript"> function validate() Page No: 52

CS606 JAVA PROGRAMMING LAB

{ var a=0; if(document.getElementById("radio2").checked==true) a=a+1; if(document.getElementById("radio4").checked==true) a=a+1; if(a==1) alert("yor score : 1 out of 2"); else if(a==2) alert("yor score 2 out of 2"); else if(a==0) alert("yor score 0 out of 2"); } </script> </html>

Output:

Page No: 53

CS606 JAVA PROGRAMMING LAB

Page No: 54

CS606 JAVA PROGRAMMING LAB

Page No: 55

CS606 JAVA PROGRAMMING LAB

Result: Thus the program for javascript is done & output is verified.

JAVASCRIPT Review Questions: 1. What is the general structure of an HTML document? <html> <body> statement to be execute </body> </html> 2. Is it possible to incorporate a JavaScript in an XML document? Yes, its a possible to incorporate a JavaScript in an XML Document. 3. How about 2+5+"8"? 2+5+8 = 78 4. What are objects in JavaScript? JavaScript objects store their properties in an internal table that can access in two ways. Page No: 56

CS606 JAVA PROGRAMMING LAB

1st way

- using object name property name.

2nd way- using array which enables to access all an objects properties in sequence. Another way - Associative Array associative a left and a right side element, value of right side can be used by specifying the value of left side as index. Eg: document[Href] - > this is used to access the href property of document object. 5. Give the difference between Java and JavaScript. Java is an application language, which as its own independent code. JavaScript enables to embed commands in a HTML tags. JavaScript enables web authors to write small scripts that executes on the users browsers rather on the server.

Ex. No. : 8 Date Aim Objective : 31-10-11

Title: Application Program Using JDBC

: To write a program for Java Database Connectivity. : 1. To know the concept the JDBC 2. To understand the components of JDBC. 3. To demonstrate a JDBC connection. 4. To comprehend JDBC drivers..

Pre lab

For Setting a Driver: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Page No: 57

CS606 JAVA PROGRAMMING LAB

For Connection Establishment: Connection con=DriverManager.getConnection("jdbc:odbc:test"); For Statement Exection: Statement s=con.createStatement(); For initializing a result set: ResultSet rset=s.getResultSet();

Problem Description: The Java Database Connectivity will place a role to get a value in run time and store in database. Here we get a set of data to be stored in MS-Access. Connectivity ensures the stability through Open Database Connectivity with Driver Manager.

Pseudo Code:
1. Import sql packages into the program. 2. Create a class and execute a statement through try catch statement.

3. Using try get the Driver Name. 4. Create an object for Connection class and provided give the database name. 5. Create an object for Statement class and create a statement through connection. 6. Execute a Query. 7. Create an object for result set, through the statement object; initialize the result set. 8. Using while get the sequence of result. 9. If any exception gives through catch statement. 10. Finally print execution completed!

Page No: 58

CS606 JAVA PROGRAMMING LAB

Test Case: Sl No. 1. Test Case Code TC01 Test Case Description` If the fields items are properly given If the Driver Manger could not properly links Expected Result Properly Stored Actual Result Stored in corresponding fields Throws an Exception Pass / Fail Pass

2.

TC02

Display an error message

Pass

Coding: package javap; import java.sql.*; public class javap { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:test"); Statement s=con.createStatement(); s.executeQuery("SELECT *FROM products"); ResultSet rset=s.getResultSet(); while(rset.next()) { System.out.println(rset.getString("ProductName")); System.out.println(rset.getString("ProductPrice")); } } catch(Exception e) Page No: 59

CS606 JAVA PROGRAMMING LAB

{ System.out.println(); } finally { System.out.println("*** CHOCLATE STORE ***"); } } }

Database:

Output:

Page No: 60

CS606 JAVA PROGRAMMING LAB

Result: Thus the program for JDBC using java & MS-Access is done & output is verified. JDBC Java Database Connectivity Review Questions: 1. What are the steps involved in establishing a JDBC connection? a. Open or establish a connection to the database b. Execute a SQL statement. c. Process the result. d. Close the connection to the database. 2. How can you load the drivers? Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); DriverManager.getConnection("jdbc:odbc:test"); 3. What will Class.forName do while loading drivers? Loading the JDBC driver is very simple using a static method called forName which belongs to the class Class. This method creates an instance of the driver and registers it with the DriverManager.

Page No: 61

CS606 JAVA PROGRAMMING LAB

4.

How can you make the connection? Connection con = DriverManager.getConnection("jdbc:odbc:test");

5.

What does setAutoCommit do? If all transaction would have finished successfully, this command will execute.

6. What are callable statements? If some of the query to be executed then callable statement will provide such a environment.

Page No: 62

Vous aimerez peut-être aussi