Wednesday, July 13, 2011

life cycle of a message-driven bean.

The life cycle of a message-driven bean has two states, namely the ‘does not exist’ and ‘pooled’ state. A message-driven bean does not maintain any client specific state. It does not have the home and component interfaces. The following image shows the life cycle of a message-driven bean:

 

lifemdb

The container is responsible for maintaining the life cycle of a message-driven bean. A bean moves from the ‘does not exist’ to the ‘method ready’ state using the following methods:

  • The container creates a bean instance by calling the newInstance() method on a class.
  • The container assigns a context to the bean by invoking the setMessageDrivenContext() method.
  • The container calls the ejbCreate() method. The initialization code should be written in this method.

The bean instance in the pooled state can perform operations using the onMessage() method. The container ensures that only one thread executes at a particular moment. The message -driven beans connect to the JMS server, consume messages from the server, and process those messages.

The bean instance can be removed by the container by calling the ejbRemove() method. By calling this method, the container moves the bean instance back to the ‘does not exist’ state.

Creating Object using keyword “new” & method “newInstance()”

When u use the new operator to create an instance of a class, u cant change the class which is been instantiated. In other words, the class which is instantiated is determined at compile time.


If you use class.newInstance(), then u can change the class which is been instantiated at runtime. In other words for example

Class c = Class.forName("Some class Name");
Object o = c.newInstance();

Here, you can change the String argument in the class.forName() method and change the class which is getting instantiated. Say u got this String from a property file, then u don't even have to compile the class in order to get another different class instantiated.

   1:  package test;
   2:  class Emp {
   3:      String name;
   4:      public String getName() {
   5:          return name;
   6:      }
   7:      public void setName(String name) {
   8:          this.name = name;
   9:      }
  10:  }
  11:  public class Instance {
  12:      public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
  13:          Class c;
  14:          c = Class.forName("test.Emp");
  15:          Emp e = (Emp) c.newInstance();
  16:          Emp emp = Emp.class.newInstance();
  17:          e.setName("Ramesh");
  18:          emp.setName("Krishna");
  19:          System.out.println(e.getName());
  20:          System.out.println(emp.getName());
  21:      }
  22:  }

Wednesday, June 15, 2011

static block

Static block resembles a method with no name/arguments/return type. There is no need to refer to it from outside the class definition, therefore it doesn’t need a name. If it doesn’t have any name, who is executing this block? Simple :) This block is executed by the Java VM when the class is loaded.

Why Do I Need a Static Block

Static blocks are very useful if you consider doing things like below:

  • If you’re loading drivers and other items into the namespace. (for instanceClass.forName(”org.h2.Driver”))
  • Initialize your static members at once (most likely this would be singletons, etc)
  • Security related issues or logging related tasks
  • Some database operations like creating prepared SQL statements, etc
Execution Order

Java doesn’t limit you with one static block. So you may define more than one static block. JVM combines them together and then executes. Here you might think what about the order of all these statements? Since static code blocks could be separated by non-static code blocks, the execution might not be in the same order you see in the code. You must remember that JVM combines all these blocks into one single static block and then executes. Here are some notes from my understanding:

  • If you’re defining static variables/methods, JVM will execute these statements when they need.
  • If you have executable statements in the static block, JVM will automatically execute these statements when the class is loaded into JVM.
  • If you’re referring some static variables/methods from the static blocks, these statements will be executed after the class is loaded into JVM (same time as second).

 

   1:  package certify;
   2:   
   3:  public class StaticBlock {
   4:   
   5:      public static final String name = "Static Variable Name";
   6:   
   7:      {
   8:          System.out.println("Instance Initialization Block");
   9:      }
  10:      static {
  11:          System.out.println("Static Block 1");
  12:          show();
  13:      }
  14:      public StaticBlock() {
  15:          System.out.println("CONSTRUCTOR");
  16:      }
  17:      public static void show() {
  18:          System.out.println("Static Method");
  19:      }
  20:      public static void main(String[] args) {
  21:          System.out.println("MAIN");
  22:          new StaticBlock();
  23:          new StaticBlock();
  24:      }
  25:      static {
  26:          System.out.println("STATIC BLOCK 2");
  27:          System.out.println("Static Block Name = " + name);
  28:      }
  29:  }



Output


Static Block 1
Static Method
STATIC BLOCK 2
Static Block Name = Static Variable Name
MAIN
Instance Initialization Block
CONSTRUCTOR
Instance Initialization Block
CONSTRUCTOR


So what happened in above code? Let me try to explain. First of all, Java didn’t do anything before the class is loaded into JVM. After loading, JVM combined all the static blocks into one regardless of their position in the code, and started to execute each line. If line is executable JVM executed that line, otherwise it just kept the method/variable blocks on a special area in the memory. And when they are needed, JVM executed those statements too. If you double check, we have 2 static methods, one is show and the other is main. Show is executed as the first item since it is called within the static block. However, main is executed after all static initializations.


One thing you might notice is there is another block without static keyword. And it’s been executed twice. Yes, that block is not a static block. It is instance initialization block.


Limitations

Yes, we have couple limitations about static blocks:


  • You shouldn’t try to access super since there is no such a thing for static blocks
  • You cannot use this keyword since there is no instance :)
  • You cannot throw Checked Exceptions
  • And please don’t try to return anything from this block

Sunday, June 5, 2011

Java Network Launching Protocol (JNLP)

Programmers often speak of the Java Network Launching Protocol (JNLP) interchangeably with the term "Web Start". The JNLP protocol, defined with an XML schema, specifies how to launch Java Web Start applications. JNLP consists of a set of rules defining how exactly to implement the launching mechanism. JNLP files include information such as the location of the jar package file and the name of the main class for the application, in addition to any other parameters for the program. A properly configured browser passes JNLP files to a Java Runtime Environment (JRE) which in turn downloads the application onto the user's machine and starts executing it. The development of JNLP took place under the Java Community Process as JSR 56. It includes the original 1.0 release, the subsequent 1.5 maintenance release, and as of 2006[update], the pending 6.0 maintenance release. JNLP comes free of charge; developers need not pay a license fee in order to use it in programs.

Important Web Start features include the ability to automatically download and install a JRE in the case where the user does not have Java installed, and for programmers to specify which JRE version a given program needs in order to execute. The user does not have to remain connected to the Internet to execute the downloaded programs, because they execute from a locally-maintained cache. Updates of the software download from the Web become available when the user has a connection to the Internet, thus easing the burden of deployment.

Any computer user can use JNLP by simply installing a JNLP client (most commonly Java Web Start). The installation can occur automatically such that the end user sees the client launcher downloading and installing the Java application when first executed.

JNLP works in a similar fashion to how HTTP/HTML works for the web. For rendering a HTML webpage, after the user clicks on a weblink, the browser submits a URL to a webserver, which replies with an HTML file. The browser then requests the resources referred to by this file (images, css), and finally renders the page once it has received enough information. Page rendering usually starts before all resources have downloaded; some resources not critical to the layout of the page (such as images), can follow on afterwards — or on request if the "Load Images Automatically" browser-setting remains unset.

JNLP mirrors this process; in the same way that a Web browser renders a webpage, a JNLP client "renders" a Java app. After the user clicks on a weblink the browser submits a URL to a webserver, which replies with a JNLP file (instead of a HTML file) for the application. The JNLP client parses this file, requests the resources specified (jar files), waits for the retrieval of all required resources, and then launches the application. The JNLP file can list resources as "lazy", which informs the JNLP client that the application does not need those resources to start, but can retrieve them later on when/if the application requests them.

Tuesday, May 31, 2011

Db2 26 Byte Timestamp in Java

I was looking for the db2 Timestamp format for long days and finally got the solution
public static Object getCurrentTimeStamp(int returnType) {
long timeInMillis = System.currentTimeMillis();
long timeInNanos = System.nanoTime();
Timestamp timeStamp = new Timestamp(timeInMillis);
timeStamp.setNanos((int) (timeInNanos % 1000000000));
if (returnType == ReturnType.TIMESTAMP)
return timeStamp;
else {
String db2TimeStamp;
db2TimeStamp = timeStamp.toString().replace(' ', '-');
db2TimeStamp = db2TimeStamp.replace(':', '.');
System.out.println(db2TimeStamp.substring(0, 26));
return db2TimeStamp.substring(0, 26);
}
}

The time in millis does not represent the time in nanos. More precise it simply can't be. You're supposed to use Timestamp#setNanos() to set the real nanos.
java.sql.Timestamp constructor go like this:
public Timestamp(long time) {
super((time/1000)*1000);
nanos = (int)((time%1000) * 1000000);
if (nanos < 0) {
nanos = 1000000000 + nanos;     
super.setTime(((time/1000)-1)*1000);
}
}

It basically accepts time in millisecond and then extracts the last 3 digits and makes it nanos. So for a millisecond value of 1304135631 421, I'm getting Timestamp.getnanos() as 421000000. This is plain calculation (adding 6 zeroes at the end).

Saturday, May 14, 2011

Interfaces of EJB in Client Server



An EJB container is the heart of an EJB environment, in the same way an ORB is the heart of a CORBA environment. The container registers EJB objects for remote access, manages transactions between clients and EJB objects, provides access control over specific methods on the EJB, and manages the creation, pooling, and destruction of enterprise beans. The container also registers the home interface for each type of bean under a given name in a JNDI namespace, allowing remote clients to find the home interfaces and use them to create enterprise beans.
Once you provide the EJB container with the home and remote interfaces and the implementation class for your bean, along with a deployment descriptor, the container is responsible for generating the various classes that connect these components, as shown in Figure. The home and remote interfaces you provide are RMI Remote interfaces; the container generates both the client stubs and the server-side implementation for these interfaces. When a client looks up a bean's home interface through JNDI, it receives an instance of the home stub class. All methods invoked on this stub are remotely invoked, via RMI, on the corresponding home implementation object on the EJB server. Similarly, if the client creates or finds any beans through the home stub, the client receives remote object stubs, and methods invoked on the stubs are passed through RMI to corresponding implementation objects on the server. These remote objects are linked, through the EJB container, to a corresponding enterprise bean object, which is an instance of your bean-implementation class. Optionally, the EJB container may also generate a container-specific subclass of your bean implementation (e.g., if it wants to augment some of your bean methods to facilitate synchronization with the container).

Monday, May 9, 2011

My first post on Java

I am coming back to Java after 6 years. I am a software professional working on Mainframe 3270 screen coding CICS/Cobol program. I studied java, c, c++ and .net languages at college. In college, my nick name is Dennis Ritchie.. I am very much interested in object oriented languages, but I got job to work on mainframe environment.
Thanks to IBM who brings Java on mainframe - System z Application Assist Processor (zAAP) and Pershing who gives me an opportunity to work on this ..
What is zAPP?
zAAP, which runs asynchronously alongside general-purpose processors, is designed specifically to execute Java programming under the control of the IBM JVM and assist the general-purpose processors by executing the Java cycles. Utilizing zAAP, therefore, customers can expect to realize reduced demands and capacity requirements on their general-purpose processors, which can be better utilized by other, non-Java workloads.

First Post on Java