JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Java Security Packages using JCA/JCE

May 23, 2008 by Krishna Srinivasan Leave a Comment

In this tutorial, the author explains the cryptography-related concepts and packages in JDK,with code examples.Many of the concepts and technical terms thus learnt will be useful in understanding the Cryptography API in MFCalso.

There are three security-related packages in JDK1.4, as follows:

  1. JCA/JCE(Java Cryptography
    Architecture & JavaCryptography
    Extensions)
  2. JSSE( Java
    Secure-Sockets Extension).
  3. JAAS( Java Authentication &AuhorizationService)

also read:

  • Java EE Tutorials
  • Java EE 7 Tutorials
  • Java EE Interview Questions

Prior to JDK1.4, many of these packages were not available within the JDK and had to be separately installed and used. But, JDK1.4 has incorporated all these within JDK itself).

Understanding the terminology of these important packages requires that we havesome familiarity with the technical terms used inthe field of Network Security. We can begin by saying thatsecure communication ,should ensure the following.

  1. a)Integrity
  2. b)Confidentiality
  3. c)Authentication
  4. d)Non-repudiation

[There is also another requirement (ie) Authorization and it is more to protect resources and programs from users, than with communicating the data. JAAS deals with that].

These are all standard terms used in Security. Whena person, say, Sam,wants to send some information toTom, it must be ensured that the information thus sent, is not tampered with oraltered on the way. This is known as Data Integrity.

Secondly, the information is meant only for Tom and so no one else should be able to understand the message. This is known as Confidentiality. There should be some indication that the message came from Sam andthere should be some proof for that. This is Identification.Authentication,that the message came from Sam is provided byDigitalSignature.There should preferably be a trusted third party to vouchsafe for the identity and signature of Sam. This is achieved by Digital Certificate,which authenticates the signature of Sam. Besides these, sometimesit is equally important thatSam should not be able to say later that he did not send the message to Tom and the message was actually sent by someone else ,in his name. This isensuring Non-repudiation. This purpose also is served byDigital signature. We will now see step-by-step development of these concepts. Except ‘Authorization’, other things can be understood in the context ofeveryday exchange of information.

Confidentiality is achieved byusingCryptography techniques. For the sake of simple illustration, let us assume that Sam wants to send a message to Tom.( By convention, two persons Alice & Bob are chosen for illustration, because the original thesis made use of these names. Let us use Sam and Tom instead).Sam does not want his message to be understood by anybody else except Tom. So, he encrypts it. When Tom receives the encrypted message, he ‘decrypts‘ it, so that he can read the original message. The original message is known as ‘plaintext‘. After Encryption, it becomes ‘ciphertext’. The process of convertingtheciphertextinto the original plaintext is known as Decryption. A ‘key’is used for controllingEncryption and Decryption.

There are two types of key-based encryption algorithms, namely, Symmetric algorithm and Asymmetric Algorithm.

a) SymmetricAlgorithm:This algorithmuses the same key for encryption and decryption.This is also known as ‘Secret key’. In this scheme, when Sam wants to send a message to Tom, he encrypts the message by the mutually agreed secret-key and then sends the ciphertext to Tom. Tom uses the same secret key and decrypts the message and reads it.

Symmetric key system is faster than the Asymmetric system but the problem of agreeing on mutual secret keyand preserving the secrecy of thekey while communicating it over the network, led to the development ofAsymmetric key systems.

Some of the Symmetric key Algorithms are as follows: (Mostof them are implementedin JCA/JCE).

  • DES( Data-Encryption-Standard).. developed in 1970 and recommended by US government. Though it is not fool-proof, it is considered to be sufficiently safe and is in wide use. It has different modes of operation.
    1. Electronic Cook book ( ECB)
    2. Cipher Block Chaining ( CBC)
    3. Output Feedback Mode (OFB)
    4. Cipher Feedback Mode ( CFB)
  • TripleDES( also known as DESede). An improved and very safe method of DES.
  • IDEA (International Data Encryption Algorithm). This is used in PGP ( Pretty-Good-Privacymethod of secure Email).

    An important advantage of Secret-key algorithm is that a hardware-approach is possible. This results in very high speed encryption. The hardware implementation by a VLSI chip can be about 20 times faster than the corresponding software implementation!IDEA has been implemented in hardware.

  • Blowfish…This algorithm was designed by Bruce Schneier. It is not patented and he has placed the implementation in public domain.
  • v) There is also a method known as Password-Based Encryption(PBE). We will have a brief description of this method ,with code example,shortly. Ready-madeimplementations for many of these algorithms are available in SunJCA/JCE and the programmer just chooses the desired algorithm and uses it. No deep knowledge of the mathematical theory of the algorithms or how these algorithms are implemented ,is required .Such topics are highly mathematical and aredealt with inbooks on Cryptography .

b)Asymmetric Algorithms

This algorithm is also known as ‘Public Key’ algorithm. There are two keys in this scheme. One key is known as ‘public key’ and the other key is known as ‘private key’.(It should be noted that ‘secret key’ does not mean ‘private key’.)

The basic theory of Public key Cryptography was developed by two research workers at StanfordUniversityDiffie&Hellman in 1976. TheDH algorithm is known as Key-Agreement method. RSA algorithm is an implementation , named after the initials of the three academics who invented it. ( Rivest,Shamir & Adleman).RSA is the defacto standard.Another Asymmetric algorithm isDSA

( Digital Signature Algorithm). Yet another algorithm is known as ECC(Elliptic-Curve Cryptography). It is reputed to be very efficient and fast.[ However, SunJCA/JCE does not provide ready-made implementation for ECC.]

The public key and private key are known as ‘keypair’.The public key and private key are mathematically related in the sense that if a message is encrypted by using a particular public key, it can be decrypted by the corresponding private key and vice-versa(ie) the data can
also be encrypted by using a private key and can be decrypted by the corresponding public key, and not by any other public key.But
the problem is thatany person who knows Sam’s public keycan decrypt the message.So,RSA system uses public key of the recipient to encrypt the data.( But, the private key cannot be derived from public key.Similarly, the public key cannot be derived from private key).

RSA method is the most widely used scheme. When Sam wants to send a secret message to Tom, he should know the public key of Tom to begin with.( Just as we should know the mail-id of our friend first, if we want to send email to him). Samencrypts the message by using Tom’spublic keyand sends it to Tom.At the receiving end, Tom uses his (Tom’s)private key and decrypts the letter and reads it.The advantage of this scheme is that it ensures that only Tom will be able to read the message, as only his private-key can decrypt the message encrypted with his public key.A person’s private key need never be known to anyone else and there is no sharing the key with another person.Only the public key needs to be informed to others. ( like the difference in sharing our mail-id and sharing our password!).Thus key-administration problem is less.

DigitalSignature&MessageDigest

The Asymmetric system has another use as well. It can be used for creating the Digital Signature, to ensure that the message came from Sam.Though the message itself can be signed without creating a digest, the usual method is to sign the messagedigest,so that Integrity of
data also can be ensured.

A ‘Message Digest’ isa digital fingerprint.It isoften referred to simply as a digest ( summary) or hash. It is an one-way process ( ie) it is impossible to reconstruct the original from the hash.

MD5(MessageDigest-5) andSHA-1( Secure Hash Algorithm) are two examples of such Digesting algorithms.These two are provided in Sun security package.MD5 accepts some input and produces a 128-bit message digest.SHA-1 is more secure and produces a 160-bit
message digest.

When Sam wants to send a secure message, he passes the message through a MessageDigest engine. The result is a hash.

He then encrypts thehashby using Sam’sprivate key.( This encryption is done on the hash and not on the data). Thus we get the Digital Signature.

Finally, Sam encryptsthe original message usingTom’s Public key. After this, Sam sends the package to Tom.

At the receiving end, Tom uses his(Tom’s) private key to decrypt the message.By using Sam’s public key, hedecrypts the digital signature and so gets the originalhash( hash1).Using the same oneway hash algorithm on the text message,Tom creates another hash( hash2).If hash2exactly matches hash1, it means that the data has not been altered in transit. Thus, we get assurance of Confidentiality and DataIntegrity.It also ensures the identity of the sender,because the the hash1 was obtained by using the public key of Sam to decrypt the package.

If the public key of Sam, used by Tom, has the added assurance from a certificate authority that it really belongs to Sam,this is aclear-cut method with no problems except that it is not suitable if the message being encrypted is of large size. Besides satisfying the requirements of Authentication, Confidentiality, Integrity and Non-Repudiation, we should also ensure that the process is fast, in Enterprise level. The method outlined above is slow and so may not be suitable for large messages.Otherwise, it is a satisfactory method.

(We will describe a hybrid method used for large messages, shortly).

Sometimes, it may be enough if there is Authentication and Non-Repudiation,without confidentiality. In such cases, it is enough if Sam sends the message-digest encrypted by Sam’s privatekey ,along with the plaintext.

Digital Certificate

Just now , we saw that Tommade use of Sam’s public key to verify his Digital Signature. How does Tom getto know the public key of Sam?Sam could have published his public key in the internet or could have sent it to Tom, personally. A person’s public key can be freely published and shared and for this reason, anybody can use it , not necessarily Sam. A Digital signature of Sam can be verified only if Sam’s public key is available to Tombut as it is a public key, impersonation is possible. A trusted third-party is required to certify that the said key is really Sam’s public key.This is known as Digital Certificate and the authorities who issue such certifictes are Certifying Authority.

Public Key Infrastructure( PKI)

When Sam wants his public key to be certified by a CA, he generates a keypair and sends the public key to an appropriate CAwith some proof of his identification. The CA checks the identification and then after satisfying that the key has not been modified in transit, issues a certificate relating the public key of Sam with his identity,by signing the public key of Sam with the private key of the CA. The standard formatof issuing the certificate is known as X509.

Who is to attest the CA themselves? The CAare self-attested.

The PKI standard has been developed by RSA Security Systems in collaboration with Industry leaders like SUN, IBM and Microsoft and is the industry standard.

Certficate-Revocation

Acertificate becomes invalid after the expiry of validation period. Sometimes, the private key associated with a public key gets compromised ( ie) exposed, and in that case also, the cerificate should be withdrawn( revoked).The owner of the privatekey also may like to change it.The CA publishes a list of such defunct certificates and Tom should verify that Sam’scertificate is still valid, before important transactions.

Message-Authentication-Code ( MAC)

Digital Signature makes use of Sam’s private key to sign the hash. An alternative to Digital Signature is to use a secret key to encrypt the hash. By its very definition, secret key is common to both Sam & Tom. So Tom can use the secret key at his end and get back the hash.
The code thus generated by mixing the hash and the secret key is known as MAC. Digital Signature is better than MAC because it does not need any ‘secret’ key. In the context of E-Commerce, where there are thousands of parties , secret key administration is always very difficult.

The scheme outlined above is suitable for most purposes. However, for very large amounts of data, encryption and decryption of databy public-key systems becomestime consuming and requires large resources.

In such cases, it is preferred to use Symmetric Encryption systems with some modifications. Hybrid Systems make use ofAsymmetric method for agreeing upon a secret key and the actual encryption and decryption of data is done by this secretkey.Some such methodis the usual Industrial practice. The Secret keyused here is valid only for a particular instance of transmission of message and so is usually called ‘session-key’. ( This is not the ‘session’ as usually understood in servlets, because this is an one-time operation).

Digital Envelope

An illustration of Hybrid method is a Digital Envelope. In this scheme, Sam encrypts the message by a random Secret key, ( known as DEK i.e.Data-Encryption-keyor session key).Next Sam encrypts this session key with Tom’s public key. At this stage, Sam sends both the encrypted message and the encrypted session key to Tom.

At the receiving end, Tom uses his private key to get the session key. Using this session key, Tom decrypts the message.As Symmetric method is about 1000 times faster thanAsymmetric method , this is a good combination. Though public key method also has been used here, it is only for encrypting the session key and not the message.This can be further improved by creating a hash of the message and sigining it. Also, there is no permanent Secret key betweenSam & Tom,and the required secret key is produced just as required and then discarded after the job. Thus, the method is fast and secure.

With this background information, let us now see some simple code examples,specific to JDK.

There are a number ofCryptographic Engines in SunJCA & SunJCE. They are listed below. It will be immediately evident that the names will beGreek & Latin to us , unless we have a background in Crypto terminology. That is why, a broad outline was given. The function of some of the engines will be evident from the earlier discussion. A few more of the remaining items will be clear when we deal with code examples.

