Icon

Software Engineering, Architecture, Web Development and beyond…

Making things @Cacheable

Performance optimizing with caching frameworks, or in general caching, like OSCache, EHCache is inevitable in software development and especially critically important in web development. If you want to serve contents from your data storages and if you’ve hunderds of requests – per minute – or even more, like on high-traffic portals, then it must be considered to cache your contents, objects, method calls, etc. in every layer efficiently. Most of ORM frameworks like Hibernate do support first-level and second level caching out-of-box and there are also many other caching strategies like distrubuted caching with Oracle Coherence or Jboss distributed caching facilities. But we won’t discuss in detail all of them. The aim of this post is to show application developers how to integrate custom caching mechanism easily using java annotations (Java 1.5+) from programmers’ point of view.

Think about the situation that you’re developing a website of which contents are supplied by a commercial partner in xml and you have to render these contents on-fly over a reliable connection and responsive server – or you can cache the contents in a relational database, but to reduce database request it’s a best practice to integrate custom caching in your service layer. Say, the contents are about weather informations from stations and you’re about to build a weather web application. Everytime your page gets called, without any caching mechanism your service has to call partner service also. It can bring about an overhead on your network and load on backend. Maybe just for that reason, you might rehandle your contract.

EHCache is a pretty good solution and a well known caching framework which’s broadly used to cache “data” programmaticaly – not only- creating and implementing your own CacheKeys. It is easier to integrate into spring web applications. But, things’re getting even better with ehcache-spring-annotations project on google code if the application deveper had a chance to cache some data, supplying some meta informations (god bless annotations) without any coding effort.

The common scenario is that we have a MVC application and the following controller handles user requests on “http://{yourhost.com}/{appcontext}/weatherchannel/index.html?sid=4567
“sid” stands for “station id” and passed as GET parameter to the controller.

@Controller
@RequestMapping("/weatherchannel")
public class WeatherChannelController {
 
@Autowired
private IWeatherDataGateway weatherGateway;
 
@RequestMapping(value="/index.html", method=RequestMethod.GET)
public String handleUserRequest(@RequestParam("sid") String stationId, ModelMap model) {
     List<weatherstationinfobean> stationInfos = weatherGateway.callPartnerEndpointRestfully(id);
     model.addAttribute("sinfos", stationInfos);
     return "stationinfo";
}
 
}
</weatherstationinfobean>

Read the rest of this entry »

JNDI Configuration, globally defined Data Sources in Tomcat

JNDI is such an issue which developers configure once and don’t need to take care of it anymore. However, you’ll need to look at documentation everytime it must be configured to refresh your knowledge. But, everytime i need to configure my tomcat, i get headaches. For that reason here is my blog about defining data sources globally and to make them available for all application.

I have read all sections in official tomcat documentations to get my project work with JNDI resources, but it suffers with exception as soon as the application inits. If i put my just into the tomcat’s context.xml, i get an exception “NameNotFoundException: Datasource not bound” while tomcat starts. I have tried tousands of variations to make JNDI resources to make available for all applications under webapps.
Here is the way which works really:

1. Define your JNDI sources under /conf/server.xml

  <GlobalNamingResources>
 
      <Resource acquireIncrement="1"
                auth="Container"
                description="example datasource"
                driverClass="com.mysql.jdbc.Driver"
                factory="org.apache.naming.factory.BeanFactory"
                idleConnectionTestPeriod="600"
                initialPoolSize="1"
                jdbcUrl="jdbc:mysql://127.0.0.1:3306/mydb?autoReconnect=true"
                maxIdleTime="600"
                maxPoolSize="2"
                maxStatements="50"
                minPoolSize="1"
                name="mydatasource"
                password="4sfS345se3E"
                preferredTestQuery="SELECT 1"
                type="com.mchange.v2.c3p0.ComboPooledDataSource"
                user="myuser"/>
 
  </GlobalNamingResources>

2. add resource links into /conf/context.xml

<ResourceLink global="mydatasource" name="mydatasource"/>

3. don’t forget to add data source libraries (jars) into tomcats /lib for tomcat 6, /shared/lib for tomcat 5. In my case, i am using pooled data source of c3p0.

After restarting tomcat, my application starts without any exception and my database connection is just there.

Best Practices: java.lang.NoSuchMethodError: javax.persistence.Persistence.getPersistenceUtil() JSR 303 Bean Validation and Hibernate validator

As soon as my form is submitted to be validated by Bean Validation facilities, i got the following exception:

java.lang.NoSuchMethodError: javax.persistence.Persistence.getPersistenceUtil()

After doing a little research i could solve the problem related to Persistence methods and Bean Validation (see Bean Validation JSR-303).
First of all, i needed to understand what the relation between Persistence and Validation is.
My Project includes Spring 3.1 and Hibernate 3.5 libraries. And i wanted to use JSR303 and annotations.

To enable Bean Validation facility in a spring project, Spring needs a default validator if you don’t give an explicit validator interface like this:

<mvc:annotation-driven validator="globalValidator"/>

globalValidator is a global validator interface, bean, which the developer must provide. But, I wanted to just make my fields be validated according to annotations. For that reason i added into my config just:

<mvc:annotation-driven/>

and added Hibernate-Validator 4.1 into my project.

(Solution) It seems that the Hibernate-Validator version 4.0 works only with J2EE 6 (JEE). Here is the stacktrace:

java.lang.NoSuchMethodError: javax.persistence.Persistence.getPersistenceUtil()Ljavax/persistence/PersistenceUtil;
at org.hibernate.validator.engine.resolver.JPATraversableResolver.isReachable(JPATraversableResolver.java:62)
at org.hibernate.validator.engine.resolver.DefaultTraversableResolver.isReachable(DefaultTraversableResolver.java:94)
at org.hibernate.validator.engine.resolver.SingleThreadCachedTraversableResolver.isReachable(SingleThreadCachedTraversableResolver.java:47)
at org.hibernate.validator.engine.ValidatorImpl.isValidationRequired(ValidatorImpl.java:757)
at org.hibernate.validator.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:324)
at org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForRedefinedDefaultGroup(ValidatorImpl.java:273)
at org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:256)
at org.hibernate.validator.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:210)
at org.hibernate.validator.engine.ValidatorImpl.validate(ValidatorImpl.java:119)
at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:86)
at org.springframework.validation.DataBinder.validate(DataBinder.java:692)

Here is the Persistence class API doc of J2EE5:

http://download.oracle.com/javaee/5/api/javax/persistence/Persistence.html

and PersistenceUtil has no such a method called getPersistenceUtil() while Persistence has this method in the sixth version:

http://download.oracle.com/javaee/6/api/javax/persistence/Persistence.html

Don’t use Hibernate-Validator 4.1 with J2EE5 otherwise you could get a headache.

erhan

Author


Hello, I'm Erhan Bagdemir and this is my blog. I talk about Java, J2EE, Frameworks, web application development, OOAD and various other topics often related to programming.

Erhan Bagdemir  Profil von Erhan Bagdemir auf LinkedIn anzeigen

ebagdemir on Stackoverflow

ebagdemir on Twitter

    Hamburg

    Slideshow