Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 

Swing Chapter 26. (Special topics) Swing and CORBA. Easy for reading, Click here!

Custom Search
Swing Chapter 26. (Special topics) Swing and CORBA. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 3/4 



Previous Page Previous Page (2/4) - Next Page (4/4) Next Page
Subpages: 1. Java 2 and CORBA
2. Creating a CORBA interface
3. Creating a CORBA server
4. Creating a CORBA client

26.3  Creating a CORBA server

Now that we have the compiler-generated source files it's time to implement the CORBA server which will run on a remote computer. First let's take a look at the DataUnit interface describing a data object which can be transported to the caller. The following code is the compiler-generated DataUnit interface, and the associated DataUnitImpl class which implements this interface:

The Code: DataUnit.java

see \Chapter26\MarketDataApp\1

/*

 * File: ./MARKETDATAAPP/DATAUNIT.JAVA

 * From: MARKETDATA.IDL

 * Date: Tue Feb 09 11:31:12 1999

 *   By: idltojava Java IDL 1.2 Aug 18 1998 16:25:34

 */

package MarketDataApp;

public interface DataUnit extends org.omg.CORBA.Object,

 org.omg.CORBA.portable.IDLEntity

{

  String getSymbol();

  String getName();

  double getLast();

  double getOpen();

  double getChange();

  double getChangePr();

  int getVolume();

}

The Code: DataUnitImpl.java

see \Chapter26\MarketDataApp\1

package MarketDataApp;

import java.sql.*;

public class DataUnitImpl extends _DataUnitImplBase

{

  protected String  m_symbol;

  protected String  m_name;

  protected double  m_last;

  protected double  m_open;

  protected double  m_change;

  protected double  m_changePr;

  protected long    m_volume;

  public DataUnitImpl(ResultSet results)

   throws SQLException {

    m_symbol = results.getString(1);

    m_name = results.getString(2);

    m_last = results.getDouble(3);

    m_open = results.getDouble(4);

    m_change = results.getDouble(5);

    m_changePr = results.getDouble(6);

    m_volume = results.getLong(7);

  }

  public String getSymbol()   { return m_symbol; }

  public String getName()     { return m_name; }

  public double getLast()     { return m_last; }

  public double getOpen()     { return m_open; }

  public double getChange()   { return m_change; }

  public double getChangePr() { return m_changePr; }

  public int getVolume()      { return (int)m_volume; }

}

The compiler-generated DataUnit interface contains seven getXX() methods intended for retrieving data fields from the implementor. Note that these fields directly correspond to the data fields of our StockData class from chapter 18.

Class DataUnitImpl extends the compiler-generated _DataUnitImplBase class (not listed here), which, in turn, implements the DataUnit interface. The seven data fields declared in the DataUnitImpl class correspond to the getXX() methods of the DataUnit interface. The DataUnitImpl constructor takes an instance of java.sql.ResultSet as parameter, and reads data from each record of the given result set.

Note: CORBA does not support 8-byte integers, so we are forced to pass the m_volume variable as int.

The Code: MarketData.java

see \Chapter26\MarketDataApp\1

/*

 * File: ./MARKETDATAAPP/MARKETDATA.JAVA

 * From: MARKETDATA.IDL

 * Date: Tue Feb 09 11:31:12 1999

 *   By: idltojava Java IDL 1.2 Aug 18 1998 16:25:34

 */

package MarketDataApp;

public interface MarketData extends org.omg.CORBA.Object,

 org.omg.CORBA.portable.IDLEntity

{

  MarketDataApp.DataUnit getFirstData(String name,

   String password, int year, int month, int day)

    throws MarketDataApp.LoginException,

    MarketDataApp.CorbaSqlException;

  MarketDataApp.DataUnit getNextData()

   throws MarketDataApp.CorbaSqlException;

}

The Code: MarketDataServer.java

see \Chapter26\MarketDataApp\1

package MarketDataApp;

import java.sql.*;

import java.util.*;

import org.omg.CosNaming.*;

import org.omg.CosNaming.NamingContextPackage.*;

import org.omg.CORBA.*;

public class MarketDataServer extends _MarketDataImplBase

{

  protected Connection m_conn;

  protected Statement  m_stmt;

  protected ResultSet  m_results;

  public MarketDataServer() {

    try {

      // Load the JDBC-ODBC bridge driver

      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

    }

    catch (Exception e) {

      e.printStackTrace();

    }

  }

  public DataUnit getFirstData(String name, String password,

   int year, int month, int day)

   throws MarketDataApp.LoginException, MarketDataApp.CorbaSqlException

  {

    if (!name.equals("CORBA") || !password.equals("Swing"))

      throw new MarketDataApp.LoginException();

    String query = "SELECT data.symbol, symbols.name, "+

      "data.last, data.open, data.change, data.changeproc, "+

      "data.volume FROM DATA INNER JOIN SYMBOLS "+

      "ON DATA.symbol = SYMBOLS.symbol WHERE "+

      "month(data.date1)="+month+" AND day(data.date1)="+day+

      " AND year(data.date1)="+year;

    try {

      m_conn = DriverManager.getConnection(

        "jdbc:odbc:Market", "admin", "");

      m_stmt = m_conn.createStatement();

        m_results = m_stmt.executeQuery(query);

      if (m_results.next())

        return new DataUnitImpl(m_results);

      else {

        disconnect();

        return null;

      }

    }

    catch (Exception e) {

      e.printStackTrace();

      throw new CorbaSqlException(e.toString());

    }

  }

  public DataUnit getNextData()

   throws MarketDataApp.CorbaSqlException {

    try {

      if (m_results != null && m_results.next())

        return new DataUnitImpl(m_results);

      else {

        disconnect();

        return null;

      }

    }

    catch (Exception e) {

      e.printStackTrace();

      throw new CorbaSqlException(e.toString());

    }

  }

  protected void disconnect() {

    try {

      if (m_results != null)

        m_results.close();

      if (m_stmt != null)

        m_stmt.close();

      if (m_conn != null)

        m_conn.close();

    }

    catch (Exception e) {

      e.printStackTrace();

    }

    m_results = null;

    m_stmt = null;

    m_conn = null;

  }

  public static void main(String args[]) {    

    try {

      // create and initialize the ORB

      Properties props = new Properties();

      props.put("org.omg.CORBA.ORBInitialPort", "1250");

      ORB orb = ORB.init(args, props);

      // create server and register it with the ORB

      MarketDataServer server = new MarketDataServer();

      orb.connect(server);

      // get the root naming context

      org.omg.CORBA.Object objRef =

        orb.resolve_initial_references("NameService");

      NamingContext ncRef = NamingContextHelper.narrow(objRef);

      // bind the Object Reference in Naming

      NameComponent nc = new NameComponent("MarketData", "");

      NameComponent path[] = {nc};        

      ncRef.rebind(path, server);

      // wait for invocations from clients

      java.lang.Object sync = new java.lang.Object();

      synchronized (sync) {

        System.out.println("Waiting for client connection");

        sync.wait();

      }

    }

    catch (Exception e) {

      e.printStackTrace();

    }

  }

}

The MarketData interface, according to the IDL file described above, defines two methods: getFirstData() and getNextData(). Class MarketDataServer extends the compiler-generated _MarketDataImplBase class (not listed here), which, in turn, implements MarketData interface.

The MarketDataServer constructor loads the JDBC-ODBC bridge driver used to retrieve data from the database.

The getFirstData() method creates an SQL query and returns the first data record (in the form of a DataUnit) or null if no data is available. As a first step, typical for any network application, user authentication is checked. If the user's name or password does not match the required values, a LoginException is thrown.

Note: In a more realistic CORBA application we would use a more sophisticated mechanism of user authentication than hard-coding a single username and password! Encryption is an increasingly important topic for addressing the security of online transactions.

getFirstData() then creates an SQL query to retrieve data corresponding to a certain date, establishes a connection to the driver, creates an SQL statement, and executes a query. If at least one record is retrieved by that query, a new DataUnitImpl object is created and returned. Otherwise, the method returns null. Note that if any exceptions occur, they will be caught and thrown as CorbaSqlExceptions.

The getNextData() method will most likely be called repeatedly to retrieve remaining data records fetched by an SQL query. If the result set is currently in use and a new record can be retrieved, a new DataUnitImpl object is created and returned. Otherwise this method calls disconnect() and returns null. Similar to getFirstData(), all exceptions are caught and thrown as CorbaSqlExceptions.

The disconnect() method closes an SQL connection and sets all related references to null.

The main() method creates an instance of this server and registers it with an ORB. Let's discuss it step-by-step:

A call to the ORB.init() static method creates an ORB. The ORB constructor takes two parameters: a String array of application parameters, and a Properties instance created from within the application. Note that we have explicitly set the ORBInitialPort property to 1250, specifying the port for our ORB to run on.

A new MarketDataServer instance is created and connected to our ORB. At this point the ORB server can start receiving remote invocations.

The CORBA naming service is resolved, and a reference to the NamingContext instance is retrieved using the narrow() method (different implementations of this method serve as the equivalent of class casting).

A NameComponent object is created to encapsulate the name of this service: "MarketData". An array of NameComponents can hold a fully specified path to an object on any file or disk system. In our case this path contains only one element. The rebind() method binds this path and the server object, so a call to our server may be resolved by CORBA.

Finally, a java.lang.Object is created and access to it is synchronized to wait for a server connection.

Note: These steps are similar to the typical procedure used to establish an RMI connection.

Note: Because of name conflict with org.omg.CORBA.Object, all references to java.lang.Object must be explicit in Java 2 CORBA-related code.



[ Return to Swing (Book) ]


Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color


[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3


[ More in News Section ]


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy