Sunday, January 27, 2013

InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode

If you have enabled the filter OpenSessionInViewFilter, for fetching the lazily loaded data, you can typically see the below error message, when trying to do a persistence operation outside of Spring-managed transaction.

org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
org.springframework.orm.hibernate3.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1186)
org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:696)
org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:419)
org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:694)

OpenSessionInViewFilter has an alternative "deferred close mode", to resolve the issue. This can be activated through setting the singleSession=false. This will use one Session per transaction, but keep each of those open until view rendering has been completed. As no Session will be reused for another transaction in this case, there is no risk of accidentally flushing inconsistent state


  OpenSessionInViewFilter
  org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
  
     singleSession     false  


Happy Programming !!!

Saturday, December 22, 2012

Sql Developer - Unable to create instance of java virtual machine

When trying to open SQL Developer IDE, you will get the following exception poped up
unable to create instance of java virtual machine sql developer
SQL Developer is created uisng JAVA, it needs the Java Virtual Machine to run the IDE, sometime the memory allocated to kick start doesn't have enough, then you will see the above exception. To fix, we need to increase the memory allocated to the JVM.

Just AddVMOption -Xmx512M in sqldeveloper\ide\bin\ide.conf. This will resolve the issue.

Happy Programming...!!!

Sunday, December 9, 2012

Hibernate Error : java.lang.NoClassDefFoundError: antlr/ANTLRException

When you are working with the Hibernate Query, you will get the following error
java.lang.NoClassDefFoundError: antlr/ANTLRException
 org.hibernate.hql.ast.ASTQueryTranslatorFactory.createQueryTranslator(ASTQueryTranslatorFactory.java:35)
 org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:74)
 org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:56)
 org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
 org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133)
 org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112)
 org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1623)
All you need is to download the latest version of antlr jar. You can download this from here antlr-2.7.7.jar, and put it under your web lib folder.

Happy Programming...!!!

Saturday, November 24, 2012

Hibernate Error : java.lang.NoClassDefFoundError: org/objectweb/asm/Type

This is the common error we will be getting when working on the Hibernate.
Caused by: java.lang.NoClassDefFoundError: org/objectweb/asm/Type
 at net.sf.cglib.core.TypeUtils.parseType(TypeUtils.java:180)
 at net.sf.cglib.core.KeyFactory.(KeyFactory.java:66)
 at net.sf.cglib.proxy.Enhancer.(Enhancer.java:69)
 at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.getProxyFactory(CGLIBLazyInitializer.java:117)
 at org.hibernate.proxy.pojo.cglib.CGLIBProxyFactory.postInstantiate(CGLIBProxyFactory.java:43)
 at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:162)
 at org.hibernate.tuple.entity.AbstractEntityTuplizer.(AbstractEntityTuplizer.java:135)

This was due to the one of the asm jar missing in your /WEB-INF/lib directory. You can download it from their official directory ASM, or you can use the springsource object jar, which can be downloaded here

Happy Programming !!!

Thursday, October 18, 2012

How to get a FaceBook comment count for a page?

Face open graph api has relevant info, to send you the facebook comment count for a particular page. Below is the sample code, which will return you the JSON response of the page details, from where you can fetch comments count, you just need to pass the URL.

Note: Your page URL is the unique identifier.

$json = json_decode(file_get_contents('https://graph.facebook.com/?ids=' . $url));
return ($json->$url->comments) ? $json->$url->comments : 0;


Tuesday, October 2, 2012

How to retrieve the auto-generated key after an INSERT in Spring

When you insert a record with a primary key field set as auto_increment in MYSQL, it will generate ID automatically, though Spring's RdbmsOperation class has two methods with encouraging names setGeneratedKeyColumnName and setReturnGeneratedKeys, at the time of writing the child class SqlUpdate doesn't not use them to return the value of the generated keys. If our table has a foreign relation, and related data needs to be inserted at the time of creation, we need the primary key field data of the insert statement.

To get the generated id, we have to use the JdbcTemplate.update method which is overloaded JdbcTemplate.update(PreparedStatementCreator psc, KeyHolder k)
The key returned from the insert is injected into the KeyHolder object. Implementation of this interface KeyHolder can hold any number of keys. In the general case, the keys are returned as a List containing one Map for each row of keys. Below is the sample implementation to get the auto generated ids, this works fine in MYSQL

