Monday, 7 March 2011

Generic database insert and select code

public class J850sjdbc {

public static String insert(String names, String values) {

java.sql.Connection conn = linktodata();

String todo = ("INSERT into staff " +
"(" + names + ") values (" + values + ")");

try {
java.sql.Statement s = conn.createStatement();
int r = s.executeUpdate (todo);
}
catch (Exception e) {
return ("Oh oops - code 003\n"+e);
}

return (todo);

}

public static String select(String [] fields, String selector) {

java.sql.Connection conn = linktodata();

StringBuffer reply = new StringBuffer("<table border=1>");

String todo = ("SELECT * "+
" from staff " + selector);

try {
java.sql.Statement s = conn.createStatement();
java.sql.ResultSet r = s.executeQuery (todo);
while(r.next()) {
reply.append("<tr>");
for (int i=0;i<fields.length;i++) {
reply.append(tabit(r.getString(fields[i])));
}
reply.append("</tr>");
}
reply.append("</table>");
}
catch (Exception e) {
return ("Oh oops - code 003\n"+e);
}

return (reply.toString());

}

private static String tabit(String box) {
return ("<td>"+box+"</td>");
}

private static java.sql.Connection linktodata () {

java.sql.Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception e) {
return conn;
// return "Oh dear - code 001 and a quarter";
}
try {
conn = java.sql.DriverManager.getConnection(
"jdbc:mysql://bhajee/J850a?user=jtest&password=");
}
catch (Exception e) {
return conn;
// return "Oh dear - code 001 and a half";
}
return conn;
}
}

Friday, 4 March 2011

RMI and CORBA

 Java RMI is a mechanism that allows one to invoke a method on an object that exists in another address space. The other address space could be on the same machine or a different one. The RMI mechanism is basically an object-oriented RPC mechanism. CORBA is another object-oriented RPC mechanism. CORBA differs from Java RMI in a number of ways:
  1. CORBA is a language-independent standard.
  2. CORBA includes many other mechanisms in its standard (such as a standard for TP monitors) none of which are part of Java RMI.
  3. There is also no notion of an "object request broker" in Java RMI.
Java RMI has recently been evolving toward becoming more compatible with CORBA. In particular, there is now a form of RMI called RMI/IIOP ("RMI over IIOP") that uses the Internet Inter-ORB Protocol (IIOP) of CORBA as the underlying protocol for RMI communication.
This tutorial attempts to show the essence of RMI, without discussing any extraneous features. Sun has provided a Guide to RMI, but it includes a lot of material that is not relevant to RMI itself. For example, it discusses how to incorporate RMI into an Applet, how to use packages and how to place compiled classes in a different directory than the source code. All of these are interesting in themselves, but they have nothing at all to do with RMI. As a result, Sun's guide is unnecessarily confusing. Moreover, Sun's guide and examples omit a number of details that are important for RMI.
There are three processes that participate in supporting remote method invocation.
  1. The Client is the process that is invoking a method on a remote object.
  2. The Server is the process that owns the remote object. The remote object is an ordinary object in the address space of the server process.
  3. The Object Registry is a name server that relates objects with names. Objects are registered with the Object Registry. Once an object has been registered, one can use the Object Registry to obtain access to a remote object using the name of the object.

Thursday, 3 March 2011

Rmi : The concept and terminologies

In the last article, we saw Objects which have to be made available to other machines have to be exported to something called a Remote Registry Server so that they can be invoked. So if Machine A wants to call methods of some object on Machine B, then Machine B would have to export that object on its Remote Registry Server. Remote Registry Server is a service that runs on the server and helps client’s search and access objects on the server remotely. Now, if an object has to be capable of being exported then it must implement the Remote Interface present in the RMI package. For example, say that you want an object Xyz on machine A to be available for remote method invocation, then it must implement the Remote interface.

RMI uses something called a stub and a skeleton. The stub is present on the client side, and the skeleton the server side. When you call remote methods, you don't just go directly to other machine and say "hey, here's the method name, here are the parameters, just give me back what has to be returned and I am out of here".

