My Quotes


When U were born , you cried and the world rejoiced
Live U'r life in such a way that when you go
THE WORLD SHOULD CRY






Sunday, January 5, 2014

Hibernate Tools and Eclipse


 
  1. In Eclipse IDE, menu bar, select “Help” >> “Install New Software …” , put the Eclipse update site URL.
  2. Copy this site's URL into Eclipse, and hit Enter.
  3. From the Abridged JBoss Tools 4.0, the JBoss Hibenate Tools section
  4. Hibernate Tools (HT) from Application Development
  5. HT from JBoss Data Services
  6. JBoss Maven Hibernate Configurator from Maven Support and
  7. HT from Web and Java EE Development
  8. After the download progress is completed, restart Eclipse to take effect.
  9. If Hibernate tools is installed properly, you are able to see the -->Hibernate Perspective--> in -->Windows--> >> -->Open Perspective--> >> -->Others-->. 
 
For generating entity files from the DB, please follow the steps in the URL
 
 

Tuesday, November 5, 2013

Hibernate – useFollowOnLocking warning


WARN  org.hibernate.loader.Loader - HHH000444: Encountered request for locking however dialect reports that database prefers locking be done in a separate select (follow-on locking); results will be locked after initial query executes

Solution
This appears to happen with Oracle and the fix is to create a custom dialect as follows

import org.hibernate.dialect.Oracle10gDialect;

public class BatchOracleDialect extends Oracle10gDialect{
          @Override
          public boolean useFollowOnLocking() {
             return false;
          }
}

Now change your hibernate.cfg.xml as follows
<property name="hibernate.dialect"><<package>>.BatchOracleDialect</property>

Thursday, October 17, 2013

Message Queue Depth


import com.ibm.mq.MQC;
import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;

public class QueueDepthTest extends ServerConfig {

 /**o
  * @param args
  */
 public static void main(String[] args) {

  QueueDepthTest classObj = null;
  try {
   classObj = new QueueDepthTest();
   final MQRegion env_region = MQRegion.DEV;
   final String queueName = MQQueueNames.CALC_REQUEST
     .getName(env_region);

   classObj.loadConfig(env_region);

   // Set up MQSeries environment
   final String mqQMgr = classObj.cf.getQueueManager();
   MQEnvironment.hostname = classObj.cf.getHostName();
   MQEnvironment.port = classObj.cf.getPort();
   MQEnvironment.channel = classObj.cf.getChannel();
   MQEnvironment.userID = classObj.cf.getClientID();

   System.out.println("******IBM MQ values*****");
   System.out.println("QMgr=" + mqQMgr);
   System.out.println("hostname=" + MQEnvironment.hostname);
   System.out.println("port=" + MQEnvironment.port);
   System.out.println("channel=" + MQEnvironment.channel);

   System.out.println("queue =" + queueName);
   final MQQueueManager qMgr = new MQQueueManager(mqQMgr);
   int openOptions = MQC.MQOO_INQUIRE;
   // int openOptions = CMQC.MQOO_INQUIRE + CMQC.MQOO_FAIL_IF_QUIESCING
   // + CMQC.MQOO_INPUT_SHARED;

   MQQueue destQueue = qMgr.accessQueue(queueName, openOptions);

   final int depth = destQueue.getCurrentDepth();
   System.out.println("printing the queue depth =" + queueName
     + " is=" + depth);
   destQueue.close();
   qMgr.disconnect();
  } catch (Exception err) {
   err.printStackTrace();
  }
 }
}


public enum MQRegion {
 DEV ("hostname", port, "channel","QMgr","ClientID");
 
 
 private String hostName;
 private long port;
 private String channel;
 private String queueManager;
 private String clientId;
 MQRegion(String hostName, int port,  String channel, String queueManager, String clientId) {
  this.hostName = hostName ;
  this.port = port;
  this.channel =channel;
  this.queueManager=queueManager;
  this.clientId = clientId;
 }
 public String getHostName() {
  return hostName;
 }
 public String getChannel() {
  return channel;
 }
 public String getQueueManager() {
  return queueManager;
 }
 public String getClientId() {
  return clientId;
 }
 public long getPort() {
  return port;
 }
}

public enum MQQueueNames {
 QUEUE_NAME("QUEUE_NAME");
 
 
 MQQueueNames(String name) {
  this.name = name;
 }

 private String name;

 public String getName(MQRegion region) {
  switch(region) {
  case DEV:
   return name + ".DEV2";
  case SIN:
   return name + ".SIN1";
  case UAT:
   return name + ".UAT3";
  }
  return name;
 }
}

import javax.jms.BytesMessage;
import javax.jms.ConnectionConsumer;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;

import com.bnym.test.common.ConstantsEnum;
import com.ibm.jms.JMSMessage;
import com.ibm.mq.MQC;
import com.ibm.mq.MQEnvironment;
import com.ibm.mq.jms.MQQueueConnectionFactory;
import com.ibm.mq.jms.MQQueueSender;
import com.ibm.mq.jms.MQQueueSession;

public class ServerConfig {