Cryptographic Engines

  1. KeyGenerator( symmetric) (Blowfish, DES,TripleDES,HmacMD5, HmacSHA1,RC5)
  2. KeyPairGenerator( asymmetric) (DiffieHellman, DSA, RSA)
  3. Mac ( message authentication code) HmacMD5, HmacSHA1)
  4. MessageDigest (MD5,SHA1)
  5. Signature (MD5withRSA, SHA1withRSA, SHA1withDSA)
  6. Cipher ( Blowfish, DES, TripleDES etc)
  7. CertificateFactory ( X509)
  8. KeyAgreement( DiffieHellman)
  9. KeyFactory
  10. SecretKeyFactory
  11. SecureRandom ( SHA1PRNG) (ie) ( SHA1 ..pseudo-random-number-generator)
  12. TrustManagerFactory
  13. KeyManagerFactory
  14. KeySore ( JKS, PHCS12)
  15. SSLContext
  16. AlgorithmParameterGenerator
  17. AlgorithmParameters

Let us now see a series of code-examples to get familiarity with some of the above engines. For all the examples, we are using JDK1.4.2. Our working directory is
[code]
g:securitydemos.

cd to g:securitydemos

We should set <b>path </b>as :

c:windowscommand;d:<b>jdk1.4.2</b>bin
[/code]
The easiest to understand is the MessageDigest. demo1.java”creates the messagedigest of the string s1, by SHA method(Secure Hash Algorithm) . The given string is first converted into a byte array, because the function md.digest(), accepts only a bytearray.md.update() simply adds the array to existing arrays,if any. The digest object thus created is simply saved as object to the file.
[code lang=”java”]
*******************************************

// demo1.java

//
creation of message-digest

//
storing the string &amp; digest in file

importjava.io.*;[/code]

Filed Under: Java EE Tagged With: JCA, JCE

Java Messaging Service(JMS)

May 22, 2008 by Krishna Srinivasan Leave a Comment

Distributed Object Technologies like RMI, CORBA and DCOM areadvanced variants of RPC(Remote-Procedure-Call).EJB( SessionBeans % Entity Beans)is essentially built on the RMI-IIOP model,( a combination of RMI with CORBA style). All these systems are Synchronous in nature. (ie) the client invokes a method on the remote object and if for some reason , there isdelay in response from the server end, the line getsblocked.This is sometimes referred to as ‘Tight Coupling’.In Enterprise level computing, especially, B2B(Business to Business) a number of applications are integrated together.Ifeither one of the applications crashes or if we want to add/remove a section from this integrated scheme,it leads to a mess. This is what led to the development of Messaging systems. Such systems are based on Asynchronous processing. (ie) aprogramsendsamessage to another program but does not wait for response. This ensures that there is no ‘blocking’.

also read:

  • Java EE Tutorials
  • Java EE 7 Tutorials
  • Java EE Interview Questions

Fundamentally, the idea is similar to ’email’.Such systems are said to be ‘loosely coupled’ systems. Wherever there are huge number of players , loose coupling is beneficial. For this reason, the Enterprise world isnowadaysveering round to the Messaging protocol . It is in response to this shift in requirements, that Sun addedthe JMS ( Java Messaging System) API andthenMessage-driven bean as a third type of EJBean in addition to Session Bean & Entity bean. .

A number ofsuch Messaging Systems had been developed by Enterprise-world majors.These are known as ‘Message-oriented-Middleware’. (MOM).Also known as JMS-Provider.

A list of such MOM products is given below.

  1. WebLogicfrom BEA
  2. MQSeriesfromIBM
  3. JBossMQfrom JBoss
  4. SoniqMQfrom Progres (David Chappel’s company)
  5. FiaranoMQfrom Fiarano
  6. MSMQfrom Microsoft

JMS is not a messaging system by itself. It is an abstraction of the underlying principles ofthe major Messaging systems in industry. This enables the programmer to write code as if there is just one generic MOM system..( Microsoftdoes not follow JMS).

There are two types of messaging:

a) Publish&Subscribe

b) PointtoPoint

In Publish & Subscribe method, the sender sends the message toJMS-Provider.. The JMS-Provider broadcasts the message. The message will be received by any ‘listener ‘who’ tunes’himself to the broadcast by registering himself as a listener. In such a method ,the message is known as a ‘Topic’.The sender is known as ‘publisher’ and the receiver is known as ‘subscriber‘.This is sometimes referred to as ‘one to many’.

In the Point to Point method, the ‘Sender‘ sends the message as before to the MOM server. These message are meant for a specific ‘Receiver‘.Such a message is known as a ‘Queue’. The listener registers himself with the JMS-Provider for a particular message and as soon as a message arrives at the provider,it is sent to the listener.This method is referred to as ‘one to one’.

For writing messaging programs, we need to import jms package. ( This is available in weblogic by default.). Thecodingconcepts are almost identical for Topics and Queues. So we will illustrate the steps forTopic method only.

steps for ‘publishdemo’ program.

  1.  connecttothe JMS PROVIDER.
  2.  locateTopicConnectionFactory
  3. create aTopicConnection
  4.  create aTopicSession
  5. locate theTopic
  6. create aTopicPublisher
  7.  create aTextMessage or other types of message.
  8.  start the connection
  9. publish the message

The ‘publishdemo’programthussends the message toaJMS-Provider(ie) WebLogic.,for publication.

A separate ‘subscribedemo’ programconnects to the sameJMS-Provider, and follows a similar procedure,but this time as a recipient of message.

  1. connect to theJMS PROVIDER.
  2.  locateTopicConnectionFactory
  3.  create aTopicConnection from the above factory
  4. create aTopicSession
  5. locate theTopic
  6. create aTopicSubscriber
  7.  Register the subscriber as a messageListener
  8. Wait to get message from JMS
  9.  Get the message as and when sent by the sender.

This time , we will create our programs as ‘stand-alone’ frames .There are no fancy items in the GUI (Graphical User Interface). TheGUI for the ‘publishdemo”program has just a textfield and a button to ‘send’ the message.Another button is provided for ‘exit’.

Similarly, the GUI for the ‘subscribedemo’ program has justatextarea .

We start the ‘subscribedemo’ program first. ( to start listening!). Then we start the ‘publishdemo’ program . We type some message in text1of’ publishdemo’ window and click the ‘send’ button. The message goes to the JMS-Provider and it broadcasts the message to all registered listeners. So our ‘subscribedemo’ programgets the message and it is displayed in textarea. We can close the sender and restart . The client side is not affected. You will remember that in socket method , if you close the sender, the client will quit because it was synchronous.

Just to make it interesting, we start another receiver program in a separate window. We will find that this client also gets the message.Withall this description, it should not be difficult to follow the coding.

If we want to make use of QUEUE, the steps are almost identical.

  1. connect toJMS-Provider
  2. locateQueueConnectionFactory
  3. createQueueConnection
  4. createQueueSession
  5. locateQueue
  6. createaQueueSender
  7.  create the message
  8. send the message.

Similar steps for the QueueReceiver. The following demo illustrates a Publish-Subscribemodel.

You will find reference to ‘ourfactory’& ‘ourtopic’in the code. These are known as ‘Administered objects’. (ie) we set up these names in the relevant section of the Weblogic.propertiesfile. How it is done has been explained below.

//***************publishdemo.java**************************

[code lang=”java”]

import javax.ejb.*;

import javax.jms.*;

import javax.naming.*;

import java.rmi.*;

import java.util.*;

import java.awt.*;

public class publishdemoextends Frame

{

TextFieldtext1;

Buttonbutton1;

Buttonbutton2;

TopicPublisher
publisher;

TextMessagetm;

public
static void main(String args[])

{

publishdemoapp=new publishdemo();

app.resize(300,200);

app.show();

}

public
publishdemo()

{

setLayout(new FlowLayout());

setBackground(Color.red);

text1=new TextField(40);

button1=new Button("send");

button2=new Button("Exit");

add(text1);

add(button1);

add(button2);

System.out.println("Please wait");// diagnostic

Propertiesprops=new Properties();

props.put(Context.INITIAL_CONTEXT_FACTORY,

"weblogic.jndi.WLInitialContextFactory");

props.put(Context.PROVIDER_URL,

"t3://127.0.0.1:7001");

Contextcontext=new InitialContext(props);

System.out.println("context ok");

//——————————————————–

TopicConnectionFactoryfactory=

(TopicConnectionFactory)context.lookup("ourfactory");

TopicConnectionconnection=

factory.createTopicConnection();

TopicSessionsession=

connection.createTopicSession

(false,Session.AUTO_ACKNOWLEDGE);

Topictopic=

(Topic)context.lookup("ourtopic");

publisher=session.createPublisher(topic);

tm=session.createTextMessage();

}catch(Exception e1){System.out.println(""+e1);}

}

public
boolean action(Event e,Object c)

{

if(e.target==button1)

{

try

{

String text=text1.getText();

tm.setText(text);

publisher.publish(tm);

System.out.println("message published");

}catch(Exception e1){System.out.println(""+e1); }

}

if(e.target==button2)

{

System.exit(0);

}

return
true;

}

}

============================================================================

//subscribedemo.java

import javax.ejb.*;

import javax.jms.*;

import javax.naming.*;

import java.rmi.*;

import java.util.*;

import java.awt.*;

public class subscribedemoextends FrameimplementsMessageListener

{

TextAreaarea1;

public
static void main(String args[])

{

subscribedemoapp = new
subscribedemo();

app.resize(300,300);

app.show();

}

publicsubscribedemo()

{

setBackground(Color.orange);

setLayout(new FlowLayout());

area1 =
new TextArea(10,30);

add(area1);

try

{

area1.append("please waitn");

Properties
props=new Properties();

props.put(Context.INITIAL_CONTEXT_FACTORY,

"weblogic.jndi.WLInitialContextFactory");

props.put(Context.PROVIDER_URL,

"t3://127.0.0.1:7001");

Context
context=new InitialContext(props);

area1.append("context
readyn");

//——————————————————–

TopicConnectionFactoryfactory=

(TopicConnectionFactory)context.lookup("ourfactory");

TopicConnectionconnection=

factory.createTopicConnection();

TopicSessionsession=

connection.createTopicSession

(false,Session.AUTO_ACKNOWLEDGE);

Topictopic=

(Topic)context.lookup("ourtopic");

TopicSubscribersubscriber=

session.createSubscriber(topic);

subscriber.setMessageListener(this);

area1.append("starting connectionn");

connection.start();

area1.append("connection startedn");

area1.append("waiting for messagen");

area1.append("——————–n");

}catch(Exception e){area1.setText(""+e);}

}

public
void onMessage(Message msg)

{

try

{

TextMessage tm=(TextMessage)msg;

String
s=tm.getText();

area1.append(s+"n");

}catch(Exception
e){area1.setText(""+e);}

}

}
[/code]

How shall we test this program?

This program is not connected with EJB but is preliminary to the study of Message-Driven Bean to be takenup shortly.So far, all our examples are being run with Weblogic 5.1. It can be run on Windows-98.

Message-Driven bean is based on EJB2.0 specification and requires Weblogic7.0 . which needs Windows 2000 for proper functioning.

We will now test our JMS program in Weblogic 5.1 installed in Windows- 98.

[code]

Create a folderas:c:jmsdemo

cd toc:jmsdemo

> SETJAVA_HOME=C:JDK1.3

>SETWL_HOME=C:WEBLOGIC

> set path=c:windowscommand;
c:jdk1.3bin;c:weblogicbin

> set classpath=c:jmsdemo;c:weblogicclasses;c:weblogiclibweblogicaux.jar

[/code]

Edit publishdemo.java and subscribedemo.java in c:jmsdemofolder.

[code]

…..jmsdemo
>javac*.java//compile

[/code]

Edit c:weblogicweblogic.properties file as follows:

You will find a section named ‘Weblogic JMS DEMOPROPERTIES’. ADD THE FOLLOWING LINES

[code]

weblogic.jms.connectionFactoryName.ourfactory=ourfactory

weblogic.jms.topic.ourtopic=ourtopic

[/code]

From the ‘start’ menu,rememberto start the weblogic server as before. Minimize the window. Run the subscriber program first.

[code]….jmsdemo >javasubscribedemo[/code]

You will geta window withjust a textarea. The area will display :

[code]

connection started

waiting for message[/code]

Now go to another dos prompt and set path, classpath etc as before. Start the publishdemo program

[code]

….jmsdemo><b>javapublishdemo[/code]

Filed Under: Java EE Tagged With: JMS

JSTL and SQL-TAGS

May 22, 2008 by Krishna Srinivasan Leave a Comment

The Struts community has ordained that JSP should bestrictly a ‘view-technology’, in the Model-View-Controller Architecture. According to Struts philosophy, JSP should not deal with Data-Accesss and such data accessshould be done by ‘Model’ components only.( read ‘beans’). JSTL , however, provides for sql tags, inspired by ColdFusion! ( please see a very short tutorial on DB-Operations using ColdFusion’ available in this issue as a separate lesson. and compare JSTL code and CF code!).And , a few months back, the editor of ‘Java Lobby’ magazine was all admiration for the absolutely nice features of these sql tags, whatever, ‘struts-fans’ may say! Just as EJB may be ‘overkill’, except for really big Enterprise applications, Struts also may bean unnecessary complication for small and medium level projects. In such cases, it is much more direct to provide for data access by the JSP itself, but using JSTL ‘sql’ tags.We take up these ‘sql’ tags inthis part of the tutorial.

also read:

  • Java EE Tutorials
  • Java EE 7 Tutorials
  • Java EE Interview Questions

Let us begin with ‘sql.htm’. It just provides a simple form with just a textarea & submit button. Normally, queries by MIS department will be very complex and so we have provided a textarea for the ‘select’ query.After filling up the query, itis submitted and the corresponding query.jsp is invoked.

query.htm

[code lang=”html”]
<html>
<body>
<formmethod=postaction="query.jsp">
<textareaname=’area1′
rows=10cols=30>
</textarea>
<inputtype=submit>
</form>
</body>
</html>
[/code]

query.jsp is given below. In the standard jdbccode,we begin by asking for the availability of the driver. “jdbc.odbc.JdbcOdbcDriver”. And then, we specify the URL of the database as ‘jdbc:odbc:telephone’.

Similarly, in JSTL also, we begin with < sql:setDataSource tag. It has attributes for ‘driver’ and ‘url’. We will refer to the database as ‘db’.

The next step is to collect the query typed in area1 by the user.

[code lang=”html”]
<c:setvar="s"value="${param.area1}"/>[/code]

is used for this purpose.We also check up whether the query typed by the user has indeed been correctly received. 

[code lang=”html”]<c:outvalue="${s}"/>[/code]

Next, the ‘<sql:query’tag, takes three attributes., such as, symbolic name:

var=”query1″

datasource=”${db}

sql=”${s}

The query result is then displayed in table form.It should be possible to follow the code now.In our example, we are having an Access db,

with table1, having two fields, (name, place). registered with ODBC.

query.jsp

[code lang=”html”]
<%@taglibprefix="c" %>uri="http://java.sun.com/jstl/core"
<%@taglibprefix="sql"
Consolas, Monaco, monospace;">%>
Consolas, Monaco, monospace;">uri="http://java.sun.com/jstl/sql"
<html>
<body>
<sql:setDataSourcevar="db"
driver="sun.jdbc.odbc.JdbcOdbcDriver"
url="jdbc:odbc:dbdemo"/>
<c:setvar=’s’value="${param.area1}"/>
<c:outvalue="${s}"/><br>
<sql:queryvar="query1"
dataSource="${db}"
sql="${s}"/>
Consolas, Monaco, monospace;"></sql:query>
<table border="1">
<c:forEachvar="row"items="${query1.rows}" >
<tr>
Consolas, Monaco, monospace;"><td> <c:out value="${row.name}"
Consolas, Monaco, monospace;">/></td>
<td> <c:out value="${row.place}"
Consolas, Monaco, monospace;">/></td>
</tr>
Consolas, Monaco, monospace;"></c:forEach>
</table>
</body>
</html>
[/code]

In the second example,(dbeditor.htm & dbeditor.jsp) we provide a combo, with options such as: add, modify, remove and verify. In JSTL , we have a separate sql tag known as ‘<sql:update’for ‘add’, ‘modify’ and ‘remove’ operations. When we want to verify, we must use’ <sql:query’tag, because, resultset will be returned.

dbeditor.htm

[code lang=”html”]
<html>
<body>
<form>method=post action="dbeditor.jsp">
<input>type=text name=’text1′>name<br>
<input>type=text name=’text2′>number<br>
<input>type=text name=’text3′> criterion<br>
<select>name=combo1>
<option value="add">add
<option>value="delete">delete
<option>value="modify">modify
<option value="verify">find
</select>
<br>
<input>type=submit>
</body>
</html>
[/code]

dbeditor.jsp

[code lang=”html”]
<%@taglibprefix="c" uri="http://java.sun.com/jstl/core"%>
<%@taglibprefix="c" uri="http://java.sun.com/jstl/sql"%>
<html>
<body>
<sql:setDataSourcevar="db"
driver="sun.jdbc.odbc.JdbcOdbcDriver"
url="jdbc:odbc:dbdemo"/>
<c:setvar=’a’value=’${param.text1}’/>
<c:setvar=’b’value=’${param.text2}’ />
<c:setvar=’c’value=’${param.text3}’ />
<c:setvar=’d’value=’${param.combo1}’ />
———————————————-
<c:iftest="${d == ‘add’}">
<sql:updatevar="query1"dataSource="${db}"
sql="insertinto table1 values${a}’,’${b}’)" >
</sql:update>
<c:outvalue="record added"/>
</c:if>
———————————————
<c:iftest="${d == ‘delete’}">
<sql:updatevar="query1"dataSource="${db}"
sql="deletefrom table1 where name= ‘${a}’ " >
</sql:update>
<c:outvalue="record deleted"/>
</c:if>
——————————————-
<c:iftest="${d == ‘modify’}" >
<sql:updatevar="query1"dataSource="${db}"
sql="updatetable1 set table1.name=’${a}’,
table1.place=’${b}’ where
table1.name=’${c}’" >
<–sqlshould be typed in a single line–>
</sql:update>
<c:outvalue="record modified"/>
</c:if>
——————————————
<c:iftest="${d == ‘verify’}" >
<sql:queryvar="query1"dataSource="${db}"
sql="select* from table1 where name=’${a}’" >
</sql:query>
<tableborder="1">
<c:forEachvar="row"tems="${query1.rows}" >
<c:setvar="n" value="OK" />
<tr>
<td> <c:out value="${row.name}"/></td>
<td> <c:out value="${row.place}"/></td>
</tr>
</c:forEach>
<c:iftest="${n != ‘OK’}" >
<c:outvalue="No such Records" />
</c:if>
</table>
</c:if>
</html>
<body>
[/code]

These are ,afterall, the essentials. All else, are only, ornamental. Thus, it will be seen that the JCP has done a great job in creating really fine
standard tags, for simplifying routine tasks. But, Java coders, have to take note that , their job as JSP coders, will be slowly erodedby page-authors using JSTL!

Suggested Reference Books

  • ProJSP by SIMON BROWN & OTHERS (A-Press) (Excellent material)
  • JavaServer Pages by Hans Bergsten ( Third Edition) (O’Reilly Press/SPD)
  • EARLY ADOPTER JSP Standard Tag Library by JAYSON FALKNER & OTHERS
    Wrox Press
  • JSTL in Action by SHAWN BAYERN (Manning/ DreamTech).

Filed Under: Java EE Tagged With: JSTL

JSTL and XML-TAGS

May 22, 2008 by Krishna Srinivasan Leave a Comment

No one can have any second opinion about the elegance of xml tags in JSTL. If the readers have been following the earlier installments of this J2EE series of tutorials, they would have come across JAXP,DOM,SAX ,JDOM and such terms, and it mayhave been none too easy to learn. But the xml tags in JSTL , make XML processing and even Transformation , a cinch! And ,we now proceed to study them.

also read:

  • Java EE Tutorials
  • Java EE 7 Tutorials
  • Java EE Interview Questions

Making our studyeven easier, many of the xml tags in JSTL , are very much similar to the ‘core’ tags. For example, just like <c:out>, we have <x:out>.

Similarly, <x:forEach>, <x:if>,<x:when>etc. So, if we have understood the syntax of the ‘core’; tags, it will not be difficult to use the ‘xml’ tags. All the followingexamples use the books.xmlfile.It contains ‘elements’ like ‘title’ and ‘author’.

———————————————–

books.xml

[code lang=”html”]
<?xml version="1.0" ?>

<books>

<book>

<title>cobol</title>

<author>roy</author>

</book>

<book>

<title>java</title>

<author>herbert</author>

</book>

<book>

<title>c++</title>

<author>robert</author>

</book>

<book>

<title>coldfusion</title>

<author>allaire</author>

</book>

<book>

<title>xml
unleashed</title>

<author>morrison</author>

</book>

<book>

<title>jrun</title>

<author>allaire</author>

</book>

</books>
[/code]

demo1

The following program reads the xml file using ‘forEach’ tag and displays the title and author ofeach book. The syntax:

<x:forEachvar=”n” select=”$doc/books/book”>

is used to select the elements from the xml file.

<x:outselect=”$n/title”/>

is used to print the elements of the xml file. We begin byimporting the reference to the XML file to be parsed.

<c:importurl=”books.xml”var=”url” />

We have given a symbolic name for this file as ‘url’.Next we askthe program to parse this XML file.The resulting tree is given a symbolic name as ‘doc’.

<x:parsexml=”${url}”var=”doc”/>

In the next step, we direct the program to select each title and each author in the XPATH expression$doc/books/book.

If we refer to the xml file , we find that the root element of the document is ‘books’. Inside this, we have ‘book’.So, XPATH can be thought of as just a file hierarchy. Just like <c:out, we have <x:out!

demo1.jsp

[code lang=”html”]
<%@

page contentType="text/html" %>

<%@taglibprefix="c"
uri="http://java.sun.com/jstl/core" %>

<%@taglibprefix="c"
>uri="http://java.sun.com/jstl/xml"%>

<html>

<body>

<c:importurl="books.xml"var="url" />

<x:parsexml="${url}"var="doc"/>

———————————————–

<x:forEachvar="n"

select="$doc/books/book">

<x:outselect="$n/title"/>

<x:outselect="$n/author"/>

========

</x:forEach>

</body>

</html>
[/code]

Magically, we have parsed a given XML document and extracted information, without any mention about DOM,SAX and suchwords., atall!Wonderful!As a famous author would say, ‘anything that makes my job easier, I like!’. When we executethe ‘program’, we get the following result.

(Result for executing demo1.jsp)

[code]
==========================

cobol
roy

==========

java
herbert

==========

c++
robert

==========
coldfusion
allaire

==========
xmlunleashed
morrison

==========
jrun
allaire

==========

[/code]

The following program (demo2)displays the books and authors of xml filein table format.

demo2.jsp

[code lang=”html”]
<%@
page contentType="text/html" %>

<%@taglibprefix="c" uri="http://java.sun.com/jstl/core" %>

<%@taglibprefix="c" >uri="http://java.sun.com/jstl/xml"%>

<html>

<body>

<c:importurl="books.xml"var="url" />

<x:parsexml="${url}"var="doc"
/>

<tableborder=1>

<th>

<tr>

<td>title</td>

<td>author</td>

</tr>

</th>

<x:forEachvar="n"

select="$doc/books/book">

<td>

<tr>
<x:outselect="$n/title"/></tr>

<tr>
<x:outselect="$n/author"/></tr>

</td>

</x:forEach>

</table>

</body>

</html>
[/code]

title

author

cobol

roy

java

herbert

c++

robert

coldfusion

allaire

xml
unleashed

morrison

jrun

allaire

demo3 deals with the selection of particular book’s authorfrom the xml file ,when we give the title, with the help of <x:if> action tag.The title is choosen from combo box in demo2.htm file and submitted.We get a display of the selected title and its author. Think of this as ansql query like

[code]
"select * from table1 where title=’jrun’"

[/code]

demo3.htm

[code lang=”html”]
<html>

<body>

SELECT THE TITLE.<BR>

YOU WILL GETTITLE &amp; AUTHOR.

<form method=postaction="demo3.jsp">

<select
name="combo1">

<option value="xml
unleashed">xml

<option value="c++">c++

<option value="coldfusion">cold
fusion

<option value="java">java

<optionvalue="cobol">cobol

</select>

<input
type=submit>

</form>

</body>

</html>
[/code]

—————————

demo3.jsp

[code lang=”html”]
<%@
page contentType="text/html" %>

<%@taglibprefix="c" uri="http://java.sun.com/jstl/core"%>

<%@taglibprefix="c"
uri="http://java.sun.com/jstl/xml"%>

<html>

<body>

<c:importurl="books.xml"var="url" />

<x:parsexml="${url}"var="doc"/>

<c:setvar="s"

value="${param.combo1}"/>

——

<x:forEachvar="n"
select="$doc/books/book" >

<x:ifselect="$n/title=$s"
>

<x:outselect="$n/title"/>

<br>

<x:outselect="$n/author"/>

<br>

</x:if>

</x:forEach>

</body>

</html>
[/code]

demo4 is a simple variation on the same theme. In this case, the user selects the author name from the combo and any books by that author are displayed, due to the code. It will be noted that ‘allaire’ has two books to his credit and so if we choose ‘allaire’ in the combo,his two books are displayed.If ‘haris’ is chosen, we should display the message that it is yet to be published as there is no such entry in the xml file. But there is no ‘if-else’ construct and so we improvise. We have created a variable ‘a’ and assigned the value ‘ok’ to it. If there is no author to match the user’s selection, the conditional block is ignored and’a’ will not be ‘ok’.

From this, we conclude that ‘the book is not ready’.

demo4.htm

[code lang=”html”]
<html>

<body>

<b>Select name of author &amp; view his books</b><br>

<form
method=post action="demo4.jsp">

<select
name="combo1">

<option value="morrison">morrison

<option value="robert">robert

<option value="allaire">allaire

<option value="herbert">herbert

<p class="MsoNormal" style="margin-right: 4.5pt;[/code]

Filed Under: Java EE Tagged With: JSTL

An Introduction to JSTL

May 22, 2008 by Krishna Srinivasan Leave a Comment

AsJ2EE programmers, we are familiar with Servlets , JSPand JavaBeans.Any JSP page should encapsulate the business logic in a bean and invoke it by using <jsp:useBean>tag.Till recently, a combination of Servlets, JSP and beans was the standard practice. But, the JCP realeased an API for enabling programmers to create custom tags and use them in their JSP pages. The difference between javabean and java custom tags was that, though both made use of java classes,tags can be used by non-programmers also withoutknowledge of Java programming, just as they would use html tags.( From a programmer’s perspective,however, a much more important distinction is that tags are specific to the page in which they are created while javabeans are general. )

also read:

  • Java EE Tutorials
  • Java EE 7 Tutorials
  • Java EE Interview Questions

Back in 1998, a Web-Server Technology , known as ColdFusion , created by Allaire of Allaire Corporation, was very much in demand!. It was a purely tag-based language, using which page-authors can turn into programmers overnight. The tags were so powerful and simple to use! There is a separate lesson on using ColdFusion for typical web-based database opeartions, elsewhere in this edition, just to indicate the source of inspiration of the tag library idea, of the JSTL. To this day, ColdFusion is unbeatable, in its power,speed, ease of use and productivity. However, among the various web-server technologies ( namely ASP, Servlets, JSP,Perl,PHP , ColdFusion & ASP.net), CF is the only technology that is not free!And perhaps for this reason, it is no longer popular in Indian environment, though it is said to be very much in vogue still, in US!
MacroMedia of ‘Flash fame’ purchased ColdFusion .There was even a tutorial on MacroMediaColdFusionExprsess in DeveloperIQ., a few months back.It is interesting to make a comparison of the CF tags approach and the JSTL approach., especially , in DataBaseoperations.Readers are requested to read the lesson on ColdFusion,in this edition, after covering sql tags in JSTL , in the fourth part of this tutorial.
To resume,the release of the TagLibrary API, triggereda lot ofactivity and hundreds of tags were introduced by the java community, some of them ‘open’ and a few ‘proprietary’.This led to a lot of confusion in code maintenance, because knowledge of Java was no longer sufficient to understand and interpret a given jsp page using non-standard tags .The JCP had unwittinglyintroduced elements of confusion by the JSP-Custom-Tag specification. To correct this problem, Sun and JCP, initiatedthe JSP-Standard Tag Library (JSTL) project.Though there are a number of popular and powerful tag-libraries, it is always better for j2ee coders toadopt the JCP standard because, it is likely to be merged into the core specification of Java langauage itself , in future. (That yardstick may be valid for all creations, in Java world. Splintering of the Java platform due to’ hyper-active creativity’without the corresponding discipline to get it through a standards body ,is the greatest threat, looming large in the Java-horizon. Too frequent revisions and additions, that too without caring for backward compatibility,are not conducive to programmer productivity and the net result is that programmers spend ,in learning new twists in grammar,their precious time which should have been spent more usefully in applying that grammar in solving business-logic problems and acquiring proficiency in the chosen application-domain. While, tag library is sometimes very elegant and simple to use, it defeats the very purpose if the tags are not standard tags and if there is proliferation of non-standard tags.It is for this reason that JSTL merits our serious study and adoption. JSTL is a quite recentdevelopment. It was only in 2003, that the official version 1.1 was released and now incorporated intoJSP-2.
According to the latest position, the JCP is suggesting that a JSP page should be completely free from any trace of Java code!So, programmers who were writing their JSP using Javabeans and scriptlets , may not be able to carry on in their old style as,to prevent programmers from
introducing scripting sections in their pages, there is aprovisionfor turning off scriptlets altogether from a jsp page. If that happens ,all our knowledge of Java coding will be of little use in creating a jsp page, though such knowledge may be useful in creating beans and other types of java programs. It is thus very important forJ2EE students, to understand the trend and get to know the techniques, advantages and limitations oftag libraries…In a way, a study of JSTL is almost synonymouswith a study of the latest version of JSP (ie) JSP2.0 .

Without an introductory demo for each of these types, it may be difficult to appreciate the significance of the above lines. So we will now give simplest illustration. [It is presumed that readers are conversant with basic Servlets & JSP techniques and executing them in Tomcat environment. In case of any difficulty, they can refer to back issues of this magazine ( from Oct-2003onwards) and gain access to a number of lessons for illustrations.] Servlets are full-fledged java-classes and so are very powerful. But, when we want to create a dynamically-generated web-page using servlets, it becomes difficult and clumsy. Let us consider a very simple example.
The user fills up text in html form with his name and submits the form,to the servlet. The servlet reads the data , appends a greeting and sends it back to the user. We begin with a simple html form;
//greeting.htm
[code lang=”html”]
<html><body>
<formmethod=post action=’http://localhost:8080/servlet/greeting’>
<inputtype=textname=’text1′>
<inputtype=submit>
</form>
</body>
</html>
[/code]
(relevant section of greeting.javaservlet)
[code lang=”html”]
//greeting.java( code-snippet only)
public
void doPost(HttpServletRequestreq,
HttpServletResponseresp)
throwsServletException,IOException
{
resp.setContentType("text/html");
PrintWriterout
= resp.getWriter();
//——————————-
Strings
= req.getParameter("text1");
out.println("<html><bodybgcolor=yellow>");
out.println("wewelcome"+",<br>");
out.println (s);
out.println("</body> </html>");
}
[/code]
It will be noticed thatwe have to write so many ‘out.println’ statements. This makes the page unreadable.( If String-buffer is used , we can do it with just a single out.println , butforming the correct string may pose difficulties).
It is to solve this problemthat JSP was developed five years back(1999).While a servletinterposes HTMLin java code, JSP interposes java-code in HTML, as some authors correctly observe..( in this case, we have to modify the action field in html form, so that it refers to the following greeting1.jsp).
Student readers will know about ‘delimiters’( <%).in ASP. This is the same as inJSP. Only the syntax is slightly different.In JSP parlance, the code within delimiters is known as ‘scriptlet‘.( see greeting1.jsp)
———————————————–
//greeting1.jsp
[code lang=”html”]
<html>
<bodybgcolor=yellow>
<%
Strings = request.getParameter("text1");
out.println("we welcome"+<br>);
out.println(s);
%>
</body>
</html>
[/code]
Some coders prefer to use expressions. What is an ‘expression’? It is a method of sustituting request-time values in html page. ( see greeting2.jsp). Carefully note that there is no semi-colon after (“text1″).
[code lang=”html”]
// greeting2.jsp
<html>
<bodybgcolor=yellow>
we welcome <br>
<%=request.getParameter("text1")%>
</body>
</html>
[/code]
The third variant is to use a javabean to encapsulate the business-logic. Wedevelop a jsp-bean as follows:
[code lang=”java”]
//greeter.java
packageourbeans;
public class greeter
{
public
greeter(){}
publicStringgreetme(Strings)
{
return"we welcome…"+s;
}
}
[/code]
This source file is compiled and the class-file is copied to : ‘e:tomcat5webappsrootWEB-INFclassesourbeans’ (Carefully note that WEB-INF folder name should be in capital letters).
( Anytime, a new class is placed in Tomcat, we should remember to restart the server).
We can nowwrite our JSP code as follows:
greeting3.jsp
[code lang=”html”]
<html>
<body>
<jsp:useBeanid=’bean1’class=’ourbeans.greeter’>
<%
Strings
= request.getParameter ("text1");
Stringr =bean1.greeteme(s);
out.println(r);
%>
</body>
</html>
[/code]

We are now enteringJSTLzone. How exactly we should proceed toinstalJSTL, we will take up shortly. For the moment, we are just getting familiar with the required syntax.We begin with taglib directive.

<%@taglibprefix=”c”uri=”http://java.sun.com/jstl/core”%>

The directive says that we are using ‘core’ tags and the prefix will be ‘c’.If we want to assign the value ‘sam’ to a variable ‘a’ and then print it, the JSTL code will be

[code lang=”html”]
<c:set var="a"value="sam"/>
<c:out value="${a}"/>
[/code]
The Dollar sign & brace will be familiar ground for Perl programmers.In JSTL & JSP-2, it isknown as EL ( Expression Language).

To consider another example,Inservlet & jsp, we write:
[code lang=”java”]
String s = request.getParameter("text1");[/code]
to collect the input from the user. The same job is done inJSTLby:
[code lang=”html”]
<c:setvar="s" value="${param.text1}" >[/code]

With these brief hints, it should not be difficult to understand the followingJSPpage writtenbyusing JSTL core-tags.
//greeting4.jsp(usesJSTL)
[code lang=”html”]
<%@taglibprefix="c" uri="http://java.sun.com/jstl/core"%>
<html>
<body>
<c:setvar=svalue="${param.text1}"/>
We
welcome<br>
<c:outvalue="${s}" />
</body>
</html>
[/code]
In the previous examples, there was java code in a few lines atleast. But, in theJSTLexample, we find that there are only tags and no javascriptlets. This is the avowed objective of the JSTLinitiative, under the auspices of Java Community Project! Why?This enables, clean separation ofPage author’s role and Logic programmers’ role. Thus maintenance becomes easy.

There are five groups under which the JSTL tags have been organized. They are as follows:

  1. core
  2. xml
  3. sql
  4. formatting
  5. functions.

The most difficult part isto set up Tomcatso that it executes JSTL.There are some basic requirements, before we can experiment and study the use of JSTL.All that we have studied in using Tomcat for servlets and JSP may not be sufficient to learn JSTL, because, jstl library is not built into Tomcat5even, as yet. Without hands-on experimention, JSTL could be confusing and strange, because of thefact that it is veryrecent. But in coming months, support will be built into Tomcat and we won’t have to worry about installing the JSTLlibraries inside Tomcat. But, as it is, we have to learn how to set up the necessary development environment..So , how do we go about , placing the JSTL libraries in tomcat?

The best solution is to get JWSDP1.3. This is Java Web Service Development’ Pack.
( Carefully note the version , however!). It is good to start with this because, it contains a lot of valuable software , including the latest and greatest fromJCP, (ie) JSF (Java Server Faces)…. which may soon replace Struts.
We unzipthe jwsdp1.3and installit in C: drive. There are a number of folders like JAXP, JAXR, JAXB,JAX-RPC, JSF,JSTL etc. in the JWSDP pack.
For the present, we are interested in JSTL folder only. If we expand the JSTL folder, we find four sub folders :

  1. docs
  2. lib
  3. samples
  4. tld(tag library descriptors)

When we look into the ‘lib’ folder, we findtwo jar files:

  1. standard.jar
  2. jstl.jar

We should copythese two jar files into:
[code]
‘e:tomcat5webappsrootWEB-INFlib’
[/code]

(Remember to restart the Tomcat server). That is all that is required to useJSTL. ! The included taglibrary descriptors do not have to be placed in the WEB-INF folder.These files are alreadyincluded in the /META-INF folder of the jstl.jar and so will be automatically loaded by Tomcat, when it is restarted. ( we are using tomcat5 & jdk1.4.2) ( the results are notensuredfor other environments.).( however, we adopted the same method in Tomcat4.1 with jdk1.41 and got correct functioning.)

The JSTLfolder contains a sub-folder named ‘tld’.There will be a number of tld files there such as c.tld ( core), x.tld (xml), fmt.tld

Filed Under: Java EE Tagged With: JSTL

Hibernate Vs EJB 3.0

April 10, 2008 by Krishna Srinivasan Leave a Comment

Originally published in DeveloperIQ magazine

What is CMP and BMP in EJB?

So, why is it that Entity beans alone were found wanting and the specification keeps on changing? Entity beans are of two types. CMP & BMP. CMP stands for Container-Managed Persistence and BMP stands for Bean-managed persistence. Theoretically, the EJB specification does not say anything about the method to be adopted in persisting objects for permanent storage and retrieval. It could be simple object serialization. The database may be object-database or Object-relational database or XML.In practice , however, a database has always meant a Relational Database and its SQL.

also read:

  • Introduction to Hibernate
  • Hibernate Interview Questions
  • Interceptors in Hibernate
  • Hibernate Books

In a very complex Enterprise application, we begin with Modelling. Instead of dealing with tables and their complex inter-relations, it is more intuitive to deal with classes and objects. Thus we design our system , ‘thinking in objects’ and not in tables. So long, as we are dealing with objects in memory or with objects persisted in hard-disk simply as objects, there is no problem, except that object-serialization , especially of complex objects is a slow process. On the other-hand, Relational Database technology is fast, time-tested, well-known and famous. So, the problem is to work with objects in memory but persist the objects in hard disk as relational database.

This is what is known as ORM ( Object-Relational Mapping).If we opt to deal directly with tables only and either read data or manipulate data by session beans, we skip the entire ORM problem. But how practical is it for really complex projects? That is the rationale for the development of Entity Beans in EJB.

In CMP, the coder deals with objects, only in memory. He creates new objects, modifies them, deletes them and views them , all in memory. The task of saving these objects in memory ,to the relational database table is done by the container, automatically. The coder does not write any sql-related code for this.

In BMP, the coder has to write the sql to persist the object in memory to the relational database.

CMP in EJB1.1 was suitable for simple tables, without complex relationships to other tables. CMP avoids all references to the underlying database. So, it is more portable. There is no vendor-lock-in. CMP can persist data to Object- databases also, besides Relational databases.

But, CMP is not always suitable. If the database is some legacy type, which cannot be used with SQL, the database company gives a proprietary code for persistence and such code has to be used in our program to persist data. The facilities given in CMP originally were found to be too elementary and there were complaints.

But, what matters is that CMP makes use of ORM concepts, though the implementation left much to be desired. It did not expose how the EJB vendor implements it. Weblogic, Oracle, IBM WebSphere, SUN , JBoss , each may implement CMP in any way that they deem fit. Except in special circumstances, it will be better to use CMP, not merely because, it makes the code more portable & is easy to write. Much more important reason is that the EJB container can optimize the performance dramatically, if we adopt CMP. So the developer community wanted to adopt CMP but found it unsuitable for really complex jobs.

And a sizable section of developers found the XML Deployment Descriptors for CMP ,especially for complex jobs, a bit troublesome and tedious.It can be said that any design which makes us dependent on wizards, is a bad design. Unlike the Deployment Descriptors for Session beans, which can be hand-coded in a jiffy, by just find/replace method in a text editor, the DD for CMP required three XML files, two of them very special to the container used.

In order to improve things, EJB 2.0 proposed a few changes, mainly in the matter of writing CMP. It provided for Relationships. It proposed a simple query language known as ‘EJB-QL’. Since, calling an Entity bean through a session bean (Facade pattern) is more efficient , from the viewpoint of minimizing network traffic, the very concept of remote interface for entity beans was questioned and so local interface also was provided for Entity beans.( In a total reversal, there is no local interface in EJB-3! and instead of EJB-QL , Hybernate Query Langauge is taking over in EJB-3).

Even with all these improvements, CMP was found to be less than the ultimate solution. There was no possibility for Inheritance.

Though the container services provided by the EJB container are indispensable in a truly large enterprise application, the J2EE camp is almost vertically split into WebTier & EJB-Tier votaries. The WebTier supporters claim that EJB with its steep learning curve and error prone development environment for developers is not really necessary for most applications. And they would like to have an ORM tool , built into the J2EE specification. For after all, ORM task is not specific to EJB alone. Even Servlets and JSP could use them. In fact , they have been using them, though the J2EE specification was silent about it. ORM tools like OJB, JDO and Hibernate can be used not only in EJB containers but in webcontainer and even in standalone containers. Gavin King makes it a special point in favour of Hibernate. Making such a tool , a J2EE standard, would make development tasks far easier ,to develop either web-tier application or ejb-tier application, saving us from the medley of classpath to required jars.

In a scathing attack on the complexity and questionable performance of EJB Entity beans (though, unjustifiably on EJB itself), Rod Johnson,prophesies , that in a few years’ time, J2EE will cease to include EJB. Whether , we agree or not, it is worth looking into the criticisms against EJB Entity beans ,raised by him.( ‘J2EE Development without EJB’-Wrox/Wiley/DreamTech-2004).For, he is proposing the Spring Framework as an alternative to EJB container and the idea is gaining ground.J2EE developers and students may have to re-orient themselves rather abruptly, to remain relevant to industry.

Originally published in DeveloperIQ magazine

Introduction

The J2EE field is agog with excitement about a very popular open-source technology , Hibernate , being elevated to the status of JCP standard. Feedback from J2EE programmers in industry says that knowledge of Hibernate is mandatory for all J2EE aspirants. In this short tutorial , the author attempts to trace the reasons for this new trend & to alert us , to the imminent and dramatic changes in the J2EE landscape.

What is Hibernate?

HIBERNATE is an ORM ( Object-Relational-Mapping) technology. It is an Open-Source and free technology , developed in SourceForge.net. There have been a number of such ORM technologies,in recent past.. TopLink is one such tool , subsequently adopted by Oracle and so proprietory.

Hibernate from SourceForge and OJB(Object-Relational-Bridge) from Apache are two well known ORM tools,open-source and free. JDO , also falls within the same category.

Gavin King is the lead for Hibernate and Craig Russell & David Jordan , the lead authors for SUN-sponsored JDO effort. Due to some technical problems, it appears that the majority in JCP favors Hibernate today instead of JDO.At first reading though, the difference is not, all that apparent. The syntax and the approach appear to be almost same,but Hibernate syntax is easier to learn.

It is interesting to note that Craig Russell works for SUN and Gavin King is now with JBoss. It shows that JCP is a democratic community and SUN is not dictating terms except to protect the language and its enterprise-level users.

Hibernate and EJB 3.0

EJB-3 , is the latest version and it is heavily influenced by Hibernate. Some readers equate EJB-3 with Hibernate. Some even equate EJB-3 with JBOSS! Oracle supports EJB-3 proposals and as it is the main Database company in j2ee world, EJB-3 has bright future. J2EE( Java Enterprise Edition) by its very name is an Enterprise level technology, and as EJB is the essence of such Enterprise applications, because of the built-in container services offered, the significance of the surging interest in Hibernate can be really appreciated only in association with EJB and hence a detour into EJB is inevitable.

EJB has three types. One type is the SESSION BEAN,residing in ENTERPRISE container, which can be thought of as a function-bean, invoked in RMI-IIOP style. (this is a rough definition).Such session-bean , may be either stateless or stateful.

This type of EJB has stood the test of time during the last six years and has even gained wide approval, even for data-access, especially since it fits very well with the emerging XML WebService technology, and is very easy to learn and implement.( The earlier tutorial on EJB as webservice in Feb-2005, in DeveloperIQ illustrates this feature).The stateless bean working in Enterprise container has an exact counter-part in Microsoft COM+(MTS), but the other types are said to be available in MS platform only through third-party extensions.

ORM tools have been sometimes used along with Session beans. The only problem till recently was that they were proprietary and rather costly. But nowadays, very reliable open-source ORM tools are available, and even Richard Monson Haefel ( an acknowledged authority and author on EJB)approves this method as a safe and productive alternative to Entity beans.( page-467..EJB by Haefel-OReilly).

The other branch, the ENTITY BEAN has been less lucky. EJB-1.1, EJB-2.0 and then EJB-2.1 , have meant a number of changes in the specification relating to Entity Beans. We can say that an Entity bean is an ‘Attribute bean’ or ‘property-bean’, with setter and getter methods, invoked in RMI-IIOP style and persisted in Enterprise container. The pattern of defining a typical Javabean is a recurring theme in Java. The same style occurs in BDK,EJB-Entity beans, Struts,JSF and now in Hibernate too. So, it is very important and elegant.

The third branch is Messaging paradigm and MDB. A recent article in the web dubbed the ‘RPC’ style, on which the previous two types of EJB are based, as stone-age technologies! An Enterprise by its very name implies huge number of customers and concurrent transactions, RPC style being like telephone call, could result in ‘line-engaged!’ problem. If the call involves the called person referring to some records before replying, it leads to line- blocking. But, messaging style, as in email, at least ensures that the message has been sent. It is evident that dubbing RPC( read ‘telephone’) as unsuitable , is over-statement. Sometimes, we desire immediate response, too. By the same token, even XML webservice , if it is really serious, should adopt messaging style and it does.MDB (Message-Driven bean) has weathered the storm and is in fact gaining more and more acceptance.

Filed Under: Java EE Tagged With: EJB, EJB 3, Hibernate

Expression Language in JSP 2.0

August 20, 2007 by Krishna Srinivasan Leave a Comment

1)Introduction

Expression Language was first introduced in JSTL 1.0 (JSP Standard Tag Library ). Before the introduction of JSTL, scriptlets were used to manipulate application data.JSTL introduced the concept of an expression language (EL) which simplified the page development by providing standerd tag libraries. These tag libraries provide support for common, structural tasks, such as: iteration and conditionals, processing XML documents, internationalization and database access using the Structured Query Language (SQL).

also read:

  • Java EE Tutorials
  • Servlets Interview Questions
  • New Features in Servlets 3.0
  • Asynchronous Servlets in Servlets 3

The Expression Language introduced in JSTL 1.0 is now incorporated in JavaServer Pages specification(JSP 2.0). This articie gives some idea about what is Expression Language and how to simplify the maintenance for JSP applications by avoiding scripting elements.

2)Expression Language

The pattern that identifies Expression Language is ${ }. To deactivate the evaluation of EL expressions, we specify the isELIgnored
attribute of the page directive:
[code lang=”html”]
<%@ page isELIgnored ="true|false" %>
[/code]

The valid values of this attribute are true and false. If it is true, EL expressions are ignored when they appear in static text or tag attributes. If it is false, EL expressions are evaluated by the container.

Operators which can be used in EL expression
[code]Operator    Description
    .         Access a bean property or Map entry.
    []         Access an array or List element.
    ()         Grouping of a subexpression for evaluation order.
    ? :         Conditional test: condition ? ifTrue : ifFalse.
    +         Addition.
    –         Subtraction.
    *         Multiplication.
    /or div     Division.
    % or mod M    Modulo (remainder).
    == or eq     equality.
    != or ne     inequality.
    < or lt     less than.
    > or gt     greater than.
    <= or le     less than or equal.
    >= or ge     greater than or equal.
    && or and     logical AND.
    || or or     logical OR.
    ! or not     Unary Boolean complement.
    empty         Test for null,empty String,array or Collection.
    func(args)     A function call.
[/code]

  • Arithmetic operators.

    [code] Before JSP2.0/JSTL
    <%! int k = 0; %> <% k = 10 + 20; out.println("value of k is.."+k); %>
    Using JSP2.0/JSTL (without using scriptlet)
    value of k is ${10 + 20} [/code]
    Few more examples on arthmetic operations.
    [code] EL Expression Result
    ${10.2 + 20.3} O/P: 30.5
    ${-40 – 20} O/P: -60
    ${20 * 2} O/P: 40
    ${3/4} O/P: 0.75
    ${3 div 4} O/P: 0.75
    ${10/0} O/P: Infinity
    ${50%8} O/P: 2
    ${50 mod 8} O/P: 2
    ${(10==20) ? "true" : "false"} O/P: false [/code]

  • comparison operators.

    [code] Numeric EL Expression Result
    ${10 (4/2)} false
    ${1 gt (4/2)} false
    ${4.0 >= 3} true
    ${4.0 ge 3} true
    ${40 <= 30} false
    ${40 le 30} false
    ${10 == 10} true
    ${100 eq 100} true
    ${(5*20) != 100} false
    ${(5*20) ne 100} false

    Alphabetic EL Expression Result
    ${‘a’ 3} true [/code]

  • EL implicit objects

    [code] Identifier Description
    pageContext PageContext instance
    pageScope Map-associates name and values of page-scoped attributes
    requestScope Map-associates name and values of request-scoped attributes
    sessionScope Map-associates name and values of session-scoped attributes
    applicationScope Map-associates name and values of application-scoped attributes
    parametersparam Map-stores the primary values of the request parameters by name
    paramValues Map-stores all values of the request parameters as String arrays
    header Map-stores the primary values of the request headers by name
    headerValues Map-stores all values of the request headers as String arrays
    cookie Map-stores the cookies accompanying the request by name
    initParam Map-stores the context initialization params of the appln by nam[/code]

  • Note:EL impilcit objects are not as same as the implicit objects available for JSP scripting except for pageContext.JSP and EL implicit objects have only one object in common (pageContext),and pageContext has properties for accessing all of the other eight JSP implicit objects.The first four maps represent the various attribute scopes which can be used to look up identifiers in specific scopes. The next four maps are for fetching the values of request parameters and headers.The cookie implicit object provides access to the cookies set by a request and the final EL implicit object, initParam, is a map storing the names and values of any context initialization parameters associated with the Web application.Lets look at few examples on how to use implicit objects.
    [code] First.jsp
    First Name: <input type=’text’ name=’Name’/>
    Last Name: <input type=’text’ name=’Address’/>
    <input type=’submit’ value=’Submit’/>

    Second.jsp
    Name is : ${param.Name}
    Address is : ${param.Address}
    Similarly

    Header Key : ${header.key}
    Header Value : ${header.value} [/code]
    Here in First.jsp we are entering the details of Name and Address, when we click on submit button the flow goes to Second.jsp.
    We can retrieve the values by using ${param.xxxx}

  • Scope Examples:

    [code] Accessing a page-scoped attribute named as firstName: ${pageScope.firstName} Accessing a request-scoped attribute named as firstName: ${requestScope.firstName} Accessing a session-scoped attribute named as ‘lastName’ (null if not found): ${sessionScope.lastName} [/code]

  • Page Context Examples
    [code] ${pageContext.request.protocol} ${pageContext.response.locale} ${pageContext.session.id} ${pageContext.servletContext} [/code]
    Above we are accessing request, response, session, and application properties, using the pageContext implicit object.
  • Cookie Example:

    [code lang=”java”] addCookies.java
    Cookie c=new Cookie("name","test");
    res.addCookie(c);

    Test.jsp
    Name : ${cookie["name"]}
    Value : ${cookie["name"].value} [/code]
    Here in addCookies.java we are creating a new Cookie,These values can be retrieved in jsp by using ${cookie.xxxx}.

  • Init Parameter Example
    [code lang=”xml”] XML:
    <context-param>
    <param-name>email</param-name>
    <param-value>Hello@xyz.com</param-value>
    </context-param>

    Test.jsp email is: ${initParam.email} [/code]

  • Functions
    Defining Functions:The JSP expression language allows you to define a function that can be invoked in an expression. Functions are defined using the same mechanisms as custom tags.
    [code lang=”java”] public class MyFunctions { public static String toCaps( String text ) { return text.toUpperCase(); } } [/code]
    Using Functions:
    [code lang=”xml”] XML: <uri>testFunctionsURI</uri>
    <function> <name>toCaps</name>
    <function-class>mypkg.MyFunctions</function-class>
    <function-signature>String toCaps( java.lang.String)</function-signature>
    </function>

    JSP: <%@ taglib prefix="myFunctionTest" uri="testFunctionsURI"%> ${myFunctionTest.toCaps("testingCaps")} [/code]

Conclusion

By using this expression language, page authors could drastically reduce the amount of scripting in their pages, resulting in greater productivity, easier maintenance, and a flatter learning curve in terms of page development. Over the years, the expression language has evolved to include more advanced functionality, while still maintaining its simplicity.

Filed Under: Java EE Tagged With: JSP 2.0

J2EE Connector Architecture(JCA), An Introduction

July 16, 2007 by Krishna Srinivasan Leave a Comment

Introduction

JCA, the J2EE Connector Architecture, is an initiative towards EAI, Enterprise Application Integration. It is a standardized architecture providing the J2EE Components to have plug and play access to heterogeneous EIS, Enterprise Information Systems. Examples of EIS are ERP (Enterprise Resource Planning), Transaction Processing Systems, Legacy Database Systems etc. In the following section we will discuss about the major problems that the programmers had to face for the EIS Integration and the role of JCA.

also read:

  • Java EE Tutorials
  • Java EE 7 Tutorials
  • Java EE Interview Questions

EIS Integration

An Enterprise Information System provides the information infrastructure for an enterprise. This information may be in the form of records in the database, business objects in an ERP, a workflow object in a Customer Relationship Management (CRM) System or a transaction program in a transaction processing application. Prior to the Internet economy, many companies had heavily invested in Business and Management Information Applications Systems.

Examples of such systems can be:-

  • ERP, Enterprise Resource Planning applications, such as SAP, BAAN etc.
  • CRM, Customer Relationship Management applications, such as Seibel and Clarify.
  • Database applications such as DB2 and Sybase.
  • Main Transaction processing applications, such as CICS.
  • Legacy Database Systems such as IBM’s IMS.

Before the JCA, most vendors supported a variety of custom adapters for integrating their EIS. Basically these adapters provided custom native interfaces, which were complex to incorporate and limited to only one EIS. Because of this the application programmers had to deal with as many adapters as the number of EIS their application communicates to. Some of the limitations are listed below:-

  1. Application programming for the EIS was proprietary in nature, because there was no generic platform for integration with the open architectures.
  2. Custom adapters lacked support for Connection Management, which is very crucial for large scale Web Applications, where thousands of customers interact every second. Because of which programmers had to implement connection pooling in their code which is a shear waste of time and money of the enterprises.
  3. There was no standard infrastructure solution available to provide a vendor-neutral Security Mechanism and Generic Transaction Mechanism support to multiple EIS resource managers.

In order to address the above problems Sun Microsystems released the J2EE Connector Architecture, JCA that provides a standard architecture for integration of J2EE Servers with heterogeneous EIS resources. It provides a common API and a common set of services within a consistent J2EE Environment.

The following diagram shows the J2EE application server with the JCA Components and some Enterprise Information Systems:-

In the above diagram, there is a Web Container and an EJB Container in the J2EE Application Server. There are also some blocks for Resource Adapters. Resource adapters play the role of intermediaries between the J2EE Application / Web Components and the EIS. The programmers communicate with the Resource Adapters using the CCI API, Common Client Interface API. This is very similar to the JDBC API where the J2EE Components communicate with the relational database drivers using the JDBC API.

In this architecture, the J2EE Application Server implements the JCA Services like Connection Management, Transaction Management and Security Management etc. Whereas the EIS vendors implements the Resource Adapters specific to their products. This way the programmers need to code their programs in vendor neutral manner to communicate with heterogeneous EIS resources from different vendors.

Elements of the J2EE Connector Architecture

The JCA is implemented by J2EE compliant Application Servers and the Resource Adapters are provided by the EIS vendors.
The Resource Adapter is an EIS specific, pluggable J2EE Component in the Application Server, which provides an interface for the J2EE Components to communicate with the underlying EIS.

There are the following elements and Services in a JCA implementation:-

  1. System-level Services: – It defines the standard interface between the J2EE Components and the J2EE Aplication Server provider and the EIS Vendor. This contract specifies the roles and responsibilities of the Resource Adapter and the Application Server, so that they can co-ordinate with each other for the System level services like Connection Pooling, Security and Transactions. Furthermore this allows for any JCA compliant Resource Adapter to be pluggable to any J2EE Compliant Application Server.
  2. CCI, Common Client Interface: – This is an API which is used by the J2EE Components and other non managed Java Applications (like standalone Java programs and Java Applets) to communicate with the Resource Adapters, which in turn communicate to the underlying EIS.
  3. Packaging and Deployment Interfaces: – Packaging and Deployment Interfaces allow the Resource Adapters to be able to plug into any Application Server.

The following diagram shows all the components of the J2EE Connector Architecture. It shows how the components communicate with each other.

The CCI, Common Client Interface is part of the implementation of the Resource Adapters. The J2EE components use this API in order to communicate with the underlying EIS resource. Because of the System Level contracts the J2EE Application Servers provide the services like Connection Pooling, Transaction Management and Security Management and the programmers can stay away from the implementation of these services.

There are two types of environments based on the type of client application using the Resource Adapter. These are: –

  • Managed Environment: – This includes the multi tired J2EE based Web Applications that may have several Web / Application Components communicating to the Resource Adapters. Such applications are called as the Managed Applications in the JCA context.
  • Non-Managed Environment: – In a two tired architecture, where the application client directly uses the application, the Resource Adapter provides the system level services to its clients. Such applications are referred as Non Managed applications.

Resource Adapter

The Resource Adapter is a component in the J2EE Connector Architecture that sits between the J2EE Components and the EIS. This module is implemented with the EIS specific library, which can be written in Java or with native interface components. Basically it implements two things, first is the Common Client Interface, CCI so that when the developers invoke the methods of this library in their code, the invocations can be resolved by the implementations inside the Resource Adapter, and second is the implementation of the functionality through which it connects to the underlying EIS resource and get the work done for the method invocations. The Resource Adapters are required to support the System Level contracts as is required by the Application Servers. There are mainly two types of contracts that a Resource Adapter implements in order to get compliant with the JCA. These are: –

  • Application-Level Contracts: – Application Contract basically defines the CCI that the Resource Adapter must implement in order for the J2EE Components and the non-managed components to communicate to the underlying EIS resource.
  • System-Level Contracts: – This defines a set of System Contracts which enable the Resource Adapter to plug-in into the Application Server and utilize its services to manage connections, transactions and Security. The three basic contracts are discussed below: –
    • Connection Management: – The Connection Management contract specifies the following things: –
      1. Connection to the Resource Adapters for managed and non-managed components can be made by using consistent application programming techniques, which remain same every time.
      2. The Resource Adapter provides the Connection Factory and Connection Interface based on the CCI, which in turn is specific to the EIS.
      3. Provide a generic mechanism for the J2EE components to consume the Application Server services like Transaction, Security and last but not the least the Connection Pooling etc.
    • Transaction Management: – This contract extends the Application Server’s transactional capabilities to the underlying EIS Resource Managers. An EIS Resource Manager manages a set of shared EIS resources to participate in a transaction. It can manage the following two types of transactions: –
      1. XA Transaction: – XA Transactions are controlled and coordinated by external Transaction Managers. A JTA XATransaction Management contract exists between the JCA compliant Resource Adapters and its underlying Resource Manager. The participating EIS resource also supports XA Transactions by implementing an XAResource in their Resource Adapter. The JTA XAResource interface enables two resource managers to participate in transactions coordinated by an external Transaction Manager. This allows the transactions to be managed by a transaction manager which is external to the Resource Adapter.
      2. Local Transactions: – These transactions do not require any external Transaction Manager, because it is managed internally, either by the J2EE Application Server (container managed) or by the J2EE component (component managed). In Component Managed Transactions the component uses JTA UserTransaction interface or a transaction API specific to the EIS. When an application component requires an EIS Connection, the Application Server starts a local transaction using the currently available transaction context. Upon closure of the connection by the application component, the server commits or rolls back depending upon success or failure of the transaction.
    • Security Management:- This contract defines ways to implement security between the Application Server and the EIS resource. There are the following mechanisms used to protect the EIS against unauthorized access and other security threats:-
      1. Use of user identification, authentication and authorization.
      2. Use of open network communication security protocols like Kerberos which provide end to end security with authentication and confidentiality services.
      3. Implementing an EIS specific security Service.

EIS Sign-On

A Sign-on process is required while creating a new connection to EIS. Based on the security context, authentication and authorization is done for the user to obtain appropriate access. A re-authentication is required in case the Security Context is changed for the user. The following steps are required for sign on:-

  1. Identity of the initiating user, or Resource Principal, is determined. This helps finding the security context of the user using which the connection will be established to the EIS.
  2. Resource Principal is authenticated if the connection is not already authenticated.
  3. Establish a secure connection between the Application Server and the EIS Resource using secure mechanisms like SSL or Kerberos etc. At this point the connection is associated with the initiating user. All subsequent invocations will happen under this context.

This sign-on process can be Application Managed or it can be Container Managed. In case of Application Managed sign-on process, the application component itself provides the security credentials to the EIS Resource Adapter. While in the later case it becomes the duty of the application to find out the Resource Principal of the initiating user and present information of this Resource Principal to the EIS Resource Adapter in the form specific to the JAAS, Java Authentication and Authorization Service.

Packaging and Deploying a Resource Adapter

The Resource Adapters module is packaged as a .rar file, similar to the .ear files for the J2EE Application Modules. There are proper deployment and packaging interfaces that allow a Resource Adapter to plug-in to any J2EE compliant Application Server. The following diagram illustrates the process of packaging and deployment of Resource Adapters module into the Application Server.

The exact steps involved in packaging and deployment are listed below: –

  1. The EIS Resource Adapter provider, usually the EIS Vendor, implements the Resource Adapter as a set of Interfaces and utility classes implementing the CCI API and the EIS functionality. These implementations take care of the JCA contracts that the Resource Adapter need to follow for JCA compliance.
  2. All the components of the Resource Adapter, including the source files are packaged into a .rar file, called as Resource Adapter Module. The deployment descriptor of the Resource Adapter specifies the contract between the Resource Adapter provider and the one who deploys the Resource Adapter.
  3. In the actual deployment process the Resource Adapter is deployed in the Application Server and then it is configured with the Application Server and the underlying EIS environment.

Lets now discuss these steps in greater detail:-

Packaging a Resource Adapter

The Resource Adapters are proper J2EE components packaged in .rar files. One or more Resource Adapters can be staged in one directory and then packaged as .rar files. The following steps are usually involved for packaging a Resource Adapter:-

  1. Compile the Resource Adapter Java files into a staging directory.
  2. Create a .jar file to add the class files created in the above step.
  3. Create an ra.xml deployment descriptor file in the META-INF subdirectory. Add entries for the Resource Adapter.
  4. Create a J2EE Application Server specific deployment descriptor in the same directory and add the entries for the Resource Adapter.
  5. Create the Resource Adapter module .rar file by executing the following command: –

[code lang=”java”] jar cvf JavaBeatResourceAdapter.rar -C staging-dir[/code]

Now this .rar file can be deployed to the Application Server or packaged inside an application’s .jar file. The packaged Resource Adapter includes the following: –

  1. Java Classes and Interfaces that implement the functionality of the JCA contract and the underlying EIS resource.
  2. Some helper classes used by main implementation classes.
  3. Platform dependent native libraries required by the Resource Adapter.
  4. Meta information about the above elements.
  5. Documentation.

After installation of the .rar file, the directory structure of the Application Server looks like the following: –

[code lang=”java”] \AppServerHomeDir
\config
\JavaBeatDomain
\applications
\JavaBeatResourceAdapter.rar [/code]

There are basically two deployment descriptors packaged within a .rar file of the Resource Adapter Module. These are the ra.xml, which specifies the general information about the Resource Adapter, and the ABCAppServer.xml, which specifies operational parameters required for the Application Server.

Ra.xml, the Resource Adapter deployment descriptor

Following is a deployment descriptor for an ABC Resource Adapter, we will discuss about all the xml elements in this file after this example: –

[code lang=”xml”]<connector>

<display-name>ABCResourceAdapter<display-name>
<vendor-name>Java Beat</vendor-name>
<spec-version>1.0</spec-version>
<eis-type>JDBC Database</eis-type>
<version>1.5</version>

<resourceadapter>

<managedconnectionfactory-class>com.sun.connector.javabeat.NoTxManagedConnectionFactory</managedconnectionfactory-class>
<connectionfactory-interface>javax.sql.Datasource</connectionfactory-interface>
<connectionfactory-impl-class> com.sun.Connector.abc.JdbcDataSource</connectionfactory-impl-class>
<connection-interface>java.sql.Connection</connection-interface>
<connection-impl-class>com.sun.connector.abc.JdbcConnection</connection-impl-class>
<transaction-support>NoTransaction</transaction-support>
<config-property>
<config-property-name>ConnectionURL</config-property-name>
<config-property-type>java.lang.String</config-property-type>
<config-property-value>jdbc:cloudspace:rmi:CloudscapeDB:create=true</config-property-value>
</config-property>
<authentication-mechanism>
<authentication-mechanism-type>BasicPassword</authentication-mechanism-type>
<credential-interface>javax.resource.security.PasswordCredential</credential-interface>
</authentication-mechanism>
<reauthentication-support>false</reauthentication-support>

</resourceadapter>

</connector>[/code]

The first block of the descriptor is:-

[code lang=”xml”]<display-name>ABCResourceAdapter<display-name>
<vendor-name>Java Beat</vendor-name>
<spec-version>1.0</spec-version>
<eis-type>JDBC Database</eis-type>
<version>1.5</version>[/code]

It lists general information about the Resource Adapter, like its name, Vendor’s name, specification version, the type of the EIS resource that this Adapter is representing and the version of the JCA supported.

Then the name of the class that implements the javax.resource.spi.ManagedConnectionFactory interface is listed in the element.

The ConnectionFactory interface and the implementation class are mentioned thereafter in the following block of the descriptor:-

[code lang=”xml”]<connectionfactory-interface>javax.sql.Datasource</connectionfactory-interface>
<connectionfactory-impl-class> com.sun.Connector.abc.JdbcDataSource</connectionfactory-impl-class>[/code]
The Connection implementation class for the java.sql.Connection interface is com.sun.connector.abc.JdbcConnection.

The level of transaction support can be either NoTransaction, or LocalTransaction or XATransaction. In this example the Resource Adapter does not support transaction which is specified by the NoTransaction value in the element.

Certain properties of ManagedConnectionFactory can be configured by specifying a name and type of the property and then providing a value of the property as follows: –

[code lang=”xml”]<config-property>
<config-property-name>ConnectionURL</config-property-name>
<config-property-type>java.lang.String</ config-property-type>
<config-property-value>jdbc:cloudspace:rmi:CloudscapeDB:create=true</ config-property-value>
</config-property>[/code]

The last section of the deployment descriptor specifies the authentication mechanisms supported by the Resource Adapter provider. In this case only BasicPassword method is supported. The Security Credential interface is javax.resource.security.PasswordCredential. There is no re-authentication support with this Resource Adapter.

[code lang=”xml”]<authentication-mechanism>
<authentication-mechanism-type>BasicPassword</authentication-mechanism-type>
<credential-interface>javax.resource.security.PasswordCredential</credential-interface>
</authentication-mechanism>
<reauthentication-support>false</reauthentication-support>[/code]

The Resource Adapter can be deployed in two ways as discussed below: –

  1. By using the deploytool command line or the deploytool UI console using the following command: –
    • [code lang=”xml”]Deploytool -deployConnector %J2EE_HOME%\lib\connector\abc-ra.rar <HostName>[/code]
  2. Deploying as a Web Application archive file, i.e. .ear file. In this method the .rar file is included into the .ear file just as we include a .jar or .war file in it. And then the .ear file is deployed in the Application Server. To identify the .rar module in the package the following line is added into the application.xml file: –
    • [code lang=”xml”]<connector>abcresourceadapter.rar</connector>[/code]

JCA Advantages

J2EE Connector Architecture has emerged as the primary technology for providing a vendor neutral platform for the programmers to communicate with multiple EIS resources without changing their components at all. There are the following scenarios in which the technology offers a potential solution: –

  1. Enterprise Application Integration: – While integrating multiple EIS applications there are many challenges that need to be taken care of. These include, transaction, security and scalability issues. Multiple EIS vendors providing their own proprietary APIs for integration, which creates much bigger problem of embedding code specific to each vendor into the application components. But with the JCA technology, the EIS vendors are now required to provide with a Resource Adapters obeying the JCA contracts. And the programmers need to understand just the CCI API, required to communicate with the similar Resource Adapter of all the different EIS resources.
  2. Web-Enabled Enterprise Portals: – Enterprise portals usually unifies all the information, services, applications and processes for all the members of an enterprise, including the employees, clients, partners and customers etc. Such a portal needs to integrate all the heterogeneous EIS resources, such as database systems, information systems etc. which handle all information of the enterprise. In such a scenario the JCA technology solves the problem by seamlessly integrating the different EIS resources by introducing the concept of Resource Adapters and the CCI API. It also helps by providing the EIS sign-on mechanism that supports generic and application specific authentication mechanism.
  3. Business to Business Integration: – Business to Business integration requires end-to-end process automation and allows application interaction with an enterprise and across partners through the internet. In order to support the external partner interactions, the backend internal business systems need to be seamlessly integrated into the same process. With the help of JCA the backend EIS resources and end to end processes can be integrated without much difficulty.

Summary

In this article we discussed about the concept of JCA, J2EE Connector Architecture, how it helps in solving the problems faced in EAI, Enterprise Application Integration, by introducing the concept of Resource Adapters, and the CCI API to facilitate communication between the J2EE Application Components and the underlying EIS, Enterprise Information Systems. We also discussed about the deployment details of the Resource Adapters by looking into two main deployment descriptors required in the process.

This technology is aimed to solve the problems and challages that the industry face while working with heterogeneus EIS, Enterprise Information Systems. In the next article we will discuss about this technology in more detail, which would be aimed at professional programmers in the J2EE domain.

Filed Under: Java EE Tagged With: JCA

Sample Application for Java Persistence API (JPA)

April 15, 2007 by Krishna Srinivasan Leave a Comment

This article is the last part of the article series Java Persistence API (JPA), the earlier articles are introduction to JPA and the query api in JPA. This article is only for explaining the sample program with concepts used in the previous articles. I would recommend reading the previous two articles before start analyzing this sample code. If you are familiar with the JPA concepts, you can jump into the code and complete reading this article. If you have any doubts or queries, please post it in the comments section. Thank you for reading our blog. Have a fun!!

Following is a sample code in J2SE that creates and find Employee objects.

Code for Employee.java

[code lang=”java”]package com.javabeat.ejb30.persistence.entities;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;

@Entity(name = "EMPLOYEE")

@NamedQueries({
@NamedQuery(name = "Employee.findAll",
query = "SELECT EMP FROM EMPLOYEE AS EMP")
})

public class Employee implements Serializable {

@Column(name = "EMP_NAME", nullable = false, length = 100)
private String name;

@Column(name = "EMP_AGE", nullable = true)
private int age;

@Column(name = "EMP_SALARY", nullable = true)
private double salary;

@Id
@Column(name = "EMP_ID", nullable = false)
private Long id;

public Employee() {
}

public String getName(){
return name;
}

public void setName(String name){
this.name = name;
}

public int getAge(){
return age;
}

public void setAge(int age){
this.age = age;
}

public double getSalary(){
return salary;
}

public void setSalary(double salary){
this.salary = salary;
}
public Long getId() {
return this.id;
}

public void setId(Long id) {
this.id = id;
}
}[/code]

The following code test the Employee entity class by creating some sample employee objects and then finding them using the Query API.

Code for EmployeeTest.java:

[code lang=”java”]package employee.test;

import com.javabeat.ejb30.persistence.entities.Employee;
import java.util.Arrays;
import java.util.List;
import javax.naming.Name;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class EmployeeTest {

private static EntityManagerFactory entityManagerFactory =
Persistence.createEntityManagerFactory("EmployeePersistentUnit");

private EntityManager entityManager;

public EmployeeTest() {
entityManager = entityManagerFactory.createEntityManager();
}

public void createEmployees(){
try{
beginTransaction();
Employee emp1 = createEmployee("Johny", 35, 10000, 1L);
entityManager.persist(emp1);
Employee emp2 = createEmployee("David", 43, 50000, 2L);
entityManager.persist(emp2);
Employee emp3 = createEmployee("Philip", 55, 70000, 3L);
entityManager.persist(emp3);
Employee emp4 = createEmployee("James", 29, 30000, 4L);
entityManager.persist(emp4);
}catch (Exception exception){
failTransaction();
}finally{
commitTransaction();
}
}

public List findAllEmployees(){
Query query = entityManager.createNamedQuery("Employee.findAll");
List employees = query.getResultList();
return ((List)employees);
}

public Employee findByName(String empName){
String queryString =
"SELECT EMP FROM EMPLOYEE AS EMP WHERE EMP.EMP_NAME = ?1";
Query query = entityManager.createQuery(queryString);
query.setParameter(1, empName);
return (Employee)query.getSingleResult();
}

public void display(List employees){
for(Employee employee : employees){
display(employee);
}
}

private void display(Employee employee){
StringBuilder results = new StringBuilder();
results.append("Name = " + employee.getName() + ", Age = "
+ employee.getAge() + ", ");
results.append("Salary = " + employee.getSalary() + ",
Id = " + employee.getId());
System.out.println(results.toString());
}

private void beginTransaction(){
entityManager.getTransaction().begin();
}

private void commitTransaction(){
entityManager.getTransaction().commit();
}

private void failTransaction(){
entityManager.getTransaction().rollback();
}

private Employee createEmployee(String name, int age,
double salary, long primaryKey){
Employee employee = new Employee();
employee.setName(name);
employee.setAge(age);
employee.setSalary(salary);
employee.setId(primaryKey);
return employee;
}
}[/code]

For the above code to work, we have to create a persistence.xml file that contains the configurations for the EntityManager object like the database name, its URL, username/password etc inside the META-INF directory. Since it is a J2SE application we have to declare the type of transaction as Resource-Local. The following is the persistence.xml

Persistence.xml file:

[code lang=”xml”]<?xml version="1.0" encoding="UTF-8"?>
<persistence>
<persistence-unit name="EmployeePersistentUnit"
transaction-type="RESOURCE_LOCAL">
<provider>oracle.toplink.essentials.
ejb.cmp3.EntityManagerFactoryProvider</provide>
<class>
com.javabeat.ejb30.persistence.entities.Employee
</class>
<properties>
vproperty
name="toplink.jdbc.url" value="jdbc:derby://localhost:1527/sample"/>
<property
name="toplink.jdbc.user" value="app"/>
<property
name="toplink.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="toplink.jdbc.password" value="app"/>
<property name="toplink.ddl-generation"
value="drop-and-create-tables"/>
</properties>
</persistence-unit>
</persistence>[/code]

The above example uses the apache derby database for persisting the Employee objects as represented by the provider tag.

also read:

  • Introduction to JPA
  • The query api in JPA.

Filed Under: Java EE Tagged With: EJB, JPA

The Query API in JPA (EJB 3.0)

April 14, 2007 by Krishna Srinivasan Leave a Comment

Introduction

One of the disadvantage of locating the entity objects using the EntityManager.find() and EntityManager.getReference() methods is, we cannot specify any powerful search criteria for searching the entity objects. All we can provide is the primary key to request for a particular object. Another fact is the class name of entity must be known. The Query API that comes with JPA is powerful in the sense more additional criteria can be specified in the run-time during executing the query.

EntityManager serves as factory classes for getting a reference to the Query objects. The query string that we specify for locating entity objects is called Java Persistent Query Language (JPQL). The current version of the JPQL is 1.0 and it is more robust flexible and object-oriented than SQL. The persistence engine will parse the query string, transform the JPQL to the native SQL before executing it.

also read:

  • Introduction to JPA
  • Sample Application Using JPA

Types of Queries

Queries can be classified into two different types depending upon how actually the query string is defined. One is the static query (Named Query) and the other one, the Dynamic Query.

Static Query

A static query (or a named query) is one which is defined statically with the help of annotation (or XML) before the entity class. A name is usually given to the query definition so that other components in the same persistent unit can refer the query using the same.

For example,

[code lang=”java”]
@NamedQuery(name = "MobileEntity.findAll"
query = “SELECT M FROM MOBILEENTITY”)
@Entity
class MobileEntity{
}[/code]

A named query (with a name ‘Mobile.findAll’) has been defined and this query can be referenced later in the code through its name, like this.

[code lang=”java”]Query findAllQuery = entityManager.createNamedQuery
("MobileEntity.findAll");
// Execute the query.[/code]

Note that the code is referring the query by its name (‘Mobile.findAll’) by calling the createNamedQuery() method. Also, since these named queries are statically defined, during deployment time itself, the persistent engine may parse and translate the JPQL into native SQL, cache them, thereby yielding better performance.

Multiple named queries can be logically defined with the help of @NamedQueries, like this,

[code lang=”java”]@NamedQueries( {
@NamedQuery(name = "Mobile.selectAllQuery"
query = "SELECT M FROM MOBILEENTITY"),

@NamedQuery(name = "Mobile.deleteAllQuery"
query = "DELETE M FROM MOBILEENTITY")
} )[/code]

[The @NamedQueries is very similar like @NamedQuery, but can accept multiple @NamedQuery objects, The definition of the @NamedQueries looks like this,

[code lang=”java”]@interface NamedQuries{
NamedQuery[] value;
}[/code]

The way to specify arrayed elements with the definition of an annotation is by using {}. So was defined for the @NamedQueries( {…} ) and since the property called ‘value’ is the default property name for annotation, there is no need to explicitly mention the property name in the annotation definition. Following also works well which explicitly defines the property name ‘value’ for the annotation @NamedQueries.

[code lang=”java”]@NamedQueries(value = { …. } )[/code]

Dynamic Queries

Dynamic Queries are nothing but whose query strings are provided at run-time. All calls to EntityManager.createQuery(queryString) are actually creating dynamic query objects. By defining query objects in this way, we lose the efficiency and from the performance point of view, the query execution may be slow as the persistence engine has to do all the parsing and validation stuffs, along with mapping the JPQL to the SQL at the run-time.

Following code creates a dynamic query object on the fly.

[code lang=”java”]String queryString = …… // Obtained during run-time.
Query dynaQuery = entityManager.createQuery(queryString);[/code]

Static Queries will be a better choice if the scenario for which the query to be executed is well known in advance.

Query Operations

Subsequent topics cover how to work with the query API for locating the entity objects, named and the positional support for Query objects and Paging Query Results for performance.

Single Result

The following code shows how to execute a query that returns a single entity object (assuming that a table called MobileEntity with field’s model, manufacturer and imei are available in the database).

[code lang=”java”]Query singleSelectQuery = entityManager.createQuery(
"SELECT M FROM MOBILEENTITY WHERE M.IMEI = ‘ABC-123’");
MobileEntity mobileObj = singleSelectQuery.getSingleResult();[/code]

The query string that’s defined inside the createQuery() method is the Java Persistence Query Language. The Java Persistent Query Language (JPQL) resembles more like a SQL. The query statement is a simple select statement that is used to select a particular mobile object with imeiNo ‘ABC-123’. M represents a named instance row, which can be used to directly refer the fields in the corresponding table.

A call to getSingleResult() will execute the query and returns a single row that matches the search criteria in the query string. If the match wasn’t successful, then the getSingleResult() will return an EntityNotFoundException. Also, if more than one matches occur during query execution (this may not happen in our case, since imeiNo is a primary key), a run-time NonUniqueResultException will be thrown.

Multiple Results

Query.getResultList() will execute a query and may return a List object containing multiple entity instances. The following code demonstrates the same.

[code lang=”java”]Query multipleSelect = entityManager
.createQuery("SELECT M FROM MOBILE");
List mobiles =
(List)multipleSelect.getResultList();[/code]

The type-cast (List) is necessary as the getResultList() method will return a non-parameterized List object. If only one mobile object is found as a result of executing the query, then this method may simple return a list with size 1. Also note that, getResultList() method can only execute on select statements as opposed to UPDATE or DELETE statements. If any statement other than SELECT statement is passed on to the method, then an IllegalStateException will be thrown at the run-time.

Working with parameters

To reuse and to execute the query more efficiently with different set of values, one can depend on the parameter support (positional and named) offered by the JPA. These techniques resembles the one we had for the java.sql.PreparedStatement where one can prepare the statement object once and can execute the query with different set of parameter values again and again.

The positional parameter is used to bind the parameter value in terms of positional index and it is denoted by ?index within the query string. Similarly the named parameter is used to substitute the parameter value which is specified in terms of :name.

Following examples will clarify the above concepts,

[code lang=”java”]String selectQuery =
“SELECT M FROM MOBILE WHERE M.MODEL = ?1 and M.MANUFACTURER = ?2”;
Query selectQuery = entityManager.createQuery(selectQuery);

selectQuery.setParameter(1, model);
selectQuery.setParameter(2, manufacturer);[/code]

The above code illustrates the positional parameter support, during query execution,?1 and ?2 will be replaced with the values specified for model and manufacturer.

For named parameter, the parameter can be given with some meaningful name prefixed with :, like the below code,

[code lang=”java”]String selectQuery = "SELECT M FROM MOBILE WHERE M.MODEL =
:modelName and M.MANUFACTURER = :manufacturer";
Query selectQuery = entityManager.createQuery(selectQuery);

selectQuery.setParameter(“modelName”, model);
selectQuery.setParameter(“manufacturer”, manufacturer);[/code]

It is not that only dynamic queries can be benefited with positional and named parameters. Even for statically defined queries, the same is applicable. We can embed : or ? even in the static query definitions also,

[code lang=”java”]@NamedQuery(
name =
"Mobile.findByModel” query = "SELECT M FROM MOBILEENTITY WHERE
M.MODEL = :modelName
)
…[/code]

And later in code,

[code lang=”java”]Query namedQuery = entityManager.createNamedQuery("Mobile.findByModel");
namedQuery.setParameter("modelName", model);[/code]

Paging Query Results

Imagine that a select query is returning larger number of record entities, it may not be advisable to show the entire set of results to the end-user as it may eat performance. The following two methods can be used in tandem to solve this kind of performance issue.

Assume that we have 1000 mobile entities in our database and we wish to show only 100 objects in an application that displays them in a nice tabular view. In the following code, before calling the getResultList(), which will return all the mobile objects in the database, the query object is well configured with setMaxResults(maxResults) method (the number of maximum entity objects that will be returned) setFirstPosition(position) method (which tells starting position of the pointer is made to point to).

[code lang=”java”]int maxRecords = 10;
int startPosition = 0;
String queryString = “SELECT M FROM MOBILEENTITY”;

while(true){

Query selectQuery = entityManager.createQuery(queryString);
selectQuery.setMaxResults(maxRecords);
selectQuery.setFirstResult(startPosition);
List mobiles = entityManager.getResultList(queryString);

if (mobiles.isEmpty()){
break;
}

//Process the mobile entities.
process(mobiles);
entityManager.clear();

startPosition = startPosition + mobiles.size();
}[/code]

The above code loops through all the 100 objects in the database in a more efficient way. Also note that the EntityManager.clear() method is called every time, to clear (or to detach) the mobile objects which will make the EntityManager less burdened in terms of managing the mobile objects.

Flushing Query objects

JPA provides two modes of flushing query objects namely AUTO and COMMIT (which are defined in FlushModeType Enumeration). If the AUTO mode is set on the Query object which is the default one, then any changes made to entity objects will be reflected the very next time when a select query is made. That means that the persistence engine must make sure to update all the states of the entity objects which will affect the results of a SELECT query.

The AUTO flush mode can be set explicitly on the Query by calling setFlushMode().

[code lang=”java”]queryObject.setFlushMode(FlushModeType.AUTO);[/code]

When the flush mode is set to COMMIT, then the persistence engine, may only update all the state of the entities during the database COMMIT. The dirty changes applied to entity objects and then querying for the results of the entities may be unspecified.

[code lang=”java”]queryObject.setFlushMode(FlushModeType.COMMIT);[/code]

[The method setFlushMode(FlushModeType) is available in both EntityManager and Query interface. If the EntityManager has been configured with setFlushMode(FlushModeType.AUTO) and the Query object has been called with setFlushMode(FlushModeType.COMMIT), then the preference will always goes to the Query object.]

Persistent Units

Before getting into the theory of what is a persistence unit and how it has relations with EntityManagerFactory and EntityManager, let us look into a sample persistence.xml file.

[code lang=”xml”]<?xml version="1.0" encoding="UTF-8"?>
<persistence>
<persistence-unit name="EmployeePersistentUnit" transaction-type="RESOURCE_LOCAL"> <provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provide>
<class>com.javabeat.ejb30.persistence.entities.Employee</class>
<properties>
vproperty
name="toplink.jdbc.url" value="jdbc:derby://localhost:1527/sample"/>
<property
name="toplink.jdbc.user" value="app"/>
<property
name="toplink.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="toplink.jdbc.password" value="app"/>
<property name="toplink.ddl-generation" value="drop-and-create-tables"/>
</properties>
</persistence-unit>
</persistence>
[/code]

[A persistence.xml file is used to manage one or more persistence units. Like web.xml for a servlet application and ejb-jar.xml for an EJB application, this persistence.xml is a must for an entity application to run.]

At a very high-level, we can infer multiple persistence units within the same persistence.xml file being uniquely identified by its name tag. Each persistence unit is configured with a provider along with its data-source and with some set of entities. So, we can say that a persistence unit provides a logical grouping for some set of entities that share some configuration.

Imagine an application is having so many entity objects and these entity objects have been nicely categorized in a way that some set of entities are sharing a common provider (Toplink, for example), acting on some data-source, whereas other set of entities are depending on a different provider (Hibernate, for example). In such a case, we can define a persistent unit with some configuration properties for some set of entities and a different persistent unit with different set of configuration properties for the remaining entities. So a persistent unit is a way to categorize some set of entities that aimed to do some common goals and common configurations to share with.

Back to the above sample code, we have two different persistent units, one being configured to point to Toplink provider with the help oftag, and the other one pointing to a hibernate provider. We also have put some vendor specific hints (or properties) through the property tag (found within the properties tag). The meaning of toplink.ddl-generation with value drop-and-create-tables essentially tells the Toplink persistence engine that during deployment time, if already there exists a table for the corresponding class MobileEntity, just drop (delete ) the table and create it before using. Similarly the property-value pair “hibernate.hbm2ddl.auto-update” tells the persistence engine, to use the existing table and not to recreate it. Thetag represents the name of entity class that is to be included as part of this persistent unit.

Now, that we have a basic understanding about persistent units that how they are useful in categorizing entity objects, now its time to see how EntityManager and persistent units are related. In a regular J2SE application, instances of EntityManager class are obtained through EntityManagerFactory which is turn is obtained through the boot-strap class Persistence.

The following shows the sample code to achieve the same,

[code lang=”java”]String persistentUnitName = "MyMobilePersistentUnit";
EntityManagerFactoryfactory factory = Persistence
.createEntityManagerFactory(persistentUnitName);
 // Line 1

EntityManager entityManager = factory.createEntityManager();
// Line 2[/code]

In line 1, an instance of EntityManagerFactory is obtained with a call to createEntityManagerFactory() with the name of the persistent unit being passed as an argument. At this stage, we know that the persistent unit by name MyMobilePersistentUnit has been configured with Toplink as its provider along with a data source object with some additional vendor specific properties. Therefore, EntityManager objects being created for this kind of configuration from the EntityManagerFactory have this configuration for their entire life-time.

In the case of a J2EE application , one can instantiate an instance of EntityManager object backed up with @PersistentUnit like this,

[code lang=”java”]@PersistentUnit(unitName = "MyMobilePersistentUnit")
private EntityManager entityManager;[/code]

Now, the EntityManager object will have the set of configuration parameters being loaded as referenced by the persistent unit name “MyMobilePersistentUnit”.

Filed Under: Java EE Tagged With: EJB, EJB 3, JPA

  • « Previous Page
  • 1
  • …
  • 18
  • 19
  • 20
  • 21
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved