Thursday, April 15, 2010

Deploying war to Tomcat using Maven

Step1: Add following in tag:


Step2: Add the username and password for the manager account in $MAVEN_HOME/conf/settings.xml file.
value in tag in step1 should be same as id in in step2


Step3: Maven command to build & deploy
        mvn clean install tomcat:deploy


to undeploy use: 
     mvn tomcat:undeploy


This does:

  • Deletes the service-war/target output folder if it already exists (same as mvn clean alone)
  • Recreates the folder and generates and compiles the Java classes into it (mvn package)
  • Creates a WAR file for the web service provider and JAR file for the JAX-WS artifacts (mvn package)
  • Installs the JAR and WAR into your local Maven repository (mvn install)
  • Undeploys the previous WAR file (tomcat:undeploy of the Maven Tomcat plugin) from Tomcat
  • Deploys the new WAR file onto Tomcat. (mvn tomcat:deploy)

Wednesday, April 14, 2010

Metro over JAX-WS

Metro has two fundamental levels:
- JAX-WS RI (that follows the JAX-WS JCP specification) - this includes JAXB
- WSIT/Tango - this provides WS-*: Security, SecureConversation, Trust, ReliableMessaging, AtomicTransactions, MEX

Unless you need the upper level WSIT features you can just use JAX-WS. JAX-WS supports SSL (it supports WS-I BSP).

If you want end-to-end message-level security then you need the WSIT/Tango layer of Metro. WSIT is intended to provide compatibility across the webservices developed in Java & .Net3.0 platforms, along with security, reliable & transaction guaranteeing features.

Hibernate Object States

Hibernate object states

* Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition).

* Persistent - a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual UPDATE statements, or DELETE statements when an object should be made transient.

* Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e., a unit of work from the point of view of the user.

Detached Objects & re-attaching them:

Many applications need to retrieve an object in one transaction, send it to the UI layer for manipulation, then save the changes in a new transaction. Applications that use this kind of approach in a high-concurrency environment usually use versioned data to ensure isolation for the "long" unit of work.

Hibernate supports this model by providing for reattachment of detached instances using the Session.update() or Session.merge() methods:
// in the first session
Cat cat = (Cat) firstSession.load(Cat.class, catId);
Cat potentialMate = new Cat();
firstSession.save(potentialMate);

// in a higher layer of the application
cat.setMate(potentialMate);

// later, in a new session
secondSession.update(cat); // update cat
secondSession.update(mate); // update mate

If the Cat with identifier catId had already been loaded by secondSession when the application tried to reattach it, an exception would have been thrown.

Use update() if you are certain that the session does not contain an already persistent instance with the same identifier. Use merge() if you want to merge your modifications at any time without consideration of the state of the session. In other words, update() is usually the first method you would call in a fresh session, ensuring that the reattachment of your detached instances is the first operation that is executed.

The application should individually update() detached instances that are reachable from the given detached instance only if it wants their state to be updated. This can be automated using transitive persistence. See Section 10.11, “Transitive persistence” for more information.

The lock() method also allows an application to reassociate an object with a new session. However, the detached instance has to be unmodified.

//just reassociate:
sess.lock(fritz, LockMode.NONE);
//do a version check, then reassociate:
sess.lock(izi, LockMode.READ);
//do a version check, using SELECT ... FOR UPDATE, then reassociate:
sess.lock(pk, LockMode.UPGRADE);

Note that lock() can be used with various LockModes. See the API documentation and the chapter on transaction handling for more information. Reattachment is not the only usecase for lock().

saveOrUpdate() method

ither saves a transient instance by generating a new identifier or updates/reattaches the detached instances associated with its current identifier.

// in the first session
Cat cat = (Cat) firstSession.load(Cat.class, catID);

// in a higher tier of the application
Cat mate = new Cat();
cat.setMate(mate);

// later, in a new session
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)

The usage and semantics of saveOrUpdate() seems to be confusing for new users. Firstly, so long as you are not trying to use instances from one session in another new session, you should not need to use update(), saveOrUpdate(), or merge(). Some whole applications will never use either of these methods.

Appropriate usage scenarios:

Usually update() or saveOrUpdate() are used in the following scenario:

* the application loads an object in the first session
* the object is passed up to the UI tier
* some modifications are made to the object
* the object is passed back down to the business logic tier
* the application persists these modifications by calling update() in a second session

saveOrUpdate() does the following:

* if the object is already persistent in this session, do nothing
* if another object associated with the session has the same identifier, throw an exception
* if the object has no identifier property, save() it
* if the object's identifier has the value assigned to a newly instantiated object, save() it
* if the object is versioned by a or , and the version property value is the same value assigned to a newly instantiated object, save() it
* otherwise update() the object

merge() is very different:

* if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance
* if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent instance
* the persistent instance is returned
* the given instance does not become associated with the session, it remains detached

Hibernate flush() - syncing ORM cache to db state

Flushing the Session


Sometimes the Session will execute the SQL statements needed to synchronize the JDBC connection's state with the state of objects held in memory. This process, called flush, occurs by default at the following points:


    *      before some query executions
    *      from org.hibernate.Transaction.commit()
    *      from Session.flush() 


The SQL statements are issued in the following order:


   1.      all entity insertions in the same order the corresponding objects were saved using Session.save()
   2.      all entity updates
   3.      all collection deletions
   4.      all collection element deletions, updates and insertions
   5.      all collection insertions
   6.      all entity deletions in the same order the corresponding objects were deleted using Session.delete() 


An exception is that objects using native ID generation are inserted when they are saved.


Except when you explicitly flush(), there are absolutely no guarantees about when the Session executes the JDBC calls, only the order in which they are executed. However, Hibernate does guarantee that the Query.list(..) will never return stale or incorrect data.


It is possible to change the default behavior so that flush occurs less frequently. The FlushMode class defines three different modes: only flush at commit time when the Hibernate Transaction API is used, flush automatically using the explained routine, or never flush unless flush() is called explicitly. The last mode is useful for long running units of work, where a Session is kept open and disconnected for a long time (see Section 11.3.2, “Extended session and automatic versioning”).


sess = sf.openSession();
Transaction tx = sess.beginTransaction();
sess.setFlushMode(FlushMode.COMMIT); // allow queries to return stale state


Cat izi = (Cat) sess.load(Cat.class, id);
izi.setName(iznizi);


// might return stale data
sess.find("from Cat as cat left outer join cat.kittens kitten");


// change to izi is not flushed!
...
tx.commit(); // flush occurs
sess.close();


During flush, an exception might occur (e.g. if a DML operation violates a constraint).

Hibernate - load() vs get()

Difference between Hibernate - load() & get() methods:

 load() takes a class object and loads the state into a newly instantiated instance of that class in a persistent state.

Cat fritz = (Cat) sess.load(Cat.class, generatedId);
&
// you need to wrap primitive identifiers
long id = 1234;
DomesticCat pk = (DomesticCat) sess.load( DomesticCat.class, new Long(id) );

load() will throw an unrecoverable exception, if there is no matching database row.
If the class is mapped with a proxy, load() just returns an uninitialized proxy and does not actually hit the database until you invoke a method of the proxy. This is useful if you wish to create an association to an object without actually loading it from the database. It also allows multiple instances to be loaded as a batch if batch-size is defined for the class mapping.

If you are not certain that a matching row exists, you should use the get() method which hits the database immediately and returns null if there is no matching row.

Cat cat = (Cat) sess.get(Cat.class, id);
if (cat==null) {
    cat = new Cat();
    sess.save(cat, id);
}
return cat;

You can even load an object using an SQL SELECT ... FOR UPDATE, using a LockMode:
Cat cat = (Cat) sess.get(Cat.class, id, LockMode.UPGRADE);

Any associated instances or contained collections will not be selected FOR UPDATE, unless you decide to specify lock or all as a cascade style for the association.

It is possible to re-load an object and all its collections at any time, using the refresh() method. This is useful when database triggers are used to initialize some of the properties of the object.

sess.save(cat);
sess.flush(); //force the SQL INSERT
sess.refresh(cat); //re-read the state (after the trigger executes)

Database BatchInsert - comparing JPA, Hibernate & Jdbc using Spring

I was trying batch inserting operation using JPA. I'm using Hibernate implementation under JPA.

Option1. Understood the vanilla JPA don't have batchInsert. But, according to Hibernate documentation, it supports insert but in specific format viz. 'INSERT INTO ... SELECT ... form is supported; not the INSERT INTO ... VALUES ... form.'
So, I tried the following:
public int batchInsertMessageList(List customerList) {
final String jpaQuery = "insert into Customer (tm.getCustomerId(),tm.getAddress()) " +
"select :tm tm from dual";
final Object[] customerArray = customerList.toArray();
Object ret = getJpaTemplate().execute( new JpaCallback() {
           public Object doInJpa(EntityManager em) throws PersistenceException {
               Query query = em.createQuery(jpaQuery);
               if (customerArray != null && customerArray.length > 0) {
                   for (Object obj : customerArray) {
                       //query.setParameter(parameterIndex++, obj);
                    query.setParameter("tm", obj);
                   }
               }
               return query.executeUpdate();
           }
       });
return (Integer) ret;
}


I'm using Hibernate jars in version 3.3. Unfortunately, it is giving following exception:
query must begin with SELECT or FROM: insert [insert into Customer (tm) select :tm tm from dual]; nested exception is java.lang.IllegalArgumentException: org.hibernate.QueryException: query must begin with SELECT or FROM: insert [insert into Customer (tm) select :tm tm from dual]

If ever there is an error in my query, I cannot solve it to make work, as Hibernate says it don't support.

Option2:
I'm going for option2, directly updating using getJdbcTemplate(). This would deliver better performance :) but my deviation from JPA :(


Option3:
Using Hibernate directly as below:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

for ( int i=0; i<100000; i++ ) {
   Customer customer = new Customer(.....);
   session.save(customer);
   if ( i % 20 == 0 ) { //20, same as the JDBC batch size
       //flush a batch of inserts and release memory: to avoid OutOfMemoryException
       session.flush();
       session.clear();
   }
}

cURL commandline utility

A command line tool for getting or sending files using URL syntax.

Since cURL uses libcurl, it supports a range of common Internet protocols, currently including HTTP, HTTPS, FTP, FTPS, SCP, SFTP, TFTP, LDAP, LDAPS, DICT, TELNET, FILE, IMAP. POP3, SMTP and RTSP.

The name of the project is a play on 'Client for URLs', originally with URL spelled in uppercase to make it obvious it deals with URLs. The fact it can also be pronounced 'see URL' also helped; it works as an abbreviation for "Client URL Request Library" or the recursive version: "Curl URL Request Library". Distributed under the MIT License, cURL is free software.

Basic use of cURL involves simply typing curl at the command line, followed by the URL of the output to retrieve.

To retrieve the example.com homepage, type:

curl http://www.google.com.au

cURL defaults to displaying the output it retrieves to the standard output specified on the system (usually the terminal window). So running the command above would display the source-code of the google.com.au homepage.

cURL can write the output it retrieves to a file with the -o flag, thus:

curl -o example.html www.example.com

A practical example is the cURL for testing the twitter api like posting the tweet (status) as below:
curl -u username:password http://api.twitter.com/1/direct_messages.xml

Quickest way to download files:
eg: curl -o j2ee-6.pdf http://java.sun.com/javaee/6/docs/tutorial/doc/JavaEETutorial.pdf
PS: this is indeed a good doc ;)

FastInfoset (FI) - 'binary' webservice

The key idea is that the speed of marshalling and unmarshalling content can be improved by moving away from a textual markup language to a binary one. It aims to provide more efficient serialization than the text-based XML format. In short, it adopts concept of Binary XML.

This is done at the expense of human readability or accessibility. No longer can you look at messages through a logging proxy server. No longer can you write normative 'correct' requests and responses to XML files in your SCM repository, run ant's over them and check that your XSD matches expectations.

As such, it is firmly in the camp of XML is a detail end users don't need to care about, which is not far behind WSDL and XSD are things the toolkit handles for you. It is also not XML, not in its classic sense.

One can think of FI as gzip for XML, though FI aims to optimize both document size and processing performance, whereas gzip optimizes only the size. While the original formatting is lost, no information is lost in the conversion from XML to FI and back to XML.