 protected MQQueueConnectionFactory cf = null;
 protected boolean needConcurrent = false;
 
 protected void loadConfig(MQRegion region) throws JMSException {
  cf = new MQQueueConnectionFactory();
  cf.setHostName(region.getHostName());
  cf.setPort((int) region.getPort());
  cf.setTransportType(1);
  cf.setQueueManager(region.getQueueManager());
  cf.setChannel(region.getChannel());
  cf.setClientId(region.getClientId());
 }
}

Tuesday, October 8, 2013

Nano seconds in Java

  1. Get backport-util-concurrent.jar from nexus
<dependency>
<groupid>backport-util-concurrent</groupid>
<artifactid>backport-util-concurrent</artifactid>
<version>3.1</version>
</dependency>
  • code snippet
   import java.util.concurrent.TimeUnit;
long timeInMillis = System.currentTimeMillis();
  • You can use query to get the DB time
select extract(day from(systimestamp - to_timestamp('1970-01-01', 'YYYY-MM-DD'))) * 86400000 + to_number(to_char(sys_extract_utc(systimestamp), 'SSSSSFF3')) current_time_milliseconds
    from dual;
  • Timestamp dbTimeStamp = result of above quey...
long nanos = TimeUnit.SECONDS.toNanos(System.currentTimeMillis());
dbTimeStamp.setNanos((int) (nanos % 1000000000));

Oracle equivalent of java currentTimeMillis


Instead of the
queryString = "SELECT systimestamp param FROM DUAL";

use the following
select extract(day from(systimestamp - to_timestamp('1970-01-01', 'YYYY-MM-DD'))) * 86400000 + to_number(to_char(sys_extract_utc(systimestamp), 'SSSSSFF3')) current_time_milliseconds
from dual;

Tuesday, September 17, 2013

Result Set Mapper for hibernate and JPA

There were times when I had to use an Entity without a primary Key in the DB.

I was trying to get it work thru the Result Set Mapper functionality which was provided for Hibernate. I had faced some issues and here are my alternatives.

Step-1
Create a transformer which extends the org.hibernate.transform.ResultTransformer
import java.lang.reflect.Field;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.PropertyNotFoundException;
import org.hibernate.property.ChainedPropertyAccessor;
import org.hibernate.property.PropertyAccessor;
import org.hibernate.property.PropertyAccessorFactory;
import org.hibernate.property.Setter;
import org.hibernate.transform.ResultTransformer;
public class AdvancedSearchResultTransformer implements ResultTransformer {
 private final Class resultClass;
 private final PropertyAccessor propertyAccessor;
 private Setter[] setters;
 private Field[] fields;

 private static final long serialVersionUID = -3489302728091710568L;

 public AdvancedSearchResultTransformer(Class resultClass) {
  if ( resultClass == null ) {
   throw new IllegalArgumentException( "resultClass cannot be null" );
  }
  this.resultClass = resultClass;
  propertyAccessor = new ChainedPropertyAccessor(
    new PropertyAccessor[] {
      PropertyAccessorFactory.getPropertyAccessor( resultClass, null ),
      PropertyAccessorFactory.getPropertyAccessor( "field" )
    }
  );
 }

 public Object transformTuple(Object[] tuple, String[] aliases) {
  Object result;
  try {
   fields = resultClass.getDeclaredFields();
   if ( setters == null ) {
    setters = new Setter[aliases.length];
    for ( int i = 0; i < aliases.length; i++ ) {
     String alias = aliases[i];
     if ( alias != null ) {
      Setter setter;
      try {
                       setter = propertyAccessor.getSetter(resultClass, alias);
                    } catch (PropertyNotFoundException e) {
                       for (Field field : this.fields) {
                          String fieldName = field.getName();
                          if (fieldName.equalsIgnoreCase(alias)) {
                             alias = fieldName;
                             break;
                          }
                       }
                       setter = propertyAccessor.getSetter(resultClass, alias);
                    }
      setters[i] = setter;
     }
    }
   }
   result = resultClass.newInstance();
   for ( int i = 0; i < aliases.length; i++ ) {
    if ( setters[i] != null ) {
     setters[i].set( result, tuple[i], null );
    }
   }
  }
  catch ( InstantiationException e ) {
   throw new HibernateException( "Could not instantiate resultclass: " + resultClass.getName() );
  }
  catch ( IllegalAccessException e ) {
   throw new HibernateException( "Could not instantiate resultclass: " + resultClass.getName() );
  }
  return result;
 }
 public List transformList(List collection) {
  return collection;
 }
 public int hashCode() {
  int result;
  result = resultClass.hashCode();
  result = 31 * result + propertyAccessor.hashCode();
  return result;
 }
}

Step-2
Look at the place where I catch the PropertyNotFoundException. There is a reason for the same

Step-3
There are 2 ways of implementing the ResultSet Transformer
Create the POJO which resembles the DB Table
Create an SQL Query as

sqlQuery.append(" SELECT column1 as col1, column2 as cl2 ");
sqlQuery.append(" FROM table tbl ");

col1 and col2 should be defined as variables (case sensitive)
private String col1;
private String col2;
in yur POJO with SETTER and GETTER methods.

