Friday, July 26, 2013

What's in .Class File

I never looked what's inside .class file except knowing that .class file consists of compiled byte code of Java Program. I was looking at quite a few articles, specifications, posts etc to get to know about byte class exact contents.
We already know what compiler does, what is a byte code, how byte code is executed by jre. Below is the brief definition.
Byte code: Java compiler (javac) generates the byte code for each Java file compiled. Byte-code is a sequence of mnemonics. Each of them will be translated by java run time environment to execute.
There are many mnemonics byte code consists of. Let's take a look at some of them with some examples which are very frequent.
Example 1:
package com.test;
public class Main
{
     public static void main(String...args)
     {
          System.out.println("Hello World");
     }
}
After compiling the Main.java, the generated class file looks like as below when you open in any hexa-decimal supported editor.




















To view the byte code in ASCII, we can use javap command.
Example: javap <class-name> displays the Class with methods in it where as -c option shows the each line of code inside the methods.












There are some basic points in the above lines of byte-code. As we know, each and every class we write, will be a sub-class of java.lang.Object ( as we can see extends java.lang.Object even we don't have that in .java file) and a default constructor is added with no parameters.
javap prints more detailed information
-s : the internal signature
-l : the line numbers and local variables used inside each function
And to print all the information, just give -verbose. Sample output looks like this

Interesting fact is, even though the java file is so simple with very few statements, compiler generated very large set of statements with tables, signatures, etc. We will see the details of few instructions in the next posts.

Thursday, July 25, 2013

Hibernate Caching - Second Level Cache

First Level Cache of hibernate (Detailed in the last post) is more specific to Session. Second Level Cache is another level where the cache is maintained in different regions across the sessions. The second level cache is divided into four regions: entity, collection, query, and timestamp.
Entity and Collection regions cache data from entities and their relations. 
The Query cache caches the result set of the database against the query. 
The Timestamp cache keeps track of last updated time of each table.
There will be on timestamp cache enabled for each query cache. The following properties to be set to enable the second level caching
hibernate.cache.use_second_level_cache = true|false
hibernate.cache.use_query_cache = true|false
hibernate.cache.region.factory_class=net.sf.ehcache.hibernate.EhCacheRegionFactory
Since Hibernate4, the factory "org.hibernate.cache.ehcache.EhCacheRegionFactory" to be used instead of "net.sf.ehcache.hibernate.EhCacheRegionFactory"
In addition to above lines, the objects to be specified with the cache strategy. The line to be specified in the hibernate hbm file in <class> tag is
<cache usage="read-write|nonstrict-read-write|read-only" />
If to be specified in Annotations on the Entity Class, use
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
How it Works

  • When we fetch an object using hibernate, it searches the object in first level cache. If found, it returns the object
  • If the object not found in first level cache, checks the second level cache. If found, stores the object in first level cache returns
  • If the entity is not found both the levels, a database query is fired and stores in both the levels and returns.
  • The second level cache validates all of its entities, if any modifications are done through hibernate APIs. But, it never know if the database object is modified by any other resource unless "timeToLiveSeconds" duration has passed 

Notes:
To view the statistics of Entity fetches, second level cache hits, etc. We need to configure explicitly as.
hibernate.generate_statistics=true|false
and using "sessionFactory.getStatistics()" which retunrs an object of Statistics type. 

Hibernate Caching - First Level Cache

Caching is one of the basic feature provided by ORM frameworks. Caching make the application to run faster by reducing number of queries to the database. Hibernate provides two levels of cache for this.
  1. First Level Cache: First level cache is associated with each session. This cache is by default and you cannot switch off this. As we can create sessions on demand, there will be first level cache associated with each session.
  2. Second Level Cache: Second level cache is associated with Session Factory. Basically, there is only one second level cache as only one Session Factory is maintained by application.
When a session is closed, the first level cache associated with it will be cleared. When a session factory is cleared, full second level cache associated with it will be lost.

Example for First level cache:

   SessionFactory sessionFactory = (SessionFactory) context.getBean("sessionFactory");
   Session session = sessionFactory.openSession();
        
   Employee emp = null;
   emp = (Employee) session.load(Employee.class, new Integer(1));
   System.out.println("Employee Name : "+emp.getName());
        
   emp = (Employee) session.load(Employee.class, new Integer(1));
   System.out.println("Employee Name : "+emp.getName());
        
   Session newSession = sessionFactory.openSession();
   emp = (Employee) newSession.load(Employee.class, new Integer(1));
   System.out.println("Employee Name : "+emp.getName());
        
   session.evict(emp);
   emp = (Employee) session.load(Employee.class, new Integer(1));
   System.out.println("Employee Name : "+emp.getName());
        
   newSession.clear();
   emp = (Employee) newSession.load(Employee.class, new Integer(1));
   System.out.println("Employee Name : "+emp.getName());
The log for the above program will be :
Hibernate: select employee0_.id as id0_0_, employee0_.age as age0_0_, employee0_.name as name0_0_ from EMP employee0_ where employee0_.id=?
Employee Name : name
Employee Name : name
Hibernate: select employee0_.id as id0_0_, employee0_.age as age0_0_, employee0_.name as name0_0_ from EMP employee0_ where employee0_.id=?
Employee Name : name
Hibernate: select employee0_.id as id0_0_, employee0_.age as age0_0_, employee0_.name as name0_0_ from EMP employee0_ where employee0_.id=?
Employee Name : name
Hibernate: select employee0_.id as id0_0_, employee0_.age as age0_0_, employee0_.name as name0_0_ from EMP employee0_ where employee0_.id=?
Employee Name : name

Explanation:
First time when load method called, the object is fetched by firing a query to database. When the second time loaded, no query was fired as the object is cached in first level cache.
Even though the object is cached by session "session", the new session "newSession" is fetched the object by firing a new query.
To clear the cache from the session, evict() or clear() method can be used. Once it's cleared, the session tries to get the object from the database. The last two queries of hibernate in the log explains that.

Notes:

  • First level cache is only associated to Session. Each session will have it's own first level cache.
  • There is no extra configuration required for first level cache. No way to switch off configuration.
  • Cache will be cleared by closing the session, by using clear() method.
  • Individual object can be removed from the cache by using evict method.

Monday, June 24, 2013

MDB Using Jboss 7

Jboss 7 architecture is completely changed compared to the previous versions. Due to this, there is a change in configuration of queues, connection factories, security etc. Here, we are not going to see how we create MDB, rather we will look at how to configure to work in Jboss7 and how to create a standalone client to send a message to Queue on Jboss7.
Jboss7 has been fully modulated, we treat each and every component of jboss7 as separate module. This has to be done in standalone.xml file. By default, we get different versions of standalone files like standalone, standalone-full etc. I prefer to use standalone.xml and add modules as required.
To enable messaging we need to add the following lines to standalone file
  • In <extensions> tag, add
<extension module="org.jboss.as.messaging"/>
  • Add sub-system in <profile>
<subsystem xmlns="urn:jboss:domain:messaging:1.1">
    <hornetq-server>
        <persistence-enabled>true</persistence-enabled>
        <journal-file-size>102400</journal-file-size>
        <journal-min-files>2</journal-min-files>

        <connectors>
            <netty-connector name="netty" socket-binding="messaging"/>
            <netty-connector name="netty-throughput" socket-binding="messaging-throughput">
                <param key="batch-delay" value="50"/>
            </netty-connector>
            <in-vm-connector name="in-vm" server-id="0"/>
        </connectors>

        <acceptors>
            <netty-acceptor name="netty" socket-binding="messaging"/>
            <netty-acceptor name="netty-throughput" socket-binding="messaging-throughput">
                <param key="batch-delay" value="50"/>
                <param key="direct-deliver" value="false"/>
            </netty-acceptor>
            <in-vm-acceptor name="in-vm" server-id="0"/>
        </acceptors>

        <security-settings>
            <security-setting match="#">
                <permission type="send" roles="guest"/>
                <permission type="consume" roles="guest"/>
                <permission type="createNonDurableQueue" roles="guest"/>
                <permission type="deleteNonDurableQueue" roles="guest"/>
            </security-setting>
        </security-settings>

        <address-settings>
            <address-setting match="#">
                <dead-letter-address>jms.queue.DLQ</dead-letter-address>
                <expiry-address>jms.queue.ExpiryQueue</expiry-address>
                <redelivery-delay>0</redelivery-delay>
                <max-size-bytes>10485760</max-size-bytes>
                <address-full-policy>BLOCK</address-full-policy>
                <message-counter-history-day-limit>10</message-counter-history-day-limit>
            </address-setting>
        </address-settings>

        <jms-connection-factories>
            <connection-factory name="InVmConnectionFactory">
                <connectors>
                    <connector-ref connector-name="in-vm"/>
                </connectors>
                <entries>
                    <entry name="java:/ConnectionFactory"/>
                </entries>
            </connection-factory>
            <connection-factory name="RemoteConnectionFactory">
                <connectors>
                    <connector-ref connector-name="netty"/>
                </connectors>
                <entries>
                    <entry name="RemoteConnectionFactory"/>
                    <entry name="java:jboss/exported/jms/RemoteConnectionFactory"/>
                </entries>
            </connection-factory>
            <pooled-connection-factory name="hornetq-ra">
                <transaction mode="xa"/>
                <connectors>
                    <connector-ref connector-name="in-vm"/>
                </connectors>
                <entries>
                    <entry name="java:/JmsXA"/>
                </entries>
            </pooled-connection-factory>
        </jms-connection-factories>

        <jms-destinations>
            <jms-queue name="MyQueue">
                <entry name="queue/MyQueue"/>
                <entry name="java:jboss/exported/jms/queue/MyQueue"/>
            </jms-queue>
        </jms-destinations>
    </hornetq-server>
</subsystem>
  • This creates a queue named MyQueue. Now i can deploy a MDB listening to the queue "MyQueue". Listener class is as follows.
@MessageDriven(activationConfig = {
  @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
  @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/MyQueue") }, mappedName = "MyQueue")
public class QueueListener implements MessageListener {

 private static final Logger logger = Logger.getLogger(QueueListener.class);

 /**
  * @see MessageListener#onMessage(Message)
  */
 public void onMessage(Message message) {
  logger.debug("Inside onMessage");
  try {
   if (message instanceof TextMessage) {

    TextMessage msg = (TextMessage) message;
    logger.info("Message : " + msg.getText());
   }
  } catch (Exception e) {
   logger.error("Exception while processing the message ", e);
  }

 }
}
  • After deploying, start the Jboss7, you will find log saying QueueListener is listening using hornetq-ra resource adapter. Now, it's time to send a message to the Queue. Here is the client which can send the message to the Queue.
public class MDBClient {
 public static void main(String... strings) {
  try {
   final Properties props = new Properties();
   props.put(Context.INITIAL_CONTEXT_FACTORY,     "org.jboss.naming.remote.client.InitialContextFactory");
   props.put(Context.PROVIDER_URL, "remote://localhost:4447");
   props.put(Context.SECURITY_PRINCIPAL, "sample");
   props.put(Context.SECURITY_CREDENTIALS, "sample123");

   InitialContext context = new InitialContext(props);
   QueueConnectionFactory factory = (QueueConnectionFactory) context     .lookup("jms/RemoteConnectionFactory");
   Queue queue = (Queue) context.lookup("jms/queue/MyQueue");
   QueueConnection cnn = factory.createQueueConnection("sample",     "sample123");
   QueueSession session = cnn.createQueueSession(false,     QueueSession.AUTO_ACKNOWLEDGE);
   QueueSender sender = session.createSender(queue);
   TextMessage message = session.createTextMessage();
   message.setText("Text Message");
   sender.send(message);
   context.close();
   cnn.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
  • Run the above code, which sends the message to Jms Queue "MyQueue". Add jboss-client.jar ($JBOSS_HOME/bin/client/jboss-client.jar) to classpath to get it running.
Points to remember
  1. Remote JNDI : A new entry added for RemoteConnectionFactory (java:jboss/exported/jms/RemoteConnectionFactory) to expose it so that it can be called looked up from remote. Same is the case for the queue (java:jboss/exported/jms/queue/MyQueue)
  2. Security: Credentials to be passed to the Context and While creating connection to connect to Queue. The credentials must be of user who belongs to group (guest). User can be setup by using adduser script in $JBOSS_HOME/bin.
  3. Off the Secutiry: We can off the security by adding <security-enabled>false</security-enabled> to the hornetq-server element
  4. Jboss-Client: jboss-client.jar which is added to Standalone client classpath.

Sunday, May 19, 2013

JAXB XML Adapter

JAXB provides XMLAdapter to change the format of default JAXB types. For example, formatting decimal places in Decimal or BigDecimal, Date formatting etc.
How to do it?
First look at the following plain vanilla example of JAXB
package com.test;

import java.math.BigDecimal;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.datatype.XMLGregorianCalendar;

@XmlRootElement
public class Loan {
	private String name;
	private Long amount;
	private XMLGregorianCalendar startDate;
	private BigDecimal interestRate;
	public String getName() {
		return name;
	}
	@XmlElement
	public void setName(String name) {
		this.name = name;
	}
	public BigDecimal getInterestRate() {
		return interestRate;
	}
	@XmlElement
	public void setInterestRate(BigDecimal interestRate) {
		this.interestRate = interestRate;
	}
	public XMLGregorianCalendar getStartDate() {
		return startDate;
	}
	@XmlElement
	public void setStartDate(XMLGregorianCalendar startDate) {
		this.startDate = startDate;
	}
	public Long getAmount() {
		return amount;
	}
	@XmlElement
	public void setAmount(Long amount) {
		this.amount = amount;
	}	
}
If we marshall the Loan object, the output is similar to
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<loan>
    <amount>200000</amount>
    <interestRate>15.6</interestRate>
    <name>Name</name>
    <startDate>2013-05-19T16:02:51.080+05:30</startDate>
</loan>
Now, format the XMLGregorianCalendar to YYYY-MM-DD in XML. For this, we need to add a new XMLAdapter which can convert(marshall) from Calendar format to String format.
package com.test;

import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.datatype.XMLGregorianCalendar;

public class CalendarAdaptor extends XmlAdapter<String, XMLGregorianCalendar> {

	@Override
	public String marshal(XMLGregorianCalendar v) throws Exception {
		return v.getYear()+"-"+v.getMonth()+"-"+v.getDay();
	}

	@Override
	public XMLGregorianCalendar unmarshal(String v) throws Exception {
		return null;
	}
}
and Add the Adapter to the property where we would like to change. So the Loan.java file will be changed at the setStartDate method to following
        @XmlJavaTypeAdapter(CalendarAdaptor.class)
	public void setStartDate(XMLGregorianCalendar startDate) {
		this.startDate = startDate;
	}
When we marshall the same Loan object now, with the above change, the xml string will be
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<loan>
    <amount>200000</amount>
    <interestRate>15.6</interestRate>
    <name>Name</name>
    <startDate>2013-5-19</startDate>
</loan>
But the thing is, we need to change each property for the class definitions to affect this change. Instead of changing the classes, we can provide this adapter change at the package level by defining a class called package-info.java without changing the individual class properties. By doing this, all the XMLGregorianCalendar attributes in the package will follow the format defined by the Adapter. package-info.java
@XmlJavaTypeAdapter(value=CalendarAdaptor.class, type=XMLGregorianCalendar.class)
package com.test;

import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;