public int add(BaseObject obj) {
 final Dealer dealer = (Dealer) obj;
 dealerJdbcTemplate.update(psc, generatedKeyHolder)
 KeyHolder keyHolder = new GeneratedKeyHolder();
 dealerJdbcTemplate.update(new PreparedStatementCreator()
  {
   public PreparedStatement createPreparedStatement(Connection connection) throws SQLException 
   {     
    PreparedStatement ps = connection.prepareStatement("INSERT INTO DEALER (NAME, ADDRESS, CITY, STATE, COUNTRY, ZIP, CONTACTPERSONNAME, MOBILENUMBER, PHONENUMBER) VALUES (?,?,?,?,?,?,?,?,?)" , Statement.RETURN_GENERATED_KEYS);
    ps.setString(1, dealer.getName());
    ps.setString(2, dealer.getAddress());
    ps.setString(3, dealer.getCity());
    ps.setString(4, dealer.getState());
    ps.setString(5, dealer.getCountry());
    ps.setInt(6, dealer.getZip());
    ps.setString(7, dealer.getContactPersonName());
    ps.setString(8, dealer.getMobileNumber());
    ps.setString(9, dealer.getPhoneNumber());            
    return ps;
   }    
  },
  keyHolder
 );
 return keyHolder.getKey().intValue(); 
}
Happy Programming...!!

Saturday, September 22, 2012

How to cache data using Zend_Cache


Cache is a temporary storage area where frequently used data can be stored for faster access. If we are running a very expensive query to fetch records from the database very frequently, we can store these data in the cache (in our machine memory or file system). Accessing the memory will be quicker than connecting to database and fetching the data.

In Zend Framework, we can achieve this by using the Zend_Cache, it is very flexible such that, it allows you what you want to cache and where you want to cache.

What you want to cache (Frontend)
The main parameters which is used are

Caching

This controls whether we need to have caching or not, defaults to true

Lifetime

How long the cache should be alive

Automatic Serialization

defaults to false, if it is set to true, serialization will happen on the fly, if not we must perform it

Where you want to cache (Backend)
Backend is nothing but telling the Zend, where you want to store the cached data.
There are many options available, of them Memcache is relatively faster and easy to implement. But here we will see, how to implement it in the File system.

The main parameter which used for File system


cache_dir

Directory where we need to store the cached data

Lets see how to configure the cache settings in Zend through application.ini

Format will be resources.cachemanager.<NAME>.<OPTION> = <VALUE>
resources.cachemanager.config.frontend.name=Core
resources.cachemanager.config.frontend.options.caching=true
resources.cachemanager.config.frontend.options.cache_id_prefix=CACHE_PREFIX "_"
resources.cachemanager.config.frontend.options.lifetime=86400
resources.cachemanager.config.frontend.options.automatic_serialization=true
resources.cachemanager.config.frontend.options.logging=true
resources.cachemanager.config.frontend.options.write_control=true

;For File System
resources.cachemanager.config.backend.name=File
resources.cachemanager.config.backend.options.cache_dir=APPLICATION_PATH "/cache"

;For Memcache
resources.cachemanager.config.backend.name=Memcached
resources.cachemanager.config.backend.options.servers.0.host=server1
resources.cachemanager.config.backend.options.servers.0.port=11211
resources.cachemanager.config.backend.options.servers.1.host=server2
resources.cachemanager.config.backend.options.servers.1.port=11211

By defining these in application.ini settings, Zend will automatically instantiate an instance of Zend_Cache_Manager and set up a cache that is named "config" with the individual options as specified. We can create a different instances of cache like this with its own configuration settings, for example say the above options will be used for all Configuration related items, suppose if you want to have different configuration for data related items, you have to replicate the above setting with the changed to data.

resources.cachemanager.data.frontend.options.caching=true
resources.cachemanager.data.frontend.options.cache_id_prefix=DATA_CACHE_PREFIX "_"
resources.cachemanager.data.frontend.options.lifetime=500
resources.cachemanager.data.frontend.options.automatic_serialization=true
resources.cachemanager.data.frontend.options.write_control=false

resources.cachemanager.data.backend.name=File
resources.cachemanager.data.backend.options.cache_dir=APPLICATION_PATH "/datacache"

So now in your Bootstrap, you can get the relevant cache manager instance and store in the Zend_Registry, so that it will be available to you at need

$cacheManager = $this->getPluginResource('cachemanager')->getCacheManager();
$cache = $cacheManager->getCache('config'); 
Zend_Registry::set(self::REGISTRY_KEY_CACHE_CONFIG, $cache);

So you can save the cache data like this
$cach->save($data , $cacheKey);
To reterive the data from teh cache
$cache->load($cacheKey);
Happy Programming !!!