If you are using Hibernate here is the way
 public List executeReadAllSQLQuery(String queryString, Object[] values,
   Object[] aliasInputs, Class transformerClass) throws ORMException {
  SQLQuery sqlQuery = null;
  try {
   sessionObj = getHibSession();
   sqlQuery = sessionObj.createSQLQuery(queryString);
   sqlQuery.setResultTransformer(new AdvancedSearchResultTransformer(transformerClass));
   if(aliasInputs != null){
    for (int i = 0; i < aliasInputs.length; i++) {
     sqlQuery.addScalar(aliasInputs[i].toString());
    }
   }
   if (values != null) {
    for (int i = 0; i < values.length; i++) {
      sqlQuery.setParameter(i, values[i]);
    }
   }
   return sqlQuery.list();
  } 


If you are using JPA mode then there is n direct way to invoke ResultSetTransformer. So what I have dne is as follows
Query sqlQuery = null;
  try {
   entityMgrObj = getHibJpaEntityManager();
   sqlQuery = entityMgrObj.createNativeQuery(queryString);
   sqlQuery.unwrap(SQLQuery.class).setResultTransformer(new AdvancedSearchResultTransformer(transformerClass));
   if(aliasInputs != null){
    for (int i = 0; i < aliasInputs.length; i++) {
     sqlQuery.unwrap(SQLQuery.class).addScalar(aliasInputs[i].toString());
    }
   }
   if (values != null) {
    for (int i = 0; i < values.length; i++) {
     sqlQuery.setParameter(i, values[i]);
    }
   }
   return sqlQuery.getResultList();
  }
Look at the place where I tweak JPA to forcibly use Hibernate ResultSet Mapper.

Thats all. Now instetad of those annoying Object[] which comes as RESULT SET, we will be able to get POJO objects just like resulr Hibernate / JPA modes.

Happy hunting.

Tuesday, July 16, 2013

Find errors in XML tags before unmarshalling






1.Create a JAXB2ValidationEventCollector-- File Atached herewith. Idealy you can put this in the same folder as that of your JAXB classes.
 2.Attach this Validator to the Unmarshaler.
 3.Now if you see any errors in the XSD with that of the field you are getting in as an XML, the Validator will spill out the same.
 4.If not assume that the XML is perfect to that of the XSD.
 5.I have tested this by manually changing the XSD.
 6.My XSD has the following
 





















1.My XML has the following EPH1035303164649
 2.I get the following 
 
msg-->cvc-length-valid: Value 'EPH1035303164649' with length = '16' is not facet-valid with respect to length '10' for type '#AnonType_ReferenceNumberOpfTriggerMessage'.

msg-->cvc-type.3.1.3: The value 'EPH1035303164649' of element 'xs:ReferenceNumber' is not valid.




XML message



   


 


 


 


  EPH1035303164649 


  


  


  




XSD











  


   


    


     


    


   


  




  


   


    


    


   


  




  


   


    


    


    


     


      


       


      


     


    


    


    


   


  


 


  


   


    


     


      


       


      


     


    


   


  





 




 Validator


import javax.xml.bind.ValidationEvent;



import javax.xml.bind.util.ValidationEventCollector;


public class JAXB2ValidationEventCollector extends ValidationEventCollector {


    @Override


    public boolean handleEvent(ValidationEvent event) {


        super.handleEvent(event);


        return true;


    }


}




Test File


import java.io.File;





import javax.xml.XMLConstants;


import javax.xml.bind.JAXBContext;


import javax.xml.bind.Unmarshaller;


import javax.xml.bind.ValidationEvent;


import javax.xml.bind.util.ValidationEventCollector;


import javax.xml.validation.Schema;


import javax.xml.validation.SchemaFactory;




import com.test.trigger.GoldenCopyTrigger;


import com.test.trigger.JAXB2ValidationEventCollector;




public class CheckXMLAgainstXSD {




  public static void main(String[] args){


   CheckXMLAgainstXSD classObj = new CheckXMLAgainstXSD();


   try {


    classObj.checkXML();


   } catch (Exception e) {


    // TODO Auto-generated catch block


    e.printStackTrace();


   }


  }


 


  private void checkXML() throws Exception{


        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 


         Schema schema = sf.newSchema(new File("C:/Data//jaxb/MilestoneTrigger.xsd")); 




         JAXBContext jc = JAXBContext.newInstance(GoldenCopyTrigger.class);




         Unmarshaller unmarshaller = jc.createUnmarshaller();


         unmarshaller.setSchema(schema);


         ValidationEventCollector validationCollector = new JAXB2ValidationEventCollector();


         unmarshaller.setEventHandler(validationCollector);




         GoldenCopyTrigger customer = (GoldenCopyTrigger) unmarshaller.unmarshal(new File("C:/Data/jaxb/sample.xml"));




         if(validationCollector.hasEvents())


         {


             for(ValidationEvent event:validationCollector.getEvents())


             {


                 String msg = event.getMessage();


                 System.out.println("msg-->"+msg);


             }


         } 


 


  }


}