You are on page 1of 33

MC1757

MIDDLEWARE LAB

0 0

100

1. Create a distributed application to download various files from various servers using RMI 2. Create a Java Bean to draw various graphical shapes and display it using or without using BDK 3. Develop an Enterprise Java Bean for Banking operations 4. Develop an Enterprise Java Bean for Library operations 5. Create an Active-X control for File operations 6. Develop a component for converting the currency values using COM / .NET 7. Develop a component for encryption and decryption using COM / .NET 8. Develop a component for retrieving information from message box using DCOM / .NET 9. Develop a middleware component for retrieving Stock Market Exchange information using CORBA 10. Develop a middleware component for retrieving Weather Forecast information using CORBA

Lab Exercises: EX.NO Cycle 1 1 2 3 4 5 6 7 8 9 10 Download files using RMI Java Bean for drawing shapes EJB for Banking Operations EJB for Library Operations Active-X control for file operations Cycle 2 Component for Currency conversion using COM Component for Encryption/Decryption using COM Component for retrieving information using DCOM Component for Stock Market information using CORBA Component for Weather Forecast information using CORBA NAME

EX NO:!

DOWNLOADING FILES USING RMI

Program Description To write a Java RMI program to download a file from one machine to another.

Method: 1. Create a folder called RMIFILE and within that create 4 programs with the following java code FileInterface.java import java.rmi.Remote; import java.rmi.RemoteException; public interface FileInterface extends Remote { public byte[] downloadFile(String fileName) throws RemoteException; } FileImpl.java import java.io.*; import java.rmi.*; import java.rmi.server.UnicastRemoteObject; public class FileImpl extends UnicastRemoteObject implements FileInterface { private String name; public FileImpl(String s) throws RemoteException{ super(); name = s; } public byte[] downloadFile(String fileName){ try { File file = new File(fileName); byte buffer[] = new byte[(int)file.length()]; BufferedInputStream input = new BufferedInputStream(new FileInputStream(fileName)); input.read(buffer,0,buffer.length); input.close(); return(buffer); } catch(Exception e){ System.out.println("FileImpl: "+e.getMessage()); e.printStackTrace();

return(null); } } } FileServer.java import java.io.*; import java.rmi.*; public class FileServer { public static void main(String argv[]) { if(System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } try { FileInterface fi = new FileImpl("FileServer"); Naming.rebind("FileServer", fi); } catch(Exception e) { System.out.println("FileServer: "+e.getMessage()); e.printStackTrace(); } } } FileClient.java import java.io.*; import java.rmi.*; public class FileClient{ public static void main(String argv[]) { if(argv.length != 2) { System.out.println("Usage: java FileClient fileName machineName"); System.exit(0); } try { String name = "//" + argv[1] + "/FileServer"; FileInterface fi = (FileInterface) Naming.lookup(name); byte[] filedata = fi.downloadFile(argv[0]); File file = new File("sh1.txt"); BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file.getName())); output.write(filedata,0,filedata.length); output.flush(); output.close();

} catch(Exception e) { System.err.println("FileServer exception: "+ e.getMessage()); e.printStackTrace(); } } } 2. Create a file called policy.txt in the same folder with the following contents. grant { permission java.security.AllPermission "", ""; }; 3. Create a text file called abc.txt with any text content. Eg: Hello World. 4. Compile all 4 java programs. 5. Use the command rmic FileImpl to generate stub and skeleton. 6. start the rmiregistry. 7. Start the server with the following command > java Djava.security.policy=policy.txt FileServer 8. Start the client with the following command java FileClient abc.txt 127.0.0.1

EX NO:2

JAVA BEAN FOR DRAWING SHAPES

Program Description To write a Java Bean program to draw various shapes and to test it using BDK.

Method: 1. Create a bean to display various shapes. 2. Create a manifest file. 3. Create a jar file . 4. Copy the jar file in the jars folder. 5. Move to beanbox directory and type run. 6. Open the beanbox and select the bean to view the shapes.

EX NO:3

EJB APPLICATION FOR BANKING OPERATION

Program Description To write a EJB Application to perform Banking operations.

