Anda di halaman 1dari 33

RAJALAKSHMI ENGINEERING COLLEGE Department of Computer Application

Subject Code :MC9251 Staff Name : Mr. A. Anthonisan Subject Name: MIDDLEWARE LAB

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

Ex.No: 1

An Application Using RMI

Aim: To create a distributed application to download various files from various servers using RMI Algorithm: 1. Create four files file interface, file implementation, file client and fileserver 2. In the file interface, class specify the prototype of the method that is to be implemented in the file implementation class 3. In the file implementation class, specify the implementation coding for the method defined earlier (download file[]) 4. Try to read the contents of a file in this class 5. In the fileclient class try to write some contents into a file 6. In the fileserver class, try to register / bind the methods with the rmiregistry 7. Compile all the files and execute as specified to get the desired output. Program 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{ 2

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[]) { try { FileInterface fi = new FileImpl("FileServer"); Naming.rebind("//127.0.0.1/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]); System.out.println(enter the file to download); BufferedReader br = new BufferedReader(new InputStreamReader(system.in)); String newname = br.readLine(); File file = new File(newname); 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(); } } } Execution Server folder [interface.java,fileimpl.java,file server.java] 1. Compile all the java program using (javac filename.java) 2. enter the (start rmiregistry) in command line 3. create stub and skeleton using (rmic FileImpl) 4.create one file i.e a.txt in server folder 5. Run the server using (java FileServer) Client folder[file interface.java,fileclient.java,copy the stub and skeleton from server folder and paste it in client folder] 1. Compile all the java program using (javac filename.java) (The next contains two parameters First is the text file created by the user second is machine IP Address) 2. Run the Client using (java FileClient a.txt 192.168.0.154) 7. next step you will give the file name to download the file (Enter the file name to download : b.txt) 8. a.txt and b.txt contains the same content.

Ex.No: 2

Application using Applets

Aim: to create a Java Bean to draw various graphical shapes and display it using or without using BDK Algorithm: 1. Create a class Appletdemo which extends Applet superclass and which implements ActionListener interface 2. Create five buttons with the required captions and add them to the container 3. Register the buttons with the ActionListener interface 4. In the Actionperformed () method, with the help of the instance, perform the action respectively 5. In the paint() method, check which button is pressed and display the shapes accordingly Program import java.awt.*; import java.applet.*; import java.awt.event.*; //<applet code="Appletdemo" height=500 width=500></applet> public class Appletdemo extends Applet implements ActionListener { String s; Button b1,b2; public void init() { b1= new Button("Test"); b2=new Button("circle"); add(b1); add(b2); b1.addActionListener(this); b2.addActionListener(this); } public void actionPerformed(ActionEvent ae) { s=ae.getActionCommand(); 5

repaint(); } public void paint(Graphics g) { try { if(s.equals("Test")); g.drawOval(122,53,62,75); //g.setColor(212, 23,45); if(s.equals("circle")); g.drawRect(122,122,122,122); } catch(NullPointerException e) {} } } Sample Output

Ex.No : 3

Developing an Enterprise Java Bean for Library operations

Aim : To develop an Enterprise Java Bean for Library operations Algorthm : 1. Create five programs Book, Bookbome, Bookbean, Bookexception, and Bookclient 2. In the Bookhome class just invoke the create() method with appropriate arguments 3. In the Book class, just define the prototytpes of addbook(), removebook() and getcontents() methods 4. In the Bookbean class provide the implementation for the various methods 5. In the Bookexception class provide the implementation for BookException 6. In the Bookclient class get the customer name and the various books he wants, also perform the other operations accordingly Program Book- Remote interface import javax.ejb.*; import java.rmi.*; import java.util.*; public interface Book extends EJBObject { public void addBook(String title) throws RemoteException; public void removeBook(String title) throws RemoteException,BookException; public Vector getContents() throws RemoteException; } Book-Home interface import java.io.Serializable; import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EJBHome; public interface BookHome extends EJBHome { public Book create(String person) throws RemoteException,CreateException; public Book create(String person,String id) throws RemoteException,CreateException; }

Book Bean class import java.util.*; import javax.ejb.*; public class BookEJB implements SessionBean { String CustomerName; String customerId; Vector contents; public void ejbCreate(String person) throws CreateException { if(person==null) throw new CreateException("\nNull person not allowed"); else CustomerName= person; System.out.println("\nCustomer name: "+person); customerId = "0"; contents = new Vector(); } public void ejbCreate(String person,String id) throws CreateException { if(person==null) throw new CreateException("\nNull person not allowed"); else CustomerName= person; System.out.println("\nCustomer name: "+person); 8

customerId = "0"; contents = new Vector(); } public void addBook(String title) { contents.addElement(title); } public void removeBook(String title) throws BookException { boolean result = contents.removeElement(title); if(result==false) throw new BookException(title+" Book is not in cart"); } public Vector getContents() { return contents; } public BookEJB() {} public void ejbActivate() {} public void ejbPassivate() {} public void ejbRemove() {} public void setSessionContext(SessionContext ctx) {} }

Book-Exception 9

public class BookException extends Exception { public BookException() {} public BookException(String msg) { super(msg); } }

Book-Client
import javax.naming.*; import javax.rmi.*; import java.rmi.*; import java.io.*; import java.util.*; public class BookClient { public static void main(String arg[]) { Enumeration enum; Vector bookList; Book shoppingCart;

10

try { Properties p = new Properties(); p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactor y"); p.put(Context.PROVIDER_URL,"t3://localhost:7001"); p.put(Context.SECURITY_PRINCIPAL,"mca"); p.put(Context.SECURITY_CREDENTIALS,"mcastudent"); InitialContext ict = new InitialContext(p); System.out.println("Context sucessful"); Object t = ict.lookup("BookEJB2"); System.out.println("Lookup successful"); BookHome home = (BookHome)PortableRemoteObject.narrow(t,BookHome.class); shoppingCart = home.create("Siva","123"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("\nEnter customer name "); String cust = br.readLine(); System.out.println("\nEnter the bookname U want: "); String book1 = br.readLine(); shoppingCart.addBook(book1); System.out.println("\nEnter the bookname U want: "); String book2 = br.readLine(); shoppingCart.addBook(book2); System.out.println("\nEnter the bookname U want: "); String book3 = br.readLine();

11

shoppingCart.addBook(book3); System.out.println("\nCustomer name is :"+cust); System.out.println("Selected books are listed below"); bookList = new Vector(); bookList = shoppingCart.getContents(); enum = bookList.elements(); while(enum.hasMoreElements()) { String title = (String)enum.nextElement(); System.out.println(title); } System.out.println("\nDo U want to remove any book from cart"); String ch = br.readLine(); if(ch.equals("y")) { try { System.out.println("Enter the book name"); String remBook = br.readLine(); shoppingCart.removeBook(remBook); System.out.println("\nBook has been removed from the cart"); System.out.println("Customer nmae: "+cust); System.out.println("Slected books are listed below"); bookList = shoppingCart.getContents(); enum = bookList.elements(); 12

while(enum.hasMoreElements()) { String title1 = (String)enum.nextElement(); System.out.println(title1); } System.out.println("Thanks for dealing with us"); } catch(Exception ex) { System.out.println("caught a BookException " +ex.getMessage()); } } else System.out.println("thanks for dealing with us"); shoppingCart.remove(); } catch(Exception ex) { System.out.println("Caught a Book Exception"); ex.printStackTrace(); } } }

13

Ex.No : 4

Developing an Enterprise Java Bean for banking operations

Aim : To develop an Enterprise Java Bean for banking operations Algorthm : 1. Create four programs- Bankbean, Bankhome, Bank, and Bankclient 2. In the Bankbean class first define the prototypes of the various methods 3. Next, provide the implementation for ejbCreate(), ejbPostCreate(), credit(), and debit() methods 4. In the Bankhome class just invoke the methods create() and findbyprimarykey() with the respective number of arguments 5. In the Bankremote class just define the prototypes of the various methods which throws the Remoteexception 6. In the Bankclient class, display the options to the user and use the lookup() method and perform the operations accordingly Program Bank-Remote Interface import javax.ejb.*; import java.rmi.*; import java.util.*; public interface BankRemote extends EJBObject { public Integer getCusid() throws RemoteException; public void setBal(double balance) throws RemoteException; public double getBal() throws RemoteException; public void debit(double amount) throws RemoteException; public void credit(double amount) throws RemoteException; } Bank-Home interface import java.io.*; import java.rmi.RemoteException; import javax.ejb.*;

14

public interface BankHome extends EJBHome { public BankRemote create(Integer empid,double balance) throws RemoteException,CreateException; public BankRemote findByPrimaryKey(Integer cusid) throws FinderException,RemoteException; } Bank-Bean class import javax.rmi.*; import javax.ejb.*; public abstract class BankBean implements EntityBean { public double cbalance; public double amount; public double balance; public EntityContext context,ctx; public Integer id; public void ejbActivate() {} public void ejbPassivate() {} public void ejbRemove() {} public void ejbLoad(){} public void ejbStore(){} public void setEntityContext(EntityContext ctx) {} public void unsetEntityContext() {} public abstract void setCusid(Integer cusid); public abstract Integer getCusid(); public abstract void setBal(double balance); public abstract double getBal(); public Integer ejbCreate(Integer cusid,double balance) { setCusid(cusid); setBal(balance); return null; } public void ejbPostCreate(Integer cusid,double balance){} public void debit(double amount) { balance = getBal(); balance-= amount; setBal(balance); } public void credit(double amount) { balance = getBal();

15

balance+=amount; setBal(balance); } } Bank Client import javax.naming.*; import javax.rmi.*; import java.rmi.*; import java.io.*; import java.util.*; import javax.ejb.*; public class BankClient { public static void main(String arg[]) { int cid; double cbalance; int ch; double camount; try { Properties p = new Properties(); p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); p.put(Context.PROVIDER_URL, "t3://localhost:7001"); p.put(Context.SECURITY_PRINCIPAL,"rec"); p.put(Context.SECURITY_CREDENTIALS, "mcastudent"); InitialContext ict = new InitialContext(p); System.out.println("Context sucessful"); Object t = ict.lookup("BankBean1"); System.out.println("Lookup successful"); BankHome h = (BankHome)PortableRemoteObject.narrow(t,BankHome.class); System.out.println("Home stub obtained"); try { System.out.println("\n 1.CREATE \n2. CREDIT \n3. DEBIT \n4. BALANCE \n5. EXIT"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); ch=Integer.parseInt(br.readLine()); switch(ch) { case 1: System.out.println("\nEnter the account number: ");

16

cid = Integer.parseInt(br.readLine()); System.out.println("\nEnter Initial amount: "); camount = Integer.parseInt(br.readLine()); BankRemote e = h.create(new Integer(cid),camount); System.out.println("Successfully inserted"); break; case 2: System.out.println("\nEnter the account number: "); cid = Integer.parseInt(br.readLine()); BankRemote c = h.findByPrimaryKey(new Integer(cid)); System.out.println("\nEnter the amount: "); camount = Integer.parseInt(br.readLine()); c.credit(camount); cbalance = c.getBal(); System.out.println("Available balance: "+cbalance); break; case 3: System.out.println("\nEnter the account number: "); cid = Integer.parseInt(br.readLine()); BankRemote d = h.findByPrimaryKey(new Integer(cid)); System.out.println("\nEnter the amount: "); camount = Integer.parseInt(br.readLine()); d.debit(camount); cbalance = d.getBal(); System.out.println("Available balance: "+cbalance); break; case 4: System.out.println("\nEnter the account number: "); cid = Integer.parseInt(br.readLine()); BankRemote b = h.findByPrimaryKey(new Integer(cid)); cbalance = b.getBal(); System.out.println("Available balance: "+cbalance); break; } } catch(IOException e) { System.out.println("Exception invoked"); } catch(Exception e) { System.out.println("Invalid Customer ID"); } } catch(Exception ex) { ex.printStackTrace(); } }}

17

Ex.No :5

Create an Active-X control for File operations

Aim : To develop an Activex control document and perform the various file operations on it. Algorthm : 1. Create a new Activex control document in Visual Basic 2. Add the drive list, directory list and file list controls from the toolbox 3. Also add three textboxes correspondingly 4. Click on File -> make project1. ocx and specify the required name and location 5. Double click on each control to add the respective coding 6. click on debug-> start to execute the application

Program
FILE OPERATIONS USING ACTIVEX CONTROL Private Sub Dir1_Change() File1.Path = Dir1.Path End Sub Private Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub Private Sub File1_Click() Text1.Text = File1.Path End Sub Private Sub Dir1_Click() Text2.Text = Dir1.FontName Text3.Text = Dir1.ListIndex End Sub

18

Ex.No: 6 Aim:

COMPONENT SIMULATING CURRENCY CONVERSION

To write a program in C# to perform conversion of dollars to rupees. Algorithm: ALGORITHM FOR COMPONENT. Step 1: Create a namespace as currwithcomp. Step 2: Create a class called currency as public. Step 3: Inside the class declare the private variables x of type integer. Step 4: Define a property variables x. Step 5: In the property we have the get and set method. Step 6: Get method is used to get the value form the user and set is used for setting the user value to the original variables. Step 7: Define a method called doll() as public. Step 7.1: Return the value of x * 46. Step 7.2: End of the method. Step 8: End of the component. AGORITHM FOR MAIN. Step 1: Create a class called curr. Step 2: Define the main function. Step 2.1: Create an object ob for currency. Step 2.2 : Get the value of x using Console.Readline() method. Step 2.3: Print the converted value using Console.Writeline() method. Step 2.4: End of the main. Program: COMPONENT using System; namespace CompCS { public class Conv { private int i=0,j=45; public int varI

19

{ get{return i;} set{i=value;} } public int sum() { return i*j; } } } MAIN using System; using CompCS; class ConvertComp { public static void Main() { Conv obj = new Conv(); Console.WriteLine("Enter the dollar amount u want to convert:"); int x = int.Parse(Console.ReadLine()); obj.varI = x; Console.WriteLine("Dollar value : {0}",obj.varI); Console.WriteLine("Ruppes value : {0}",obj.sum()); } } Execution Steps: 1.Create a dll file for the component csc /target:library Convert.cs 2.Create an exe file for the main csc /reference:Convert.dll ConvertComp.cs 3.Run the exe file ConvertComp Output: Enter the dollar amount u want to convert:30 Dollar value : 30

20

Ruppes value : 1350

CONVERTING THE CURRENCY VALUES USING COM

CODINGS FOR BUSSINESS LAYER *************************** Public Class Class1 Public Function cur1(ByVal c1 As String) As String cur1 = c1 * 43.44 MsgBox(cur1) End Function Public Function cur2(ByVal c2 As String) As String cur2 = c2 * 57.105 MsgBox(cur2) End Function Public Function cur3(ByVal c3 As String) As String cur3 = c3 * 114.73 MsgBox(cur3) End Function Public Function cur4(ByVal c4 As String) As String cur4 = c4 * 12.024 MsgBox(cur4) End Function Public Function cur5(ByVal c5 As String) As String cur5 = c5 * 1.6623 MsgBox(cur5) End Function End Class 21

CODINGS FOR PRESENTATION LAYER ****************************** Public Class Form1 Dim obj As New classLibrary1.class1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If (ComboBox1.Text = "Usa Doller") Then Dim s = Val(TextBox1.Text) obj.cur1(s) ElseIf (ComboBox1.Text = "Eurro") Then Dim s = Val(TextBox1.Text) obj.cur2(s) ElseIf (ComboBox1.Text = "Oman Rial") Then Dim s = Val(TextBox1.Text) obj.cur3(s) ElseIf (ComboBox1.Text = "Uae Dirham") Then Dim s = Val(TextBox1.Text) obj.cur4(s) ElseIf (ComboBox1.Text = "Russian Rouble") Then Dim s = Val(TextBox1.Text) obj.cur5(s) End If End Sub End Class

22

Ex.No: 7 Aim:

COMPONENT SIMULATING ENCRYPRION AND DECRYPTION

To write a C# program to perform encryption and decryption of the given data. Algorithm ALGORITHM FOR ENCRYPTION: Step 1: Step 2: Step 3: type. Step 4: Declare the class as encrypt_class. Start the main function. Declare the variable str in string data

Create the object for inbuild encryption algorithm TripleDESCryptoServiceProvider. Step 5: Create the data file using Filestream class. Step 6: Create the object for class cryptoStream. Cryptostream is a class to invoke the Encryotor algorithm. Get the input from the user using Console.Readline(). Step 7: Write the input data using WriteLine function. Step 8: Create the key file using File.Create. Step 9: convert the key file into binary form. Step 10:Close the file. Step 11:Print Data encrypted using console.writeLine.

ALGORITHM FOR DECRYPTION : Step 1: Declare a class as decrypt_class Step 2: start the main function Step 3:Create the object for the inbuild algorithm TripleDESCrypotserviceProvider. Step 4: Create the file in c drive using FileStream fs =File.openRead. Step 5: Using Binary Reader convert file as in

23

binary form. Step 6:Read the number of bytes of key file. Step 7: Open the data file using FileRead function. Step 8: Cryptostream is a class to use invoke the Decrytptor. Step 9: Create the object for CryptoStream class. Step 10: Using StreamReader read the data file . Step 11: Print the content of data file using Console.writeLine. Step 12: Close the file.

Program: Encryption using System; using System.IO; using System.Security.Cryptography; class encrypt_class { public static void Main() { String str; TripleDESCryptoServiceProvider cp= new TripleDESCryptoServiceProvider(); FileStream fs = File.Create("C:\\file.dat"); CryptoStream cs = new CryptoStream(fs,cp.CreateEncryptor(),CryptoStreamMode.Write ); StreamWriter sw = new StreamWriter(cs); Console.WriteLine("Enter a string"); str=Console.ReadLine(); sw.WriteLine(str); sw.Close(); fs= File.Create("C:\\file.key");

24

BinaryWriter bw = new BinaryWriter(fs); bw.Write(cp.Key); bw.Write(cp.IV); bw.Close(); Console.WriteLine("Data Encrypted........"); } } Decryption: using System; using System.IO; using System.Security.Cryptography; class decrypt_class { public static void Main() { TripleDESCryptoServiceProvider cp= new TripleDESCryptoServiceProvider(); FileStream fs = File.OpenRead("C:\\file.key"); BinaryReader br = new BinaryReader(fs); cp.Key=br.ReadBytes(24); cp.IV=br.ReadBytes(8); fs= File.OpenRead("C:\\file.dat"); CryptoStream cs = new CryptoStream(fs,cp.CreateDecryptor(),CryptoStreamMode.Read); StreamReader sr = new StreamReader(cs); Console.WriteLine("Content in the file (After Decryption)"); Console.WriteLine(sr.ReadLine()); sr.Close(); } } Execution: csc encrypt_class.cs encrypt_class file Enter the string

25

Abcdefghijklmnopqrstuvwxyz Data encrypted csc decrypt_class.cs decrypt_class file Content in the file is (After decryption) Abcdefghijklmnopqrstuvwxyz. ENCRYPTION AND DECRYPTION PROGRAM USING COM Dim dstr As String Dim i As Integer Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click For i = 1 To Len(TextBox1.Text) dstr = dstr + Chr(Asc(Mid(TextBox1.Text, i, 1)) + i) Next TextBox1.Text = dstr End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click dstr = "" For i = Len(TextBox1.Text) To 1 Step -1 dstr = Chr(Asc(Mid(TextBox1.Text, i, 1)) - i) + dstr Next TextBox1.Text = dstr End Sub 8 Develop a middleware component for retrieving Stock Market Exchange information using CORBA 26

Stock Market.idl module SimpleStocks{ interface StockMarket { float get_price(in string symbol); }; }; StockMarketClient.java import org.omg.CORBA.*; import org.omg.CosNaming.*; import SimpleStocks.*; public class StockMarketClient { public static void main(String[] args) { try { ORB orb=ORB.init(args,null); NamingContext ncRef=NamingContextHelper.narrow(orb.resolve_initial_references("NameService")); NameComponent path[]={new NameComponent("NASDAQ","")}; StockMarket market=StockMarketHelper.narrow(ncRef.resolve(path)); System.out.println("Price of My company is"+market.get_price("My_COMPANY")); } catch(Exception e){ e.printStackTrace(); } } } StockMarketImpl import org.omg.CORBA.*; import SimpleStocks.*; public class StockMarketImpl extends _StockMarketImplBase { public float get_price(String symbol) { float price=0; for(int i=0;i<symbol.length();i++)

27

{ price+=(int)symbol.charAt(i);} price/=5; return price; } public StockMarketImpl(){super();} } StockMarketServer import org.omg.CORBA.*; import org.omg.CosNaming.*; import SimpleStocks.*; public class StockMarketServer { public static void main(String[] args) { try { ORB orb=ORB.init(args,null); StockMarketImpl stockMarketImpl=new StockMarketImpl(); orb.connect(stockMarketImpl); org.omg.CORBA.Object objRef=orb.resolve_initial_references("NameService"); NamingContext ncRef=NamingContextHelper.narrow(objRef); NameComponent nc=new NameComponent("NASDAQ",""); NameComponent path[]={nc}; ncRef.rebind(path,stockMarketImpl); System.out.println("StockMarket server is ready"); Thread.currentThread().join(); } catch(Exception e){ e.printStackTrace(); } } }

EXECUTION STEPS 1.cREATE A INTERFACE(idl,CPP)

28

2.Create IMPLEMENTATION PROGRAM 3.sERVER PROGRAM 4.Client program 5.cOMMAND idltojava -fno-cpp interfacename.idl javac servant javac server javac client tnameserv -ORBInitialPort 900 java HelloServer in another window cmd java StockMarketClient

10.

COMMUNICATION BETWEEN CLIENT AND SERVER USING CORBA

Aim: To write a program to print Hello World in CORBA. Algorithm: Step 1: Start the process Step 2: Create an idl class in a module Hello1and declare a method sayHello(). Step 3: Create an implement class HelloImpl which extends _HelloImplBase and import the module. Step 4: Define the sayHello method and return the result. Step 5: Define the client program named HelloClient which imports the module (i) Declare a static reference for interface Hello (ii) Create and initialize the ORB and get the root naming context. (iii) Resolve the Object Reference in Naming. (iv) Call the sayHello method Step 6: (i) (ii) (iii) (iv) Create the HelloServer which imports the module. Create and initialize the ORB. Create servant and register it with the ORB. Get object reference from the servant. Bind the Object Reference in Naming. 29

(v) Use NamingContext. (vi) Wait for invocations from clients Step 7: Stop the process. Program Code: IDL Class:module Hello1 { interface Hello { string sayHello(); }; }; Client Class:import Hello1.*; import org.omg.CosNaming.*; import org.omg.CosNaming.NamingContextPackage.*; import org.omg.CORBA.*; public class HelloClient { static Hello helloImpl; public static void main(String args[]) { try { // create and initialize the ORB ORB orb = ORB.init(args, null); // get the root naming context org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); NamingContext ncRef = NamingContextHelper.narrow(objRef); // resolve the Object Reference in Naming NameComponent nc=new NameComponent ("Hello",""); NameComponent path[] = {nc}; helloImpl = HelloHelper.narrow(ncRef.resolve(path)); System.out.println(helloImpl.sayHello()); } catch (Exception e) { System.out.println("ERROR : " + e) ;

30

} } } Implement Class: import Hello1.*; import org.omg.CosNaming.*; import org.omg.CosNaming.NamingContextPackage.*; import org.omg.CORBA.*; import java.util.Properties; class HelloImpl extends _HelloImplBase { // implement sayHello() method public String sayHello() { return "\nHello world !!\n"; } }

Server Class:import import import import Hello1.*; org.omg.CosNaming.*; org.omg.CosNaming.NamingContextPackage.*; org.omg.CORBA.*;

public class HelloServer { public static void main(String args[]) { try { // create and initialize the ORB ORB orb = ORB.init(args, null); // create servant and register it with the ORB HelloImpl helloImpl = new HelloImpl(); orb.connect(helloImpl); // get object reference from the servant org.omg.CORBA.Object objRef =orb.resolve_initial_references("NameService"); // Use NamingContext NamingContext ncRef = NamingContextHelper.narrow(objRef); // bind the Object Reference in Naming

31

NameComponent nc=new NameComponent ("Hello",""); NameComponent path[] = {nc}; ncRef.rebind(path, helloImpl); System.out.println("HelloServer ready and waiting ..."); // wait for invocations from clients orb.run(); } catch (Exception e) { System.err.println("ERROR: " + e); } System.out.println("HelloServer Exiting ..."); } } Output: Impl Side: Z:\Middle ware\corba1>idlj -fclient -fserver -implBase hello.idl Z:\Middle ware\corba1>cd hello1 Z:\Middle ware\corba1\Hello1>javac *.java Z:\Middle ware\corba1>tnameserv Initial Naming Context: IOR:000000000000002849444c3a6f6d672e6f72672f436f734e61 6d696e672f4e616d696e 67436f6e746578743a312e30000000000100000000000000540001 01000000000d313732 2e31362e312e3130380000041f00000018afabcafe00000002584b 271b000000080000000 000000000000000010000000100000014000000000001002000000 000000101000000000 TransientNameServer: setting port for initial object references to: 900 Ready. Server Side: Z:\Middle ware\corba1>javac *.java Z:\Middle ware\corba1>java HelloServer HelloServer ready and waiting... Client Side: Z:\Middle ware\corba1>java HelloClient

32

Hello world!!

33

Anda mungkin juga menyukai