Between nodes that support it, FastInfoset may deliver tangible speedups through improvements in parse time. This may be at the expense of flexibility, but if the endpoint is written in a contract-last form, there is usually little flexibility in there anyway. Few Java methods are set up to deal with arbitrary amounts of incoming XML content, especially in unknown schemas, so will not be any less flexible by adopting FastInfoset.

Concerns & Facts:
There are no intellectual property restrictions on its implementation and use.

A common misconception is that FI requires ASN.1 tool support. Although the formal specification uses ASN.1 formalisms, ASN.1 tools are not required by implementations.

The other issue with FastInfoset is security. Whoever implements the parser had better design it to resist malicious content.

Genuine sacrifice would human readability and xml schema validation.

Reference Implementation

A Java implementation of the FI specification [http://fi.dev.java.net/] is available as part of the GlassFish project. The library is open source and is distributed under the terms of the Apache License 2.0. Several projects use this implementation, including the reference implementation for JAX-RPC and JAX-WS

About Performance
In addition to a significant reduction in document size of Fast Infoset with respect to standard XML 1.0, SAX-type parsing performance of Fast Infoset is much greater than parsing performance of XML 1.0. Typical increases in parsing speed observed for the reference Java implementation are a factor of 10 compared to Java Xerces, and a factor of 4 compared to the Piccolo driver (one of the fastest Java-based XML parsers)

Typical Applications

* Portable Devices - With mobile devices typically having access to low bandwidth data connections, and have slower CPUs. This can make Fast Infoset a better choice, lowering both data transmission and data processing times.

Persisting Large Volumes of Data - When persisting XML either to file or a database, the volume of data your system produces can often get out of hand. This has a number of detrimental effects; the access times go up as you're reading more data, CPU load goes up as XML data takes more effort to process, and your storage costs go up. By persisting your XML data in Fast Infoset format, it is possible to reduce the data volume by up to 80 percent.

Passing XML via the internet - As soon as an application starts passing information over the internet, one of the main bottlenecks is bandwidth. If you send reasonable chunks of data, this bottleneck can seriously degrade the performance of your client applications and limit your server's ability to process requests. Reducing the amount of data moving across the internet reduces the time it takes a message to be sent or received, while increasing the number of transactions a server can process per hour.

Supporting Java WS Stacks:
Metro, Axis2 & CXF

Monday, April 12, 2010

JMS - a quick walk-thru of concepts

Java Message Service is an asynchronous communication mechanism in the distributed system field. JMS  API is a Java Message Oriented Middleware (MOM) API for sending messages between two or more clients. It is very helpful in the situation where the distributed components are loosely coupled. Another popular distributed communication technology is Remote Method Invocation (RMI), which is tightly coupled and requires an application to know a remote application's methods. Java Message Service Specification 

Characteristics of JMS
1. Messages can be consumes sync or async
2. Consumers can filter which message they receive
3. Messages are placed in Destination in sent order
4. Message consumption order cannot be guaranteed

Elements
·      Connection
·      Session
·      Message Producer & Message Consumer
·      Destination
·      Message


Message Models
  • Point-to-Point or P2P (Queuing Model) &
  • Publisher-Subscriber or Pub-Sub (eg: Topic)

 JMS queue




A staging area that contains messages that have been sent and are waiting to be read. Note that, contrary to what the name queue suggests, messages don't have to be delivered in the order sent. If the message driven bean pool contains more than one instance then messages can be processed concurrently and thus it is possible that a later message is processed sooner than an earlier one. A JMS queue only guarantees that each message is processed only once.

JMS topic





A distribution mechanism for publishing messages that are delivered to multiple subscribers. A good analogy for this is an anonymous bulletin board.


Programming

Queue vs Topic



JMS as Administered Object 
It is recommended to use JNDI lookups. This promotes loose-coupling - an important aspect of SOA.


 
Steps involved:



Reliable Messaging done thru use of:
  1. Persistent Message Store and
  2. Acknowledgement or Transaction

Open source JMS Providers

Java Message Service is an asynchronous communication mechanism in the distributed system field. It is very helpful in the situation where the distributed components are loosely coupled. Another popular distributed communication technology is Remote Method Invocation (RMI), which is tightly coupled and requires an application to know a remote application's methods.
Java Message Service Specification

Technical Expectations:
1. Provision for Routing and delivery service
2. Support for Point-to-Point or P2P (Queue) & Publisher-Subscriber or Pub-Sub (Topics) patterns
3. Sync & Async message receipt
4. Reliability assurance
5. Built in support for common existing message formats
There are many open source JMS providers in market and they normally fulfill the above. So decision is difficult.
 I'm planning for a JMS implementation and the following are my choices. Finally, I went with ActiveMQ as reviews shows it is faster and reliable compared to the peers. Similarly good one, which I keep as alternative, is OpenMQ. Anyway, lets walk thru the list.

Apache ActiveMQ
 An open source (Apache 2.0 licensed) message broker which fully implements the Java Message Service 1.1 (JMS). It provides "Enterprise Features" like clustering, multiple message stores, and ability to use any database as a JMS persistence provider besides VM, cache, and journal persistency.
Used in ESBs like Mule and often used with Apache CXF in SOA infrastructure projects.
Integrates seamlessly into Geronimo, light weight containers and any Java application.
Apache ActiveMQ - Features
License: Apache 2.0

Open Message Queue
OpenMQ is an open source message-oriented middleware project by Sun Microsystems that implements the Java Message Service 1.1 API (JMS). In addition to support for the JMS API, OpenMQ provides additional enterprise features including clustering for scalability and high availability, a C API, and a full JMX administration API. It also includes an implementation of the Java EE Connector Architecture (JCA) called the JMSRA, that allows OpenMQ to be used by a Java EE compliant application server. OpenMQ is the default JMS provider integrated into GlassFish.
License: CCDL & GPL
Developer tips
Latest release

JBoss Messaging
JBoss/Messaging is a re-implementation of JBossMQ. Fully compatible JMS1.1 implementation. Performance characteristics to exceed JBossMQ's. One of the project tasks is to build a benchmarking infrastructure that will allow tracking of the performance metrics evolution in time, between versions, as well as comparison with equivalent metrics of similar products. High availability features, such as distributed destinations, in-memory replication of the messages and transparent client fail over. Standard JMS API to JGroups. Serverless JMS design.
On 24 August 2008, HornetQ was launched, based on the JBoss Messaging 2.0 code-base, and the JBoss Messaging project was put into bug fix mode only by JBoss.
License: LGPL


UberMQ
 is a clean-room implementation of the JMS 1.1 API (topics and queues), based on Java NIO for speed and scalability. It supports TCP, SSL and LRMP multicast connectivity, and is highly pluggable so you can customize various aspects to your needs.
Download

MantaRay
 is an Open Source serverless messaging fabric, based on peer-2-peer technology, and 100% pure Java. Features include: - Publish/subscribe (topic) and Point-to-point (queue) messaging services - Support for JMS 1.1 and 1.02 - Automatic discovery - Guaranteed message delivery - Persistent/non-persistent and durable messages - Security - Transactions support - Message filtering using selectors - Integration with WebLogic and WebSphere - TCP, UDP and HTTP transport protocols
License: GPL

Somnifugi
 is an implementation of JMS that works inside a single JVM to send JMS Messages between Threads.
License:  BSD License

HermesJMS
 is an extensible console that helps you interact with JMS providers making it easy to browse or seach queues and topics, copy messages around and delete them. It fully integrates with JNDI letting you discover administered objects stored, create JMS sessions from the connection factories and use any destinations found.
License: Apache Software License

JORAM
JORAM incorporates a 100% pure Java implementation of JMS 1.1  (Java Message Service API released by Sun Microsystem, Inc.) specification.
It provides access to a really distributed MOM (Message Oriented Middleware), built on top of the ScalAgent D.T. agents based platform.
License:    LGPL license

Open JMS
OpenJMS is an open source implementation of Sun Microsystems's Java Message Service API 1.0.2 Specification. Features include:
 * Point-to-Point and publish-subscribe messaging models
 * Guaranteed delivery of messages
 * Synchronous and asynchronous message delivery
 * Persistence using JDBC
 * Local transactions
 * Message filtering using SQL92-like selectors
 * Authentication
 * Administration GUI
 * XML-based configuration files
 * In-memory and database garbage collection
 * Automatic client disconnection detection
 * Applet support
 * Integrates with Servlet containers such as Jakarta Tomcat
 * Support for RMI, TCP, HTTP and SSL protocol stacks
 * Support for large numbers of destinations and subscribers
OpenJMS is not dependent on any given application server and therefore can be a common interface between users of different vendors.
Issue: License & still in beta phase

Reasons for my Choice with Tomcat based app: (reason from googl-ing, yet to implement)
Its generally the easiest to embed in a JVM/Tomcat, has the most features and is the fastest open source JMS server.
ActiveMQ integrates cleanly with Tomcat, JNDI and Spring.
 Useful resources:
http://activemq.org/Tomcat
http://activemq.org/JNDI+Support
http://activemq.org/Spring+Support


Vanilla flavour-ed Project - using Maven

Like the "generic" flavour of yummy vanilla in foods (especiallly ice-creams), the Maven creates you "generic" project structure. The 'recipe' is hereunder:

Step1:
mvn archetype:create \
-DarchetypeGroupId=org.apache.maven.archetypes \
-DgroupId=com.test \
-DartifactId=VanillaProject


This creates a project "VanillaProject" with pom.xml (as below) and class App.java in package com.test & a JUnit testcase for the class.


  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  4.0.0
  com.test
  VanillaProject
  jar
  1.0-SNAPSHOT
  VanillaProject
  http://maven.apache.org
 
   
      junit
      junit
      3.8.1
      test
   

 


With  Project Folder structure: 
 Step 2:
 App.java (modified with System.out.println):

package com.test;
public class App
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        if(args!=null)
        System.out.println( args[0]+"::"+args[1] );
    }


2. Run the pom.xml to compile & test
mvn install

3. This compiles to get App.class. Now, run the class file

mvn exec:java -Dexec.mainClass="com.test.App" -Dexec.args="Arg0 Arg1"

Friday, April 9, 2010

While creating Metro client for a basic authenticated webservice

I was facing with an issue creating the Metro client for a webservice - secured with plain text username & password.
Issue:
     Header was not appearing the Soap Request
Error logged:
    Apr 9, 2010 3:49:57 PM [com.sun.xml.ws.policy.EffectiveAlternativeSelector]  doSelection
    WARNING: WSP0075: Policy assertion "{http://www.bea.com/wls90/security/policy}Identity" was evaluated as "UNKNOWN".
    Apr 9, 2010 3:49:57 PM [com.sun.xml.ws.policy.EffectiveAlternativeSelector]  doSelection
    WARNING: WSP0019: Suboptimal policy alternative selected on the client side with fitness "UNKNOWN".
    ..
    ..
    javax.xml.ws.soap.SOAPFaultException: No Security header in message but required by policy.
    ..


The Workarounds:
 1. Adding the Username & Password in BindingProvider.USERNAME_PROPERTY in RequestContext. It sets value for "javax.xml.ws.security.auth.username(password)". The BindingProvider interface provides access to the protocol binding and associated context objects for request and response message processing. Eventually, the username and password has to be added in the form of an HTTP Basic Authentication header. (List of javax.xml constants)
    Result: didn't work


2. XWSSConstants.USERNAME_PROPERTY in RequestContext
    Result: didn't work (for my app)


3. Programmatically added the header ;)
    Result:    it worked :)

Here is how I did it - explained:

    Click here to Enlarge

Code - For copy & paste
try {
            SOAPFactory soapFactory = SOAPFactory.newInstance();
            String SECURITY_NAMESPACE = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
            QName securityQName = new QName(SECURITY_NAMESPACE, "Security");
            SOAPElement security = soapFactory.createElement(securityQName);
            QName usernameTokenQName = new QName(SECURITY_NAMESPACE, "UsernameToken");
            SOAPElement usernameToken = soapFactory.createElement(usernameTokenQName);
            QName usernameQName = new QName(SECURITY_NAMESPACE, "Username");
            SOAPElement username = soapFactory.createElement(usernameQName);
            username.addTextNode("username");
            QName passwordQName = new QName(SECURITY_NAMESPACE, "Password");
            SOAPElement password = soapFactory.createElement(passwordQName);
            password.addTextNode("password");
            usernameToken.addChildElement(username);
            usernameToken.addChildElement(password);
            security.addChildElement(usernameToken);
            Header header = Headers.create(security);
            ((WSBindingProvider) port).setOutboundHeaders(header);
        } catch (SOAPException e) {
            System.out.println("Failed adding the security token to header");
            e.printStackTrace();
        }


