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
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(
 at net.sf.cglib.core.KeyFactory.(
 at net.sf.cglib.proxy.Enhancer.(
 at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.getProxyFactory(
 at org.hibernate.proxy.pojo.cglib.CGLIBProxyFactory.postInstantiate(
 at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(
 at org.hibernate.tuple.entity.AbstractEntityTuplizer.(

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('' . $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 
    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;
 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


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


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


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.options.cache_id_prefix=CACHE_PREFIX "_"

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

;For Memcache

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. "_" "/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
Happy Programming !!!

Thursday, September 13, 2012

How to configure multiple handler mappings in Spring MVC

DispatcherServlet is Spring MVC's implementation of the front controller pattern. Essentially, it's a servlet that takes the incoming request, and delegates processing of that request to one of a number of handlers, to determine which controller the request should be sent. When the client request reaches the Dispatcher Servlet, the Dispatcher Servlet tries to find the appropriate Handler Mapping object to map the request.
Spring distribution contains the following Handler mappings


All of the above can be found at org.springframework.web.servlet package. You can use any one of these handler mappings in your application by just configuring it in the application context file. If no handler have been configured, by default BeanNameUrlHandlerMapping will be used. And also you can configure more than one handlers in your application. In case of multiple handlers, we have to guide our DispatcherServlet by setting the order property of the handler mappings. Every handler mapping implements Ordered interface. So all we have to do is set the order
property, where the lower order value has the higher property.

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<prop key="/edit/hello.htm">helloController</prop>
<prop key="/hello.htm">helloController</prop>
<property name="interceptors">
<ref bean="myinterceptor" />
<property name="order" value="0"/>

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<property name="order" value="1"/>

<bean name="/adddealer.htm" class="com.practice.web.AddDealerFormController">
<property name="sessionForm" value="true"/>
<property name="commandName" value="dealer"/>
<property name="commandClass" value="com.practice.domain.Dealer"/>
<property name="successView" value="hello.htm"/>
<property name="dealerManager" ref="dealerManager"/>

In the above example, we have configured 2 handler mappings BeanNameUrlHandlerMapping the default one and the simplest one to, and SimpleUrlHandlerMapping, and set the priority order. So the DispatcherServlet will consult each one of the them in the order according to their priority set by
the order priority. If a HandlerMapping does not return an appropriate HandlerExecutionChain , the next available HandlerMapping will be consulted. If no appropriate result is found after inspecting all HandlerMappings an exception will be thrown.

Happy Programming !!!

Saturday, September 1, 2012

What is Cross Cutting Concerns in Spring?

The majority of application we design will contain common functionality that spans across tiers and layers, such as Security, Caching, Logging, Transactions and more. These are called crosscutting concerns. "Concern" means logic/functionality. Since it affects the entire application, and should have been in one centralised location rather than scattered across application layers and tiers.

For example: You have application, which spans multiple layers say Controller, Service and DAO. You have a requirement to add the logging code to one of the DAO method, yes that's easy one, just go to that method, and add the logging code at the top of the method, then there is a requirement to add Security code to the same method, where you have added the logging, yes this also seems to easy, you just go to the method, and add the necessary security logic to the method after the logging. Now you got a requirement to extend this logic to all the layers(Controllers and Service) of that method, okay little tedious, but we are expert in copy and paste, we will copy the code from the DAO and paste it in Service and Controller, that's all done. But really what we have done is a dirty job.

Now, if they want this to be done in our entire system, little crazy now, already we have done a dirty job by doing a copy paste of DAO to Service and Controller, our code has been scattered, if we need to change, we have to update all the classes, it will not be a big deal if it is one or two classes, but for entire application it is a pain full job.

That's where we will be using the Aspect Oriented Programming (AOP) . It is a programming technique based on the concept of an Aspect. Aspect encapsulates cross-cutting logic, the basic infrastructure code which all application needs. What we are going to do is, we will take the logging and security code, and encapsulate it into a module for a reusable code.

Will soon publish a post on how to configure the AOP in Spring along with the Cross Cutting Concerns

Happy Programming ...!!!

Monday, August 27, 2012

What is ContextLoaderListener in Spring?

After a very long time, started refresh myself on spring framework, started with some sample web application got held up on the configuration ContextLoaderListener, what it really is, what was the use.
It is the Bootstrap listner to start up the Spring's root WebApplicationContext. All configuration which have been configured and loaded up during the startup, will be available throughout the application.

Mostly DB Configuration will be most one which can be seen
To register the listner, just add the below line to the web.xml
The class ContextLoaderListner will be found in the spring.jar, which can be found in the dist folder under spring bundle.

Happy Programming !!