Method: 1. Set the path to point to the bin directory (Eg:c:\sun\appserver\bin) and the classpath to point to j2ee.jar. 2. Create the remote interface for the bean as Bank.java. Program Bank.java import javax.ejb.EJBObject; import java.rmi.RemoteException; import java.math.*; public interface Bank extends EJBObject { public BigDecimal deposit(BigDecimal amt,BigDecimal balance) throws RemoteException; public BigDecimal withdraw(BigDecimal amt,BigDecimal balance) throws RemoteException; } 3. Create the Beans home interface BankHome.java which defines two methods deposit and withdrawal. Program BankHome.java import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EJBHome; public interface BankHome extends EJBHome { Bank create() throws RemoteException, CreateException; } 4. Implement the Beans methods in BankBean.java

Program BankBean.java import java.rmi.RemoteException; import javax.ejb.SessionBean; import javax.ejb.SessionContext; import java.math.*; public class BankBean implements SessionBean { BigDecimal yenRate = new BigDecimal("121.6000"); BigDecimal euroRate = new BigDecimal("0.0077"); public BigDecimal deposit(BigDecimal amt,BigDecimal balance) { BigDecimal result = balance.add(amt); return result.setScale(2,BigDecimal.ROUND_UP); } public BigDecimal withdraw(BigDecimal amt,BigDecimal balance) { BigDecimal result = balance.subtract(amt); return result.setScale(2,BigDecimal.ROUND_UP); } public BankBean() {} public void ejbCreate() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {} } 5. Implement the Beans client in BankClient.java.

Program BankClient.java import javax.naming.Context; import javax.naming.InitialContext; import javax.rmi.PortableRemoteObject; import java.math.BigDecimal; public class BankClient { public static void main(String[] args) { try { Context initial = new InitialContext(); Context myEnv = (Context)initial.lookup("java:comp/env"); Object objref = myEnv.lookup("ejb/BankOperations"); BankHome home = (BankHome)PortableRemoteObject.narrow(objref, BankHome.class); Bank newBank = home.create(); BigDecimal dep_amt = new BigDecimal ("100.00"); BigDecimal with_amt = new BigDecimal ("100.00"); BigDecimal bal = new BigDecimal ("5000.00"); System.out.println("Available Balance = RS."+bal); BigDecimal new_bal = newBank.deposit(dep_amt,bal); System.out.println("After deposit(Rs.100): Rs."+new_bal);

new_bal = newBank.withdraw(with_amt,bal); System.out.println("After Withdrawal(Rs.100):Rs."+new_bal); System.exit(0); } catch (Exception ex) { System.err.println("Caught an unexpected exception!"); ex.printStackTrace(); } } } 6. Compile the remote interface, home interface and implementation class.

EX NO:4

EJB FOR LIBRARY OPERATIONS

Program Description To write a EJB Application to perform issue and withdraw operations in a library..

Method: 1. Set the path to point to the bin directory (Eg:c:\sun\appserver\bin) and the classpath to point to j2ee.jar. 2. Create the remote interface for the bean as Library.java. Program Library.java import javax.ejb.EJBObject; import java.rmi.RemoteException; public interface Library extends EJBObject { public String issueBook(String ib) throws RemoteException; public String returnBook(String rb) throws RemoteException; }

3. Create the Beans home interface LibraryHome.java which defines two methods deposit and withdrawal. Program LibraryHome.java import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EJBHome; public interface LibraryHome extends EJBHome { Library create() throws RemoteException, CreateException; }

4. Implement the Beans methods in LibraryBean.java Program LibraryBean.java import java.rmi.RemoteException; import javax.ejb.SessionBean; import javax.ejb.SessionContext; public class LibraryBean implements SessionBean { String book[] = { "C++ The Complete Reference", "Computer Networks", "XML and Web Services", "Programming in Java"}; int x,i,j; public String issueBook(String ib) { for(i=0;i<book.length;i++) { if (book[i].equals(ib)) { break; } } x=i; for(j=x;j<book.length;j++) { book[j]=book[j+1]; } return ib; }

public String returnBook(String rb) { book[book.length+1]=rb; return rb; } public LibraryBean() {} public void ejbCreate() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {} } 5. Implement the Beans client in LibraryClient.java. Program LibraryClient.java import javax.naming.Context; import javax.naming.InitialContext; import javax.rmi.PortableRemoteObject;

public class LibraryClient { public static void main(String[] args) { try { Context initial = new InitialContext(); Context myEnv = (Context)initial.lookup("java:comp/env");

Object objref = myEnv.lookup("ejb/LibraryOperations"); LibraryHome home = (LibraryHome)PortableRemoteObject.narrow(objref, LibraryHome.class); Library lib = home.create(); String retbook= new String("Java 2 The Complete Reference"); String getbook = new String("XML and Web Services"); String newbook = new String(); String newbook1 = new String(); newbook=lib.issueBook(getbook); System.out.println(newbook); newbook=lib.returnBook(retbook); System.out.println(newbook); System.exit(0); } catch (Exception ex) { System.err.println("Caught an unexpected exception!"); ex.printStackTrace(); } } }

6. Compile the remote interface, home interface and implementation class.

EX NO:6

COMPONENT FOR CURRENCY CONVERSION USING COM

Program Description

To write a component-based program for currency conversion using COM. Method: 1. Create a component in VB.Net for currency conversion. Program: ConvertComponent Option Explicit On Public Class Currency Public Function dollartorupee(ByVal Num1 As Double) As Double dollartorupee = Num1 * 45 End Function Public Function rupeetodollar(ByVal Num1 As Double) As Double rupeetodollar = Num1 / 45 End Function End Class Program ConvertClient using System; namespace ConvertClient { class Program { static void Main(string[] args) { double rupee = 0; double dollar = 0; ConvertComponent.Currency myCur = new ConvertComponent.Currency(); rupee = myCur.dollartorupee(100); dollar = myCur.rupeetodollar(100); Console.Write("100 Dollars = {0} Rupees\n ", rupee.ToString()); Console.Write("100 Rupees = {0} Dollars", dollar.ToString()); Console.ReadLine();

} } }

EX NO:7

COMPONENT FOR EXCRYPTION/DECRYPTION USING COM

Program Description

To write a component-based program using COM and .Net for encryption/decryption. Method: 1. Create a new Class library Program: - EncryptComponent Option Explicit On Public Class Convert Public Function EncryptText(ByVal strText As String, ByVal strPwd As String) Dim i As Integer, c As Integer Dim strBuff As String #If Not CASE_SENSITIVE_PASSWORD Then strPwd = UCase$(strPwd) #End If If Len(strPwd) Then For i = 1 To Len(strText) c = Asc(Mid$(strText, i, 1)) c = c + Asc(Mid$(strPwd, (i Mod Len(strPwd)) + 1, 1)) strBuff = strBuff & Chr(c And &HFF) Next i Else strBuff = strText End If EncryptText = strBuff End Function Public Function DecryptText(ByVal strText As String, ByVal strPwd As String) Dim i As Integer, c As Integer Dim strBuff As String #If Not CASE_SENSITIVE_PASSWORD Then strPwd = UCase$(strPwd) #End If If Len(strPwd) Then For i = 1 To Len(strText) c = Asc(Mid$(strText, i, 1)) c = c - Asc(Mid$(strPwd, (i Mod Len(strPwd)) + 1, 1)) strBuff = strBuff & Chr(c And &HFF)

Next i Else strBuff = strText End If DecryptText = strBuff End Function End Class Program EncryptClient using System; namespace EncryptClient { class Program { static void Main(string[] args) { String data = "Happiness is a state of mind"; String pwd = "abc"; String encdata, decdata; EncryptComponent1.Convert Enc = new EncryptComponent1.Convert(); encdata = Enc.EncryptText(data,pwd).ToString() ; decdata = Enc.DecryptText(encdata,pwd).ToString() ; Console.Write("Text to be Encrypted: {0}\n",data.ToString() ); Console.Write("After Encryption : {0}\n", encdata.ToString() ); Console.Write("After Decryption : {0}\n", decdata.ToString() ); Console.ReadLine(); } } }

EX NO:8

COMPONENT FOR RETRIEVING INFORMATION USING DCOM

Program Description

To write a component-based program using DCOM for retrieving information. Method: Program MsgComponent Option Explicit On Public Class MsgComp Public Function retrieve(ByVal msg As String) As String retrieve = "Hello " + msg + "!" End Function End Class Program MsgClient using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace MsgClient { public class Form1 : System.Windows.Forms.Form { public System.Windows.Forms.TextBox textBox1; public System.Windows.Forms.Button button1; public System.Windows.Forms.Label label1; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent();

// // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.textBox1 = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(328, 96); this.textBox1.Name = "textBox1"; this.textBox1.TabIndex = 0; this.textBox1.Text = ""; // // button1 // this.button1.Location = new System.Drawing.Point(240, 160); this.button1.Name = "button1";

this.button1.TabIndex = 1; this.button1.Text = "PRESS"; this.button1.Click += new System.EventHandler(this.button1_Click); // // label1 // this.label1.Location = new System.Drawing.Point(184, 104); this.label1.Name = "label1"; this.label1.TabIndex = 2; this.label1.Text = "Enter Name"; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(664, 301); this.Controls.Add(this.label1); this.Controls.Add(this.button1); this.Controls.Add(this.textBox1); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { //string disp; //MsgComponent.MsgComp ms =new MsgComponent.MsgComp(); //TextBox tb = new TextBox(); //Button b=new Button(); Application.Run(new Form1()); } public void Form1_Load(object sender, System.EventArgs e) {

} private void textBox1_TextChanged(object sender, System.EventArgs e) { } public void button1_Click(object sender, System.EventArgs e) { string disp,d; MsgComponent.MsgComp ms =new MsgComponent.MsgComp(); Form1 f=new Form1(); d=textBox1.Text.ToString() ; disp = ms.retrieve(d); MessageBox.Show(f,disp); } } }

EX NO:9

STOCK MARKET INFORMATION USING CORBA

Program Description

To write a CORBA program to retrieve stock market information. Method: 1. Define the interface Stock.idl to define the objects and methods. Program: module StockObjects { struct Quote { string symbol; long long at_time; double price; long volume; }; exception Unknown{}; interface Stock { Quote get_quote() raises(Unknown); void set_quote(in Quote stock_quote); readonly attribute string description; }; }; 2. Implement the server StockServer.java. Program: import java.io.*; import StockObjects.*; public class StockServer { public static void main(String[] args) { if (args.length!=1) { System.err.println("Required argument: stock ior file"); return; } try { org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args,null);

StockImpl theStock = new StockImpl("GII","Global Industries Incorporated"); orb.connect(theStock); Quote quote = new Quote(); quote.price=28.0; quote.symbol="GII"; quote.volume=0; quote.at_time=System.currentTimeMillis(); theStock.set_quote(quote); System.out.println( "Created GII:\n" + orb.object_to_string(theStock) ); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(args[0]))); out.println( orb.object_to_string(theStock) ); out.close(); java.lang.Object sync = new java.lang.Object(); synchronized (sync) { sync.wait(); } } catch (Exception e) { System.err.println("Stock server error: " + e); e.printStackTrace(System.out); } } } 3. Implement the client application StockClient.java with operations suitable for stock operations. Program: import java.io.*; import org.omg.CORBA.*; import StockObjects.*; public class StockClient { public static void main(String args[]) { if (args.length!=1) {

System.err.println("Required argument: stock ior file"); return; } try { ORB orb = ORB.init(args, null); BufferedReader in = new BufferedReader(new FileReader(args[0])); String ior = in.readLine(); in.close(); org.omg.CORBA.Object obj = orb.string_to_object(ior); Stock theStock = StockHelper.narrow(obj); Quote currentQuote = theStock.get_quote(); System.out.print(theStock.description()); System.out.println(" is currently selling at "+currentQuote.price); System.out.println("Volume is "+currentQuote.volume); } catch (Exception e) { e.printStackTrace(System.out); } } } Program: import StockObjects.*; public class StockImpl extends StockObjects._StockImplBase { private Quote _quote=null; private String _description=null; public StockImpl(String name,String description) { super(); _description = description; } public Quote get_quote() throws Unknown { if (_quote==null) throw new Unknown(); return _quote; } public void set_quote(Quote quote) {

_quote = quote; } public String description() { return _description; } } 4. To run this client-server application on your development machine: a) Change to the directory that contains the file Stock.idl. b) Run the IDL-to-Java compiler, idlj, on the IDL file to create stubs and skeletons. This step assumes that you have included the path to the java/bin directory in your path. c) idlj -fall Stock.idl You must use the -fall option with the idlj compiler to generate both client and server-side bindings. The idlj compiler generates a number of files. 5. Compile the .java files, including the stubs and skeletons (which are in the directory StockApp). This step assumes the java/bin directory is included in your path. javac *.java StockApp/*.java 6. Start orbd. From an MS-DOS system prompt (Windows), enter: start orbd -ORBInitialPort 1050 Note that 1050 is the port on which you want the name server to run. The -ORBInitialPort argument is a required command-line argument. 7. Start the Hello server: From an MS-DOS system prompt (Windows), enter: start java StockServer -ORBInitialPort 1050 -ORBInitialHost localhost You will see StockServer ready and waiting... when the server is started.

8. Run the client application: java StockClient -ORBInitialPort 1050 -ORBInitialHost localhost

EX NO:!0

WEATHER FORECAST USING CORBA

Program Description To write a CORBA program to perform weather forecasting . Method: 1. Define the interface Weather.idl to define the objects and methods. Program: module WeatherDetails { struct Daily { string country; string at_time; double pressure; long temperature; long windspeed; }; exception Unknown{}; interface Weather { Daily get_daily() raises(Unknown); void set_daily(in Daily weather_daily); readonly attribute string description; }; }; 2. Implement the server WeatherServer.java. Program: import java.io.*; import WeatherDetails.*; import java.util.*; import java.text.SimpleDateFormat; public class WeatherServer { public static void main(String[] args) { if (args.length!=1) { System.err.println("Required argument: weather ior file");

return; } try { org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args,null); WeatherImpl theWeather = new WeatherImpl("INDIA","Chennai"); orb.connect(theWeather); Daily daily = new Daily(); daily.pressure=28.0; daily.country="INDIA"; daily.temperature=38; daily.windspeed= 6; Date now = new Date(System.currentTimeMillis()); SimpleDateFormat sdfEx3 = new SimpleDateFormat("MMMM d, yyyy"); String ex3 = sdfEx3.format(now);

daily.at_time=ex3; theWeather.set_daily(daily); System.out.println( "Created INDIA:\n" + orb.object_to_string(theWeather) ); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(args[0]))); out.println( orb.object_to_string(theWeather) ); out.close(); java.lang.Object sync = new java.lang.Object(); synchronized (sync) { sync.wait(); } } catch (Exception e) { System.err.println("Weather server error: " + e); e.printStackTrace(System.out); } } }

3.Implement the client application WeatherClient.java with operations suitable for weather forecasting. Program: import java.io.*; import org.omg.CORBA.*; import WeatherDetails.*; public class WeatherClient { public static void main(String args[]) { if (args.length!=1) { System.err.println("Required argument: weather ior file"); return; } try { ORB orb = ORB.init(args, null); BufferedReader in = new BufferedReader(new FileReader(args[0])); String ior = in.readLine(); in.close(); org.omg.CORBA.Object obj = orb.string_to_object(ior); Weather theWeather = WeatherHelper.narrow(obj); Daily currentDaily = theWeather.get_daily(); System.out.print("Weather Forecast for the City : "); System.out.println(theWeather.description()); System.out.println(" At Time :" +currentDaily.at_time); System.out.println(" Pressure "+currentDaily.pressure+" mb"); System.out.println(" Temperature is "+currentDaily.temperature+" deg celsius"); System.out.println(" Windspeed is "+currentDaily.windspeed+" m/hr"); } catch (Exception e) { e.printStackTrace(System.out); } } } Program2: import WeatherDetails.*;

public class WeatherImpl extends WeatherDetails._WeatherImplBase { private Daily _daily=null; private String _description=null; public WeatherImpl(String name,String description) { super(); _description = description; } public Daily get_daily() throws Unknown { if (_daily==null) throw new Unknown(); return _daily; } public void set_daily(Daily daily) { _daily = daily; } public String description() { return _description; } } 4.To run this client-server application on your development machine: a) Change to the directory that contains the file Weather.idl. b) Run the IDL-to-Java compiler, idlj, on the IDL file to create stubs and skeletons. This step assumes that you have included the path to the java/bin directory in your path. c) idlj -fall Weather.idl You must use the -fall option with the idlj compiler to generate both client and server-side bindings. The idlj compiler generates a number of files. 1. Compile the .java files, including the stubs and skeletons (which are in the directory WeatherApp). This step assumes the java/bin directory is included in your path. javac *.java WeatherApp/*.java

2. Start orbd. From an MS-DOS system prompt (Windows), enter: start orbd -ORBInitialPort 1050 Note that 1050 is the port on which you want the name server to run. The -ORBInitialPort argument is a required command-line argument. 7. Start the Weather server: From an MS-DOS system prompt (Windows), enter: start java WeatherServer -ORBInitialPort 1050 -ORBInitialHost localhost You will see StockServer ready and waiting... when the server is started. 8. Run the client application: java WeatherClient -ORBInitialPort 1050 -ORBInitialHost localhost

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

You might also like