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






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);


             }


         } 


 


  }


}

Thursday, April 18, 2013

Manage a composite primary key with an incremental id using JPA and Oracle


The regular way of doing this is to  have a Composite Key Class and mapping the field to use oracle sequence. In most of the scenarios this will fail.
The alternative is to 
1. Create the Composite Primary key as a regular java POJO with no @Column mappings.
2.Create/Override the equals() and hashCode() methods in this class.
3. Now go to the main POJO and instead of defining this composite key as @EmbeddedId, declare the composite primary key attributes your entity, associate the ID class with the entity and define the ID generation strategy,
o   @Id
o   @Column mappings
o   and for the sequence number field alone add like the following
  @Column(name="<>")   @GeneratedValue(strategy=GenerationType.AUTO, generator="<>")   @SequenceGenerator(name="<>", sequenceName="<>") 4.When you create the records, you don’t need to set this field at all. 5. DB will generate the sequence for you. 6.It’s a known defect from JPA that composite keys cannot accept sequence numbers  

Get DB Date and Time Hibernate / JPA



1.If you fire the query " SELECT sysdate param FROM dual;" (or) " SELECT systimestamp param FROM dual;"Hibernate will complain " org.hibernate.MappingException: No Dialect mapping for JDBC type: -101". Not sure of the JPA error
2.To address this, you need to ensure that Hibernate is educated to identify the sysdate (or) systimestamp as a registered field
3.The only way to do this is to addScalar to the SQLQuery
4.But here again if you say addScalar("param",Hibernate.TIMESTAMP), Type fields in org.hibernate.Hibernate are deprecated (and actually removed) as result of HHH-5196
5.So the other way is to say as follows
6.sqlQuery.addScalar("param", org.hibernate.type.TimestampType.INSTANCE);
7.Now that this is done for Hibernate, I was wondering the alternative for JPA.
8.So the thIrd hack was to hack the JPA Entity Manager to use Hibernate scalar as follows
9.query = entityMgrObj.createNativeQuery(queryString);
10.query.unwrap(SQLQuery.class).addScalar("param", org.hibernate.type.TimestampType.INSTANCE);


So here we go





For hibernate

  /**


  * public method to get the database Date and Time


  */


  public Timestamp getCurrentDBTime() throws ORMException { 


   SQLQuery sqlQuery = null;


   String queryString=null;


   Timestamp dbTimeStamp = null;


   try {


    queryString = "SELECT systimestamp param FROM DUAL";


    sessionObj = getHibSession();   


    sqlQuery = sessionObj.createSQLQuery(queryString);


    sqlQuery.addScalar("param", org.hibernate.type.TimestampType.INSTANCE);


    dbTimeStamp = (Timestamp)sqlQuery.uniqueResult(); 


    return dbTimeStamp;


   } catch (HibernateException ex) {


    throw new ORMException(ex, IORMErrorCode.LQM_ORM_E_GETCURRENT_DATE_TIME);


   } catch (RuntimeException ex) {


    throw new ORMException(ex, IORMErrorCode.LQM_ORM_E_GEN_EXCEPTION);


   } finally {


    if (sessionObj != null) {


     sessionObj.close();


    }


   }


   


  }


  /**


  * public method to get the database Date


  */




  public Date getCurrentDBDate() throws ORMException {


   SQLQuery sqlQuery = null;


   String queryString=null;


   Date dbDate = null;


   try {


    queryString = "SELECT sysdate param FROM DUAL";


    sessionObj = getHibSession();   


    sqlQuery = sessionObj.createSQLQuery(queryString);


    sqlQuery.addScalar("param", org.hibernate.type.DateType.INSTANCE);


    dbDate = (Date)sqlQuery.uniqueResult(); 


    return dbDate;


   } catch (HibernateException ex) {


    throw new ORMException(ex, IORMErrorCode.LQM_ORM_E_GETCURRENT_DATE_TIME);


   } catch (RuntimeException ex) {


    throw new ORMException(ex, IORMErrorCode.LQM_ORM_E_GEN_EXCEPTION);


   } finally {


    if (sessionObj != null) {


     sessionObj.close();


    }


   }


  }






For JPA





  /**


  * public method to get the database Date and Time


  */


  public Timestamp getCurrentDBTime() throws ORMException {


   Timestamp dbTimeStamp = null;


   String queryString=null;


   Query query = null;


   try {


    queryString = "SELECT systimestamp param FROM DUAL";


    entityMgrObj = getHibJpaEntityManager();


    query = entityMgrObj.createNativeQuery(queryString);


    query.unwrap(SQLQuery.class).addScalar("param", org.hibernate.type.TimestampType.INSTANCE);


    dbTimeStamp = (Timestamp)query.getSingleResult();


    return dbTimeStamp;


   } catch (HibernateException ex) {


    throw new ORMException(ex, IORMErrorCode.LQM_ORM_E_GETCURRENT_DATE_TIME);


   } catch (RuntimeException ex) {


    throw new ORMException(ex, IORMErrorCode.LQM_ORM_E_GEN_EXCEPTION);


   } 


  


  }


  /**


  * public method to get the database Date


  */


  public Date getCurrentDBDate() throws ORMException {


   Date dbDate = null;


   String queryString=null;


   Query query = null;


   try {


    queryString = "SELECT sysdate param FROM DUAL";


    entityMgrObj = getHibJpaEntityManager();


    query = entityMgrObj.createNativeQuery(queryString);


    query.unwrap(SQLQuery.class).addScalar("param", org.hibernate.type.DateType.INSTANCE);


    dbDate = (Date)query.getSingleResult();


    return dbDate;


   } catch (HibernateException ex) {


    throw new ORMException(ex, IORMErrorCode.LQM_ORM_E_GETCURRENT_DATE_TIME);


   } catch (RuntimeException ex) {


    throw new ORMException(ex, IORMErrorCode.LQM_ORM_E_GEN_EXCEPTION);


   } 


  


  }


setting schema information


schema names in hibernate can be painful but not with the latest releases

Refer to the following URL and you will get useful information of setting the schema names for the application at different levels


  1. Global Level
  2. Entity Level
  3. Property Level and
  4. Association Level

For JPA rather than doing it in every ENTITY class
just create the orm.xml with the following contents

<?xml version="1.0" encoding="UTF-8" ?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm    
    http://java.sun.com/xml/ns/persistence/orm_1_0.xsd"
    version="1.0">
    <persistence-unit-metadata>
        <persistence-unit-defaults>
            <schema>mySchema</schema>
        </persistence-unit-defaults>
    </persistence-unit-metadata>
</entity-mappings>

Make sure that you refer this from the persistence.xml as follows

<persistence-unit>
<mapping-file>META-INF/orm.xml</mapping-file>
</persistence-unit>


Speed up Spring loading

add the following to the web.xml

 metadata-complete="true"

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="true">

and you will see the difference in Spring performance

Thursday, April 4, 2013

Useful Debugging parameters for Hibernate via Log4j

### Hibernate logging configuration ### 

### Log everything (a lot of information, but very useful for troubleshooting) ### 
#log4j.logger.org.hibernate=info 

### Log HQL and SQL ASTs during query parsing ### 
log4j.logger.org.hibernate.hql.ast.AST=DEBUG, SQL_APPENDER 
log4j.additivity.org.hibernate.hql.ast.AST=false 

### log just the SQL 
log4j.logger.org.hibernate.SQL=DEBUG, SQL_APPENDER 
log4j.additivity.org.hibernate.SQL=false 

### log JDBC bind parameters. Very userfull, when debug parameterized queries ### 
log4j.logger.org.hibernate.type=TRACE, SQL_APPENDER 
log4j.additivity.org.hibernate.type=false 

### log schema export/update ### 
#log4j.logger.org.hibernate.tool.hbm2ddl=info 

### log HQL parse trees 
#log4j.logger.org.hibernate.hql=debug 

### log cache activity ### 
#log4j.logger.org.hibernate.cache=info 

### log transaction activity 
#log4j.logger.org.hibernate.transaction=debug 

### Log all JDBC resource acquisition 
#log4j.logger.org.hibernate.jdbc=debug 

### enable the following line if you want to track down connection ### 
### leakages when using DriverManagerConnectionProvider ### 
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace 

log4j.appender.SQL_APPENDER=org.apache.log4j.RollingFileAppender 
log4j.appender.SQL_APPENDER.File=c\:/EC_sql.log
log4j.appender.SQL_APPENDER.MaxFileSize=1000KB 
log4j.appender.SQL_APPENDER.MaxBackupIndex=62 
log4j.appender.SQL_APPENDER.layout=org.apache.log4j.PatternLayout 
log4j.appender.SQL_APPENDER.layout.ConversionPattern=[%d] %5p [%t] (%F:%L) - %m%n

Validate XML String against an XSD


JAXBContext jc = JAXBContext.newInstance(<<You class>>);
JAXBSource source = new JAXBSource(jc, <<your class object>>);
 
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
Schema schema = sf.newSchema(new File("<<your XSD>>")); 
 
Validator validator = schema.newValidator();
validator.setErrorHandler(new MyErrorHandler());
validator.validate(source);
 
 
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
 
public class MyErrorHandler implements ErrorHandler {
 
    public void warning(SAXParseException exception) throws SAXException {
        System.out.println("\nWARNING");
        exception.printStackTrace();
    }
 
    public void error(SAXParseException exception) throws SAXException {
        System.out.println("\nERROR");
        exception.printStackTrace();
    }
 
    public void fatalError(SAXParseException exception) throws SAXException {
        System.out.println("\nFATAL ERROR");
        exception.printStackTrace();
    }
 
}

Sunday, February 17, 2013

Connection Pool setting for JPA

Make sure that the following is set in the persistence.xml file

<!-- Important -->
<property name="hibernate.connection.provider_class"
  value="org.hibernate.connection.C3P0ConnectionProvider" />

<property name="hibernate.c3p0.max_size" value="100" />
<property name="hibernate.c3p0.min_size" value="0" />
<property name="hibernate.c3p0.acquire_increment" value="1" />
<property name="hibernate.c3p0.idle_test_period" value="300" />
<property name="hibernate.c3p0.max_statements" value="0" />
<property name="hibernate.c3p0.timeout" value="100" />


Ensure that the connection provider is set and all properties of connection pool are prefixed with "hibernate.

The easy way to verify is that you should see from the log files the following statements

INFO: Initializing c3p0-0.9.1 [built 16-January-2007 14:46:42; debug? true; trace: 10]
com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
INFO: Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@f3a94e12 [     connectionPoolDataSource ->

Spring AOP cannot set value NULL

After hours of debugging I figured that indeed the issue was related to the various jar file configurations which was causing the trouble.

I have listed the ideal permutation which might help some one to fix this issue soon.

Ensure that the following are the appropriate versions atleast for SPRING related stuff.

  1. aopalliance-1.0.jar
  2. asm-3.1.jar
  3. asm-attrs-1.5.3.jar
  4. aspectjrt-1.6.5.jar
  5. aspectjtools-1.6.9.jar
  6. aspectjweaver-1.6.5.jar
  7. cglib-nodep-2.1_3.jar
  8. commons-logging-1.1.1.jar
  9. log4j-1.2.16.jar
  10. spring-aop-3.1.2.RELEASE.jar
  11. spring-asm-3.1.2.RELEASE.jar
  12. spring-aspects-3.1.2.RELEASE.jar
  13. spring-beans-3.1.2.RELEASE.jar
  14. spring-context-3.1.2.RELEASE.jar
  15. spring-core-3.1.2.RELEASE.jar
  16. spring-expression-3.1.2.RELEASE.jar
  17. spring-instrument-3.1.2.RELEASE.jar
  18. spring-tx-3.1.2.RELEASE.jar


Tomcat JNDI Exception DataSource

·         DO NOT configure the DataSource (or) EntityManagerFactory in the Spring beans.
·         The version of Tomcat SHOULD BE minimum of 7.0.25. For lower versions of Tomcat you still need to use the regular connection like driverà url à password etc., This is a BUG with Tomcat server itself.
·         If you try to use DataSource with earlier versions of the Tomcat, then you will see JNDIExceptions
·         Since Tomcat does not support JTA , you need to have the following configuration for the datasource in your persistence.xml file
<persistence-unit name="<<Name>>"  transaction-type="RESOURCE_LOCAL">   
   <provider>org.hibernate.ejb.HibernatePersistence</provider>
   <!--GLOBAL_JNDI_GOES_HERE This is for Tomcat which does not support JTA-->
   <non-jta-data-source>java:comp/env/jdbc/<<Your DataSource Name>></non-jta-data-source>
·         For hibernate way it will be the following
<property name="hibernate.connection.datasource">java:comp/env/jdbc/<<Your DataSource Name>></property>
·         Note that for Tomcat you need to make sure that you are reading the datasource as a “resource” and that’s why you need have the java:compo/env as a prefix for the datasource.
·         Now normally you configure the resources in either.
a.       <Tomcat_Home>\Conf\context.xml (or)
b.      <Tomcat_Home>\Conf\server.xml (or)
·         But once this is done as above the whole of Tomcat applications will have access to that resource which we do not want to do. This also means that that you need to have database specific driver files loaded and visible to all the applications deployed.
·         EPH proposes to use application specific Context files. Here are the steps for the same.
·         Create a file called “context.xml” in your webapp folder
a.       WebContent\META-INF
·         The contents of this file is as follows
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/<<Your DataSource Name>>">
        <Resource name="jdbc/<<Your DataSource Name>>"
                          auth="Container"
                          type="javax.sql.DataSource"
                          driverClassName="oracle.jdbc.driver.OracleDriver"
                          url="jdbc:oracle:thin:@<<server>>:<<port>>:<<instance>>"
                          username="<<userid>>"
                          password="<<pwd>>"
                          maxActive="20"
                          maxIdle="30"
                          maxWait="-1"
        /> 
</Context>
·         Note the equality in “name” and “path” in the above file.
This way your DB driver files are loaded at runtime (WEB-INF\lib) and not at server start up time.

Hibernate 4 and Configuration

If you use 
configuration = new Configuration();
configuration.configure(<<hibernate.cfg.xml");

You will see the warning 
configuration.configure is deprecated.

To get rid of this do the following

Configuration configuration =null;
ServiceRegistry serviceRegistry =null;
try{
configuration = new Configuration();
configuration.configure(hibernateConfigFile);
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
factory = configuration.buildSessionFactory(serviceRegistry);
}

This will get rid of the warning

Wednesday, February 6, 2013

Caused by: java.sql.SQLException: Io exception: Got minus one from a read call


I was struggling with the following exception for couple of days and here is my fix
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection


Caused by: java.sql.SQLException: Io exception: Got minus one from a read call



Make sure that you DO NO SPAN a transaction in any of the READ methods.
entitymanager.getTransaction().begin()

If so ensure that before you call the  entitymanager.close(), do a 
entitymanager.getTransaction().commit().

This might prove costly because of the COMMIT. But on the contrary if you do not commit / rollback, then the transaction will be OPEN
and trying to close the EntityManager will not close the EM since
em.getTransaction().isActive() is true.

so these connections will be open causing the avbove said exception over a period of time.

So better the choice of execution order would be

try{
     getEntityManager()
       READ
}catch(Exception ){ do something}
  finally{
    em.close();
}


One last thing, closing the EMF will actually close the connection pool.

I really liked this website giving more insight and information about JPA





Generate JAXB with individual packages using MAVEN


If you want to generate JAXB using MAVEN from multiple XSD files
and also ensuring that the package for each XSD is different.
Following lines of code will let you do that with ease



 

Monday, January 28, 2013

Disable absolute URL access- Apache web server


you can disable accessing through absolute url and allow access only with relative url with this htaccess code 


RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

Saturday, January 26, 2013

Persistence Unit not found - JPA- RESOLVED

Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named

This is so annoying

I had been looking for solutions for the same. Here are the pointers for the same

Hope this helps someone.

  1. My project structure is as follows . I am using JPA2.0
  2. .
    ├── pom.xml
    └── src
        ├── main
           ├── java
              └── se
                  └── mycomp
                      ├── UserTest.java
                      └── domain
                          └── User.java
           └── resources
               ├── META-INF
                  └── persistence.xml
               └── log4j.properties
        └── test
            └── java
  3. Compare the case sensitiveness for the Persistence Unit Name.
  4. If you have JPA2.0 as a dependency, you can go ahead and remove the same
  5. Check if your provider is 
  6. <persistence-unit name="manager1" transaction-type="RESOURCE_LOCAL">
            <provider>org.hibernate.ejb.HibernatePersistence</provider>
    Check your pom.xml if you have hibernate entity manager as a dependency.
    If needed add the hibernate annotations too . No HARM
       <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-entitymanager</artifactId>
          <version>${hibernate-core-version}</version>
        </dependency>
    
    
    Thats it, the errors are gone.