Misc:

Beyond Compare for Linux - Wow!

Comparing file in Linux wasn't so easy (compared to the softwares available in Windows). Guys used to simulate the software like BeyondCompare using wine. Now, no longer do so...

The BeyondCompare for Linux is released in its version 3.
Available for download

Another good tool is KDiff - it is free!

Thursday, April 8, 2010

Glassfish plugin for Eclipse

Glassfish has come as an plugin for Eclipse - bringing with it a lot of ease enjoyed by NetBeans IDE users

Steps:
1. In Eclipse, menu ->   -> drop-drop,
    a. Check if software site "https://ajax.dev.java.net/eclipse" exists?
        If not, add it thru preferences link (below it).
    b. it would show as below:


 2. Select 'Glassfish JEE5, Java' and click 'next'
 3. Accept the 'Terms & conditions'
 4. In Progress:


5. Now, In servers tab -> , we can find the Glassfish servers as below:


 Also, in context menu, as below:




Misc Reference:
Creating JAX-WS using Metro plugin for Eclipse 

Tuesday, April 6, 2010

Web project - folder structure

 
Figure 2.1: Web Applications: Recommended Directory Structure

Web Deployment Descriptor
web.xml file
JavaSource (or src/java)
Contains the project's Java source code for classes, beans, and servlets. When these resources are added to a Web project, they are automatically compiled and the generated files are added to the WEB-INF/classes directory. The contents of the source directory are not packaged in WAR files unless an option is specified when a WAR file is created.
imported_classes folder
This folder may be created during a WAR import, and contains class files that do not have accompanying source. The imported_classes folder is a Java classes folder; Java classes folders can also be created using the Web project Java Build Path properties page.
WebContent (or web) folder
The mandatory location of all Web resources, including HTML, JSP, graphic files, and so on. If the files are not placed in this directory (or in a subdirectory structure under this directory), the files will not be available when the application is executed on a server. The Web content folder represents the contents of the WAR file that will be deployed to the server. Any files not under the Web content folder are considered development-time resources (for example, .java files, .sql files, and .mif files), and are not deployed when the project is unit tested or published.
META-INF
This directory contains the MANIFEST.MF file, which is used to map class paths for dependent JAR files that exist in other projects in the same Enterprise Application project. An entry in this file will update the run-time project class path and Java build settings to include the referenced JAR files.
theme
The suggested directory for cascading style sheets (css) and other style-related objects.
WEB-INF
Based on the Sun Microsystems Java Servlet 2.3 Specification, this directory contains the supporting Web resources for a Web application, including the web.xml file and the classes and lib directories.
/classes
This directory is for servlets, utility classes, and the Java compiler output directory. The classes in this directory are used by the application class loader to load the classes. Folders in this directory will map package and class names, as in: /WEB-INF/classes/com/mycorp/servlets/MyServlet.class.This is generated while a build happens. Do not place any .class files directly into this directory. The .class files are placed in this directory automatically when the Java compiler compiles Java source files that are in the Java Resources directory. Any files placed directly in this directory will be deleted by the Java compiler when it runs.
/lib
The supporting JAR files that your Web application references. Any classes in .jar files placed in this directory will be available for your Web application. In short, jar's file would be in classpath.
Libraries
The supporting JAR files that your Web application references. This folder mirrors the content of the lib folder. In addition, Web Library Projects, which are "virtual" JAR files that do not physically reside in the Web project, but are associated with Java projects elsewhere in your workspace, are included in this folder. They are packaged with your project when you export the application's WAR file.
 A library entry on the Java build path will remain there unless the actual JAR file is deleted from the WEB-INF/lib folder. If you remove a library path entry but not the JAR file, the library entry will be re-added to the path automatically.

[Ultimate Reference: http://java.sun.com/blueprints/code/projectconventions.html ]

Thursday, April 1, 2010

Quartz - driving the enterprise 'chronometer'

 A job scheduler is a system that is responsible for executing (or notifying) other software components when a pre-determined (scheduled) time arrives.

Quartz is a full-featured, open source job scheduling system that can be integrated with, or used along side virtually any J2EE or J2SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components or EJBs. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering.

 What Can Quartz Do For You?

If your application has tasks that need to occur at given moments in time, or if your system has recurring maintenance jobs then Quartz may be your ideal solution.
Sample uses of job scheduling with Quartz:
  • Driving Process Workflow: As a new order is initially placed, schedule a Job to fire in exactly 2 hours, that will check the status of that order, and trigger a warning notification if an order confirmation message has not yet been received for the order, as well as changing the order's status to 'awaiting intervention'.
  • System Maintenance: Schedule a job to dump the contents of a database into an XML file every business day (all weekdays except holidays) at 11:30 PM.
  • Providing reminder services within an application.

Quartz is distributed as a small java library (.jar file) that contains all of the core Quartz functionality. The main interface (API) to this functionality is the Scheduler interface. It provides simple operations such as scheduling/unscheduling jobs, starting/stopping/pausing the scheduler.

Quartz vs. java.util.Timer
  1. Timers have no persistence mechanism.
  2. Timers have inflexible scheduling (only able to set start-time & repeat interval, nothing based on dates, time of day, etc.)
  3. Timers don't utilize a thread-pool (one thread per timer)
  4. Timers have no real management schemes - you'd have to write your own mechanism for being able to remember, organize and retreive your tasks by name, etc.
Runtime environment
  • Quartz can run embedded within another free standing application
  • Quartz can be instantiated within an application server (or servlet container), and participate in XA transactions
  • Quartz can run as a stand-alone program (within its own Java Virtual Machine), to be used via RMI
  • Quartz can be instantiated as a cluster of stand-alone programs (with load-balance and fail-over capabilities)
Job Execution
  • Jobs can be any Java class that implements the simple Job interface, leaving infinite possibilities for the work your Jobs can perform.
  • Job class instances can be instantiated by Quartz, or by your application's framework.
  • When a Trigger occurs, the scheduler notifies zero or more Java objects implementing the JobListener and TriggerListener interfaces (listeners can be simple Java objects, or EJBs, or JMS publishers, etc.). These listeners are also notified after the Job has executed.
  • As Jobs are completed, they return a JobCompletionCode which informs the scheduler of success or failure. The JobCompletionCode can also instruct the scheduler of any actions it should take based on the success/fail code - such as immediate re-execution of the Job.
Job Persistence
  • The design of Quartz includes a JobStore interface that can be implemented to provide various mechanisms for the storage of jobs.
  • With the use of the included JDBCJobStore, all Jobs and Triggers configured as "non-volatile" are stored in a relational database via JDBC.
  • With the use of the included RAMJobStore, all Jobs and Triggers are stored in RAM and therefore do not persist between program executions - but this has the advantage of not requiring an external database.
 [ For more on features refer: http://www.quartz-scheduler.org/overview/features.html]

Few factors affecting Performance
  • RAM-based JobStore is MUCH (1000x) faster than the JDBC-based JobStore.
  • Limiting factor of the number of Triggers and Jobs Quartz can "store" and monitor is really the amount of storage space available to the JobStore (either the amount of RAM or the amount of disk space)
  • Actual number of jobs that can be running at any moment in time is limitted by the size of the thread pool

Types of Triggers
  • SimpleTrigger ALWAYS fires exacly every N seconds, with no relation to the time of day.
  • CronTrigger ALWAYS fires at a given time of day and then computes its next time to fire. If that time does not occur on a given day, the trigger will be skipped. If the time occurs twice in a given day, it only fires once, because after firing on that time the first time, it computes the next time of day to fire on.
Scheduling using Quartz
Quartz Implementation with Spring

The Quartz, as we saw above, would be used for 'timing' enterprise activities. This means it would call certain method(s) at certain interval (or certain point of time in a day, month or so). This methods of the particular class & Quartz in general can be wired using Spring IoC.

Example application context xml here under:

HelloClass would be a java class with a method printHallo() (containing System.out.println("Hello mate!"); ).
Misc: