A Working Example: JNBridgePro and WebSphere 5.0


A Working Example: JNBridgePro and WebSphere 5.0

Let’s observe an example provided by JNBridgePro called BasicCalculatorEJB. It demonstrates how to access Enterprise JavaBeans from C#. The EJBs will be running on IBM WebSphere Application Server 5.0. Assume that JNBridgePro 1.3 or later and a .NET framework are installed on a Windows machine. Also assume that WebSphere 5.0, along with the accompanying examples, exists on a compatible machine, which may be either the same machine as the .NET machine or a different machine reachable on the network.

Creating jnbcore.war

Create the jnbcore.war file as follows:

  1. Create a blank folder to hold the WAR file components. Call this folder <warroot>.

  2. Create folders <war-root>/WEB-INF and <war-root>/WEB-INF/lib.

  3. In <war-root>/WEB-INF/lib, place a copy of jnbcore.jar (copied from the JNBridgePro installation folder) and a copy of the BasicCalculatorEJB.jar file found in the Demos/J2EE-Examples/WebSpere5.0 folder in the installation.

  4. In <war-root>/WEB-INF, place copies of the files jnbcore.properties and web.xml found in the Demos/J2EE-Examples/WebSphere5.0 folder in the installation. Open a command-line window and navigate to <war-root>.

  5. Run the command jar cf jnbcore.war WEB-INF.

  6. Install jnbcore.war by starting the WebSphere Application Server and opening the Administration console. Install jnbcore.war in the usual way, using the supplied default values. There are two places where you must supply data:

    • When prompted for the context root, enter /jnbcore.

    • When asked for the JNDI name for the EJB-reference, enter WSsamples/BasicCalculator.

  7. Make sure the box asking whether the EJBs should be deployed remains unchecked. The BasicCalculator EJB has already been deployed.

  8. Once jnbcore.war is deployed, save it to the master configuration and start it.

  9. Exit the Administration console. Shut down WebSphere Application Server for the moment so that its jnbcore does not interfere with the jnbcore used by JNBProxy.

Building the Proxy DLL

Build the proxy assembly DLL as follows:

  1. Start a copy of the JNBProxy GUI-based tool.

  2. Select the menu item Project.Java options. Verify that the box Start Java Automatically is checked, and the Java configuration data is correct.

  3. Close the dialog box.

  4. Select the menu item Project.Edit Classpath and add the following files to the classpath:

    • <JNBridgePro-WebSphere5-demo-folder>/BasicCalculatorEJB.jar (it contains the classes BasicCalculator and BasicCalculatorHome, used in the C# code).

    • j2ee.jar in <was-server-root>/lib (it contains the classes EJBHome, EJBObject, and other EJB-related and JNDI-related support classes, including classes Context, InitialContext, and CreateException, used in the C# code). Close the dialog box. Create a proxy for RemoteException. The Java class is found in the local J2SDK file; no additional JAR file is needed.

  5. Select the menu item Project.Add Classes from Classpath and add the following classes. Make sure the box Include Supporting Classes is checked for each class added.

    • com.ibm.websphere.samples.technologysamples.ejb.stateless.basiccalculatorejb.BasicCalculator

    • com.ibm.websphere.samples.technologysamples.ejb.stateless.basiccalculatorejb.BasicCalculatorHome

    • javax.naming.Context

    • javax.naming.InitialContext

    • javax.naming.NamingException

    • javax.rmi.PortableRemoteObject

    • java.rmi.RemoteException

    • javax.ejb.CreateException

  6. Click OK to add the classes and all supporting classes to the Environment pane. This will take a few minutes. Check all the items in the environment (use the menu item Edit.Check All in Environment), and click on the Add button to move them all to the Exposed Proxies pane. Select the menu item Project.Build to build the proxy assembly. Choose an assembly name and click OK. The assembly will be written to a DLL file.

Building and Running the Client Application

These tasks can be similarly accomplished using the .NET Framework SDK:

  1. In Visual Studio .NET, create a new C# console application.

  2. Replace the generated file Class1.cs with the file Class1.cs located in the Demos/J2EE-Examples/WebSphere5.0 folder. You may wish to examine this file to see how the Java classes and EJBs are accessed from .NET.

  3. Add references to the previously generated proxy assembly DLL and to the assembly jnbshare.dll found in the JNBridgePro installation folder.

  4. Build the project.

  5. Find the file jnbproxy_tcp.config in the JNBridgePro installation folder and make a copy of it in the current project build directory. Rename the file jnbproxy.config.

  6. Restart WebSphere Application Server and verify that jnbcore.war has been deployed by looking in the standard output log or by opening the Administration console. Then run the .NET application. Output showing the results of calculations will be displayed.

The BasicCalculatorEJB Sample Files

Let’s look at some of the files for this example. First, the C# file. Here is the code:

Note

JNBridge LLC has given permission to quote the following code examples, which you can use as templates for developing your applications.

using System;
using java.lang;
using java.rmi;
using javax.ejb;
using javax.naming;
using javax.rmi;
using com.ibm.websphere.samples.technologysamples._
ejb.stateless.basiccalculatorejb;
/*
In C#, using imports the class libraries
*/

// JNBridgePro example C# code for WebSphere 5.0.
// Copyright 2003, JNBridge, LLC

namespace ws5Demo
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
BasicCalculatorHome basicCalculatorHome = null;

// get the context
// get the calculator home interface
try
{
System.Console.WriteLine("JNDI stuff...");
Context ctx = new InitialContext();
System.Console.WriteLine("Got context");
java.lang.Object homeObject =
ctx.lookup("WSsamples/BasicCalculator");
System.Console.WriteLine("Got home object");

basicCalculatorHome =
(BasicCalculatorHome) homeObject;
System.Console.WriteLine("Got calculator home interface");
}
catch( NamingException e )
{
System.Console.WriteLine("NamingException: " + e);
return;
}
catch( java.lang.Exception e2 )
{
System.Console.WriteLine("Generic exception: " + e2);
return;
}

// create the remote interface
BasicCalculator basicCalculator = null;
try
{
basicCalculator = basicCalculatorHome.create();
Console.WriteLine("got remote interface");
}
catch ( javax.ejb.CreateException e1)
{
Console.WriteLine("CreateException: " + e1);
return;
}
catch( java.lang.Exception e2 )
{
Console.WriteLine("Generic exception: " + e2);
return;
}

// do some calculations
try
{
double arg1 = 2.5;
double arg2 = 3.9;
double result;
// In C# we box the parameter into an object using {}, one for each argument
result = basicCalculator.makeSum(arg1, arg2)
Console.WriteLine("{0} + {1} = {2}", arg1, arg2, result);
result = basicCalculator.makeDifference(arg1, arg2);
Console.WriteLine("{0} - {1} = {2}", arg1, arg2, result);
result = basicCalculator.makeProduct(arg1, arg2);
Console.WriteLine("{0} * {1} = {2}", arg1, arg2, result);
result = basicCalculator.makeQuotient(arg1, arg2);
Console.WriteLine("{0} / {1} = {2}", arg1, arg2, result);
}
catch(java.lang.Exception ex)
{
Console.WriteLine("Generic exception
in calculation: " + ex);
return;
}
}
}
}

Next, here is the Web-app file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC"-//Sun Microsystems,Inc.//
DTD Web Application 2.2//EN" "http://java.sun.com
/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<display-name>JNBridgePro Servlet</display-name>
<servlet>
<servlet-name>JNBServlet</servlet-name>
<servlet-class>com.jnbridge.jnbcore.JNBServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<ejb-ref>
<ejb-ref-name>WSsamples/BasicCalculator</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<home>com.ibm.websphere.samples.technologysamples.
ejb.session.basiccalculatorejb.BasicCalculatorHome</home>
<remote>com.ibm.websphere.samples.technologysamples.
ejb.session.basiccalculatorejb.BasicCalculator</remote>
<ejb-link>BasicCalculator</ejb-link>
</ejb-ref>
</web-app>

JNBridgePro has included a Demo package with source code for you to use as a template for your own cross-platform applications. Here are the three classes: Book.Java, Author.Java, and DemoDBConnection.Java, in that order:

//Book.Java
package Demo2;
// Copyright 2002, JNBridge LLC
import java.sql.*;
import java.util.*;

public class Book
{
public String title;
public String publisher;
public String year;

public Book(String title, String publisher, String year)
{
this.title = title;
this.publisher = publisher;
this.year = year;
}

public static Book[] getBooks()
{
try
{
Connection conn = DemoDBConnection.getConnection();
Statement stmt = conn.createStatement();
ResultSet titles = stmt.executeQuery
("SELECT Title, Publisher, Year FROM Titles
ORDER BY Title");

Vector v = new Vector();
while (titles.next())
{
v.add(new Book(titles.getString("Title"),
titles.getString("Publisher"), titles.getString("Year")));
}

Book[] results = new Book[v.size()];
for (int i = 0; i < v.size(); i++)
{
results[i] = (Book) v.get(i);
}

return results; // for now
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e);
return null;
}
}

public static Book[] getBooks(String firstName, String lastName)
{
try
{
Connection conn = DemoDBConnection.getConnection();
Statement stmt = conn.createStatement();
String query = "SELECT Title,
Publisher, Year FROM Titles, Authors " +

"WHERE FirstName = \'" + firstName + "\' AND " +

"LastName = \'" + lastName + "\' AND Authors.ID =
Titles.AuthorID ORDER BY Title";

ResultSet titles = stmt.executeQuery(query);

Vector v = new Vector();
while (titles.next())
{
v.add(new Book(titles.getString("Title"),
titles.getString("Publisher"),
titles.getString("Year")));
}

Book[] results = new Book[v.size()];
for (int i = 0; i < v.size(); i++)
{
results[i] = (Book) v.get(i);
}

return results; // for now
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e);
return null;
}
}
}

Here is Author.Java:

//Author.Java
package Demo2;
// Copyright 2002, JNBridge LLC
import java.sql.*;
import java.util.*;

public class Author
{
public String firstName;
public String lastName;

public Author(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}

public static Author[] getAuthors()
{
try
{
Connection conn = DemoDBConnection.getConnection();
Statement stmt = conn.createStatement();
ResultSet authorNames =
stmt.executeQuery("SELECT LastName, FirstName
FROM Authors ORDER BY LastName");

Vector v = new Vector();
while (authorNames.next())
{
v.add(new Author
(authorNames.getString("FirstName"),
authorNames.getString("LastName")));
}

Author[] results = new Author[v.size()];
for (int i = 0; i < v.size(); i++)
{
results[i] = (Author) v.get(i);
}

return results; // for now
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e);
return null;
}
}
}

DemoDBConnection.Java follows:

//DemoDBConnection.Java
package Demo2;
// Copyright 2002, JNBridge LLC
import java.sql.*;

public class DemoDBConnection
{
private static DemoDBConnection theDBConnection
= new DemoDBConnection();
private Connection theConnection;

public static Connection getConnection()
{
return theDBConnection.theConnection;
}

private DemoDBConnection()
{
try
{
// load the database driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");


// allocate a connection object
theConnection = DriverManager.getConnection
("jdbc:odbc:BookDemo");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Next, the three stubs are presented. First, the Book stub:

//public class Book
package Demo2;
public class Book {
// Fields
public String title;
public String publisher;
public String year;

// Constructors
public Book(String string, String string1, String string2) { }

// Methods
public static Book[] getBooks() { return null;}
public static Book[] getBooks
(String string, String string1) { return null;}
}

Next, the following code is the Author stub:

package Demo2;
public class Author {
// Fields
public String firstName;
public String lastName;

// Constructors
public Author(String string, String string1) { }

// Methods
public static Author[] getAuthors() { return null;}
}

The following code represents the DemoDBConnection stub:

//This stub is DemoDBConnection
package Demo2;

// Imports
import java.sql.Connection;

public class DemoDBConnection {

// Fields
private static DemoDBConnection theDBConnection;
private Connection theConnection;

// Constructors
private DemoDBConnection() { }

// Methods
public static Connection getConnection() { return null;}
}

Next, we present the WebForm1.cs file:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Demo2;

// Copyright 2002, JNBridge LLC

namespace Demo3
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.ListBox ListBox1;
protected System.Web.UI.WebControls.Label Label2;
protected System.Web.UI.WebControls.ListBox ListBox2;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required
by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.ListBox1.Load +=
newSystem.EventHandler(this.ListBox1_Load);
this.ListBox1.SelectedIndexChanged += new
System.EventHandler(this.ListBox1_SelectedIndexChanged);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void ListBox1_Load(object sender, System.EventArgs e)
{
if (ListBox1.Items.Count > 0)
{
return; // don't add anything more
}

// load the authors
Author[] authors = Author.getAuthors();
for (int i = 0; i < authors.Length; i++)
{
ListItem li = new ListItem();
li.Text = authors[i].lastName + ", " +
authors[i].firstName;
ListBox1.Items.Add(li);
}
}

private void ListBox1_SelectedIndexChanged
(object sender, System.EventArgs e)
{
// clear listBox2
ListBox2.Items.Clear();

// if nothing selected, return
ListItem li = ListBox1.SelectedItem;

if (li == null)
{
return;
}

// last, first names
string name = li.Text;
int separator = name.IndexOf(",");
string lastName = name.Substring(0, separator);
string firstName = name.Substring(separator+2);

// look up books
Book[] titles = Book.getBooks(firstName, lastName);

// write out books
for (int i = 0; i < titles.Length; i++)
{
ListItem li2 = new ListItem();
string theBook = titles[i].title + "
(" + titles[i].publisher + ", "
+ titles[i].year + ")";
li2.Text = theBook;
ListBox2.Items.Add(li2);
}
}
}
}

A copy of the Access database including the Author and Book may be found in the Demo2 folder included with the JNBridgePro installation package.

In summary, JNBridgePro and Intrinsyc offer viable cross-platform business solutions for every business scenario. Finally, developers have a tool to facilitate true interoperability between J2EE version 1.3.1 and Microsoft .NET.




.NET & J2EE Interoperability
Microsoft .NET and J2EE Interoperability Toolkit (Pro-Developer)
ISBN: 0735619220
EAN: 2147483647
Year: 2004
Pages: 101
Authors: Simon Guest

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net