There are a number of events that have to take place beforehand which help in the communication of the data. The stub is like a local object on the client side, which acts like a proxy of the object on the server side. It provides the methods to the client which can be invoked on the server. The Stub then sends the method call to the Skeleton, which is present on the server side. The Skeleton then implements the method on the server side.

The Stub and the Skeleton communicate with each other through something called a Remote Reference Layer. This layer gives the stub and skeleton the capability to send data using the TCP/IP protocol. Let's take a quick look at a simple technique called "Binding".

Whenever a client wants to make a reference to any object on the server, have you thought how he would tell the server what object he wants to create? Well, this is where this concept of "Binding" comes in. On the server end we associate a string variable with an object (we have methods to do this. We will learn more about these when we start coding). The client tells the server what object he wants to create by passing that string to the server, thus letting the server know exactly what object you are talking about. All of these strings and objects are stored in the Remote Registry Server on the server.
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 before. RMI allows both client and server to dynamically load new object types as required.

Overview

Remote Method Invocation (RMI) facilitates object function calls between Java Virtual Machines (JVMs). JVMs can be located on separate computers - yet one JVM can invoke methods belonging to an object stored in another JVM. Methods can even pass objects that a foreign virtual machine has never encountered before, allowing dynamic loading of new classes as required. This is a powerful feature!
Consider the follow scenario :
  • Developer A writes a service that performs some useful function. He regularly updates this service, adding new features and improving existing ones.
  • Developer B wishes to use the service provided by Developer A. However, it's inconvenient for A to supply B with an update every time.
Java RMI provides a very easy solution! Since RMI can dynamically load new classes, Developer B can let RMI handle updates automatically for him. Developer A places the new classes in a web directory, where RMI can fetch the new updates as they are required.


rmidiagr.gif (6734 bytes)
Figure 1 - Connections made when client uses RMI
Figure 1 shows the connections made by the client when using RMI. Firstly, the client must contact an RMI registry, and request the name of the service. Developer B won't know the exact location of the RMI service, but he knows enough to contact Developer A's registry. This will point him in the direction of the service he wants to call..
Developer A's service changes regularly, so Developer B doesn't have a copy of the class. Not to worry, because the client automatically fetches the new subclass from a webserver where the two developers share classes. The new class is loaded into memory, and the client is ready to use the new class. This happens transparently for Developer B - no extra code need to be written to fetch the class.

Writing RMI services

Writing your own RMI services can be a little difficult at first, so we'll start off with an example which isn't too ambitious. We'll create a service that can calculate the square of a number, and the power of two numbers (238 for example). Due to the large size of the numbers, we'll use the java.math.BigInteger class for returning values rather than an integer or a long.

Writing an interface

The first thing we need to do is to agree upon an interface, An interface is a description of the methods we will allow remote clients to invoke. Let's consider exactly what we'll need.
  1. A method that accepts as a parameter an integer, squares it, and returns a BigInteger
    public BigInteger square ( int number_to_square );
  2. A method that accepts as a parameter two integers, calculates their power, and returns a BigInteger
    public BigInteger power ( int num1, int num2 );
Once we've decided on the methods that will compose our service, we have to create a Java interface. An interface is a method which contains abstract methods; these methods must be implemented by another class. Here's the source code for our service that calculates powers.

import java.math.BigInteger;
import java.rmi.*;

//
// PowerService Interface
//
// Interface for a RMI service that calculates powers
//
public interface PowerService extends java.rmi.Remote
{
// Calculate the square of a number
public BigInteger square ( int number )
throws RemoteException;

// Calculate the power of a number
public BigInteger power ( int num1, int num2)
throws RemoteException;
}
Our interface extends java.rmi.Remote, which indicates that this is a remote service. We provide method definitions for our two methods (square and power), and the interface is complete. The next step is to implement the interface, and provide methods for the square and power functions.

Implementing the interface

Implementing the interface is a little more tricky - we actually have to write the square and power methods! Don't worry if you're not sure how to calculate squares and powers, this isn't a math lesson. The real code we need to be concerned about is the constructor and main method.
We have to declare a default constructor, even when we don't have any initialization code for our service. This is because our default constructor can throw a java.rmi.RemoteException, from its parent constructor in UnicastRemoteObject. Sound confusing? Don't worry, because our constructor is extremely simple.
public PowerServiceServer () throws RemoteException
    {
        super();
    }

Our implementation of the service also needs to have a main method. The main method will be responsible for creating an instance of our PowerServiceServer, and registering (or binding) the service with the RMI Registry. Our main method will also assign a security manager to the JVM, to prevent any nasty surprises from remotely loaded classes. In this case, a security manager isn't really needed, but in more complex systems where untrusted clients will be using the service, it is critical.
    public static void main ( String args[] ) throws Exception
    {
        // Assign a security manager, in the event that dynamic
       // classes are loaded

       if (System.getSecurityManager() == null)
            System.setSecurityManager ( new RMISecurityManager() );

       // Create an instance of our power service server ...
       PowerServiceServer svr = new PowerServiceServer();

       // ... and bind it with the RMI Registry
       Naming.bind ("PowerService", svr);

       System.out.println ("Service bound....");
    }
Once the square and power methods are added, our server is complete. Here's the full source code for the PowerServiceServer.
import java.math.*;
import java.rmi.*;
import java.rmi.server.*;

//
// PowerServiceServer
//
// Server for a RMI service that calculates powers
//

public class PowerServiceServer extends UnicastRemoteObject
implements PowerService
{
public PowerServiceServer () throws RemoteException
{
super();
}

// Calculate the square of a number
public BigInteger square ( int number )
throws RemoteException
{
String numrep = String.valueOf(number);
BigInteger bi = new BigInteger (numrep);

// Square the number
bi.multiply(bi);

return (bi);
}

// Calculate the power of a number
public BigInteger power ( int num1, int num2)
throws RemoteException
{
String numrep = String.valueOf(num1);
BigInteger bi = new BigInteger (numrep);

bi = bi.pow(num2);
 return bi;
}

public static void main ( String args[] ) throws Exception
{
// Assign a security manager, in the event that dynamic
// classes are loaded

if (System.getSecurityManager() == null)
System.setSecurityManager ( new RMISecurityManager() );

// Create an instance of our power service server ...
PowerServiceServer svr = new PowerServiceServer();

// ... and bind it with the RMI Registry
Naming.bind ("PowerService", svr);

System.out.println ("Service bound....");
}
}

Writing a RMI client

What good is a service, if you don't write a client that uses it? Writing clients is the easy part - all a client has to do is call the registry to obtain a reference to the remote object, and call its methods. All the underlying network communication is hidden from view, which makes RMI clients simple.
Our client must first assign a security manager, and then obtain a reference to the service. Note that the client receives an instance of the interface we defined earlier, and not the actual implementation. Some behind-the-scenes work is going on, but this is completely transparent to the client.
    // Assign security manager
    if (System.getSecurityManager() == null)
    {
        System.setSecurityManager   (new RMISecurityManager());
    }

    // Call registry for PowerService
    PowerService service = (PowerService) Naming.lookup
        ("rmi://" + args[0] + "/PowerService");
To identify a service, we specify an RMI URL. The URL contains the hostname on which the service is located, and the logical name of the service. This returns a PowerService instance, which can then be used just like a local object reference. We can call the methods just as if we'd created an instance of the remote PowerServiceServer ourselves.
// Call remote method
System.out.println    ("Answer : " + service.square(value));
        // Call remote method
        System.out.println    ("Answer : " + service.power(value,power));
Writing RMI clients is the easiest part of building distributed services. In fact, there's more code for the user interface menu in the client than there is for the RMI components! To keep things simple, there's no data validation, so be careful when entering numbers. Here's the full source code for the RMI client.
import java.rmi.*;
import java.rmi.Naming;
import java.io.*;

//
//
// PowerServiceClient
//
//

public class PowerServiceClient
{
public static void main(String args[]) throws Exception
{
// Check for hostname argument
if (args.length != 1)
{
System.out.println
("Syntax - PowerServiceClient host");
System.exit(1);
}

// Assign security manager
if (System.getSecurityManager() == null)
{
System.setSecurityManager
(new RMISecurityManager());
}

// Call registry for PowerService
PowerService service = (PowerService) Naming.lookup
("rmi://" + args[0] + "/PowerService");

DataInputStream din = new
DataInputStream (System.in);

for (;;)
{
System.out.println
("1 - Calculate square");
System.out.println
("2 - Calculate power");
System.out.println
("3 - Exit"); System.out.println();
System.out.print ("Choice : ");

String line = din.readLine();
Integer choice = new Integer(line);

int value = choice.intValue();

switch (value)
{
case 1:
System.out.print ("Number : ");
line = din.readLine();System.out.println();
choice = new Integer (line);
value = choice.intValue();

// Call remote method
System.out.println
("Answer : " + service.square(value));

break;
case 2:
System.out.print ("Number : ");
line = din.readLine();
choice = new Integer (line);
value = choice.intValue();

System.out.print ("Power : ");
line = din.readLine();
choice = new Integer (line);
int power = choice.intValue();

// Call remote method
System.out.println
("Answer : " + service.power(value, power));

break;
case 3:
System.exit(0);
default :
System.out.println ("Invalid option");
break;
}
}
}

}

Running the client and server

Our example was extremely simple. More complex systems, however, might contain interfaces that change, or whose implementation changes. To run this article's examples, both the client and server will have a copy of the classfiles, but more advanced systems might share the code of the server on a webserver, for downloading as required. If your systems do this, don't forget to set the system property java.rmi.server.codebase to the webserver directory in which your classes are stored!
You can download all the source and class files together as a single ZIP file. Unpack the files into a directory, and then perform the following steps.
  1. Start the rmiregistry

    To start the registry, Windows users should do the following (assuming that your java\bin directory is in the current path):-
    start rmiregistry 
    To start the registry, Unix users should do the following:-
    rmiregistry &
  2. Compile the server

    Compile the server, and use the rmic tool to create stub files.
  3. Start the server

    From the directory in which the classes are located, type the following:-
    java PowerServiceServer
  4. Start the client

    You can run the client locally, or from a different machine. In either case, you'll need to specify the hostname of the machine where you are running the server. If you're running it locally, use localhost as the hostname.
    java PowerServiceClient localhost 
TIP - If you running the client or server with JDK1.2, then you'll need to change the security settings. You'll need to specify a security policy file (a sample is included with the source code and classes) when you run the client and server.The following changes should be made when running the server
java -Djava.security.policy=java.policy PowerServiceServer
The following changes should be made when running the client
java -Djava.security.policy=java.policy PowerServiceClient localhost

Summary

Java RMI is a useful mechanism for invoking methods of remote objects. Java RMI allows one Java Virtual Machine to invoke methods of another, and to share any Java object type, even if client or server has never come across that object type before.

Starting rmi registry

To start the registry, Windows users should do the following (assuming that your java\bin directory is in the current path):-
start rmiregistry 
To start the registry, Unix users should do the following:-
rmiregistry &

Varargs in Java: Variable argument method in Java 5

I think I am late for writing about varargs. The feature of variable argument has been added in Java 5 since its launch. Still I will write something about varargs.
varargs has been implemented in many languages such as C, C++ etc. These functionality enables to write methods/functions which takes variable length of arguments. For example the popular printf() method in C. We can call printf() method with multiple arguments.

1
2
printf("%s", 50);
printf("%d %s %s", 250, "Hello", "World");

 

Syntax

Varargs was added in Java 5 and the syntax includes three dots (also called ellipses). Following is the syntax of vararg method for method called testVar :

1
public void testVar(int count, String... vargs) { }
 
Notice the dots … in above code. That mark the last argument of the method as variable argument. Also the vararg must be the last argument in the method.
Now let us check simple hello world varargs code.
 
Example:
public class HelloWorldVarargs {

public static void main(String args[]) {
test(215, "India", "Delhi");
test(147, "United States", "New York", "California");
}

public static void test(int some, String... args) {
System.out.print("\n" + some);
for(String arg: args) {
System.out.print(", " + arg);
}
}
}




In above code, the test() method is taking variable arguments and is being called from main method with number of arguments.


So when should you use varargs?

As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called.

Tuesday, 1 March 2011

Assertions in java

Using assertions couldn't be easier. Anywhere you can put a statement in Java, you can now write
assert boolExpr;
where boolExpr is any Boolean expression. If the expression is true, execution continues as if nothing happened. If it's false, an exception is thrown. You can disable assertions at runtime if you wish, effectively removing them from your code.
Why Use Assertions?
Assertions are a cheap and easy way of building confidence in your code. When you write an assertion, you're enabling the machine to check your beliefs about your program. You write the assertion thinking that it's true, but as you well know, not all of your beliefs about your code are true - if they were, you wouldn't have any bugs. Assertions can help uncover bugs early on.
For example, here's a bit of code that makes a choice based on the remainder of dividing n by 3:
if (n % 3 == 0) {
S
} else if (n % 3 == 1) {
S
} else {
assert n % 3 == 2;
...
}

Now obviously, n % 3 == 2 in the final else of this statement, since the remainder when you divide a number by 3 is either 0, 1, or 2. So there's no need to do an explicit test. But these new assert statements are easy to write and you can always disable them, so you add one just for kicks. That will turn out to have been a wise choice when the code is run with a negative value of n. The Java % operator, like the mod operator of most programming languages, gives negative results when its left operand is negative: -5 % 3 is -2, not 2. The assertion will fail, the program will stop, and you can easily correct both the code and your false belief about how % works.
Here's another example from some recent code of my own:
TransactionEntry te = (TransactionEntry)
assoc.getEntry(key);
if (te == null) {
te = new TransactionEntry(key, dur);
assoc.put(key, te);
} else {
assert te.getState() == te.REMOVED;
te.recreate(dur, session);
}

What this code is about doesn't matter. As you can tell just from the control flow, I firmly believe that if assoc.- getEntry(key) returns a nonnull TransactionEntry, then that TransactionEntry must be in the REMOVED state. This is a desired property of my system and is enforced elsewhere (or so I believe), but is far from obvious in this piece of code. The assertion both documents my belief and confirms it at runtime, making me a little more confident that my system is correct.
The Details
Having seen why assertions are a good idea, let's look at Java's assertion facility in more detail.
The Java language has a new statement, the assert statement, which takes one of two forms. The simpler form is the one introduced earlier:
assert boolExpr;
If the expression evaluates to true, nothing happens, but if it evaluates to false, an AssertionError is thrown. The new class AssertionError is a subclass of Error.


There are a few situations where you should not use assertions:

  1. Do not use assertions for argument checking in public methods.
    Argument checking is typically part of the published specifications (or contract) of a method, and these specifications must be obeyed whether assertions are enabled or disabled. Another problem with using assertions for argument checking is that erroneous arguments should result in an appropriate runtime exception (such as IllegalArgumentException, IndexOutOfBoundsException, or NullPointerException). An assertion failure will not throw an appropriate exception.
  2. Do not use assertions to do any work that your application requires for correct operation.
    Because assertions may be disabled, programs MUST NOT assume that the boolean expression contained in an assertion will be evaluated. Violating this rule has dire consequences. For example, suppose you wanted to remove all of the null elements from a list names, and knew that the list contained one or more nulls. It would be wrong to do this:
    // Broken! - action is contained in assertion
    assert names.remove(null);
    The program would work fine when asserts were enabled, but would fail when they were disabled, as it would no longer remove the null elements from the list. The correct idiom is to perform the action before the assertion and then assert that the action succeeded:
    // Fixed - action precedes assertion
    boolean nullsRemoved = names.remove(null);
    assert nullsRemoved; // Runs whether or not asserts are enabled
    As a rule, the expressions contained in assertions should be free of side effects: evaluating the expression should not affect any state that is visible after the evaluation is complete. One exception to this rule is that assertions can modify state that is used only from within other assertions.
There are many situations where it is good to use assertions:

  1. Internal Invariants
    Before assertions were available, many programmers used comments to indicate their assumptions concerning a program's behavior. You should now use an assertion whenever you would have written a comment that asserts an invariant:
    if (i % 3 == 0) {
    ...
    } else {
    if (i % 3 == 1) {
    ...
    } else {
    assert i % 3 == 2 : i;
    ...
    }
    }
    Another good candidate for an assertion is a switch statement with no default case. The absence of a default case typically indicates that a programmer believes that one of the cases will always be executed. The assumption that a particular variable will have one of a small number of values is an invariant that should be checked with an assertion:
    default:
    assert false : suit;
    If the suit variable takes on another value and assertions are enabled, the assert will fail and an AssertionError will be thrown. An acceptable alternative is:
    default:
    throw new AssertionError(suit);
    This alternative offers protection even if assertions are disabled, but the extra protection adds no cost: the throw statement won't execute unless the program has failed. Moreover, the alternative is legal under some circumstances where the assert statement is not. If the enclosing method returns a value, each case in the switch statement contains a return statement, and no return statement follows the switch statement, then it would cause a syntax error to add a default case with an assertion. (The method would return without a value if no case matched and assertions were disabled.)
  2. Control-Flow Invariants
    Place an assertion at any location you assume will not be reached. The assertions statement to use is:
    assert false;        
    Code now reads:
    void foo() {
    for (...) {
    if (...) return;
    }
    assert false; // Execution should never reach this point!
    }
  3. Preconditions, Postconditions, and Class Invariants
    While the assert construct is not a full-blown design-by-contract facility, it can help support an informal design-by-contract style of programming.
    Do not use assertions to check the parameters of a public method. An assert is inappropriate because the method guarantees that it will always enforce the argument checks. It must check its arguments whether or not assertions are enabled. Further, the assert construct does not throw an exception of the specified type. It can throw only an AssertionError.
    You can, however, use an assertion to test a nonpublic method's precondition that you believe will be true no matter what a client does with the class.
    You can test postcondition with assertions in both public and nonpublic methods.
    A class invariants is a type of internal invariant that applies to every instance of a class at all times, except when an instance is in transition from one consistent state to another. A class invariant can specify the relationships among multiple attributes, and should be true before and after any method completes. For example, suppose you implement a balanced tree data structure of some sort. A class invariant might be that the tree is balanced and properly ordered.
    The assertion mechanism does not enforce any particular style for checking invariants. It is sometimes convenient, though, to combine the expressions that check required constraints into a single internal method that can be called by assertions. Continuing the balanced tree example, it might be appropriate to implement a private method that checked that the tree was indeed balanced as per the dictates of the data structure:
    // Returns true if this tree is properly balanced
    private boolean balanced() {
    ...
    }
    Because this method checks a constraint that should be true before and after any method completes, each public method and constructor should contain the following line immediately prior to its return:
    assert balanced(); 
    It is generally unnecessary to place similar checks at the head of each public method unless the data structure is implemented by native methods. In this case, it is possible that a memory corruption bug could corrupt a "native peer" data structure in between method invocations. A failure of the assertion at the head of such a method would indicate that such memory corruption had occurred. Similarly, it may be advisable to include class invariant checks at the heads of methods in classes whose state is modifiable by other classes.
In order for the javac compiler to accept code containing assertions, you must use the -source 1.4 command-line option as in this example:
javac -source 1.4 MyClass.java
This flag is necessary so as not to cause source compatibility problems. NOTE, in Java 5.0 the compiler accepts assertions BY DEFAULT:
javac MyClass.java     
In both Java 5.0, as in Java 1.4 assertions are disabled by default at runtime. You need explicitly to turn them on. At a runtime you can check if the program is running with enabled assertions using the following code:
boolean assertsEnabled = false;
assert assertsEnabled = true; // Intentional side-effect !!!
// Now 'assertsEnabled' is set to the correct value