Sunday, May 19, 2013

Using Spring-Cache-Guava

 Spring-Cache-Guava, uses the Maven build system. Building the code yourself should be a straightforward case of:
  git clone git@github.com:irbouho/spring-cache-guava.git
  cd spring-cache-guava
  mvn install

To use Spring-Cache-Guava, you need to include the runtime module in the dependencies section of your pom.xml (replacing ${spring-cache-guava.version} with the appropriate current release):

  
    com.springmodules.cache.guava
    core
    ${spring-cache-guava.version}
  

Instances of GuavaCache can be created using Spring XML configuration:
  

This code snippet above creates an instance of the Guava cache factory bean using the default configuration. You can fine-tune the cache instance properties by providing a CacheBuilderSpec as follows:
  

GavaCaches need to be wrapped into a CacheManager to be used with Spring Cache Abstraction. Spring-Cache-Guava has a CacheManager that can be used to this end:

 
  
   
   
  
 




Now you have your CacheManager configured and Spring Framework caching annotations enabled. All you have to do is to create your beans and annotate them using Spring Framework Cache annotations.

  @Cacheable(value = "users-cache")
  public User findUserByUserName(String userName) {
    return userRepository.findByUserName(checkNotNull(userName));
  }

Spring-Guava-Cache

I had some free time recently and wrote a small adapter for Spring Framework Cache Abstraction backed by Google Guava Cache. I use both frameworks extensively and enjoy the features they provide.

The source code is available on GitHub. The Introduction page explains how to build the artifacts and use them in your project. You can use the Issues page to submit bugs / requests.

I will post more entries on this blog to explain more and share few lessons I learned.

Dear Blog, I'm so sorry

Few years passed since I last wrote something on this blog... It's time to start blogging again...

I never had any issues with Blogger, so instead of starting a new blog somewhere else,
I thought I'd just continue posting here.
 

Tuesday, June 12, 2007

Spring Modules Cache

Tutorials about configuring and using Spring Modules Cache.

Monday, October 31, 2005

Spring Web Flow

I will be presenting on Spring Web Flow on Wednesday, 9 November at Montréal Java Users Group. Following is the official announcement

LA PROCHAINE RENCONTRE SERA LE MERCREDI 9 NOVEMBRE AU CRIM.

Le Groupe d'Utilisateurs Java de Montréal (GUJM) vous invite
à participer à la prochaine rencontre qui sera le mercredi
9 novembre 2005.

TITRE : "Introduction au Spring Web Flow"
par Omar Irbouh.

Spring Web Flow (SWF) est un sous projet du célèbre Spring
Framework. Il a pour objectif de palier aux nombreuses lacunes
introduites par l'approche de développement Web MVC classique.
SWF permet d'implémenter, facilement, des flux de pages en
terme d'actions et de vues ce qui renforce la modularité et
améliore la réutilisation. SWF peut être utilisé avec Apache
Struts, Spring MVC et JSF

Plan de la présentation :
Introduction
Bref rappel sur Spring Framework
Spring Web Flow
- Pourquoi utiliser des Flows dans des applications Web?
- Architecture
- L'implémentation SWF
- Fonctions avancées de SWF
Q&A

À propos du présentateur :

Omar Irbouh est conseiller de chez Compuware inc. Il
travaille actuellement sur un projet J2EE pour le compte
d'une institution financière internationale située à New York.
________________________________________________________________

Heure : 17h30 - 19h30.

Lieu : CRIM (Salle B, ouverte à 17h00).
550, rue Sherbrooke Ouest, Bureau 100
Montréal (Québec), Canada H3A 1B9
http://web.crim.ca/oxygene/pages/contactez-nous.epl

Horaire : 17h30 - 17h40, Mot de bienvenue.
17h40 - 19h00, Présentation
19h00 - 19h30, Discussion libre.

I hope to meet you there.

Monday, October 24, 2005

Hibernate Generic Dao

Christian Bauer blogged sometime before about a Generic Hibernate Dao pattern with JDK 5. This pattern has the advantage of simplifying the dao construction, It also allows for direct access to the underlying Hibernate session witch makes it possible to use the Hibernate powerfull API for data manipulation. The only issue I can think of, as a Spring Framework user, is intergation with Spring Framework declarative services, mainly transaction demarcation.

I updated Christian code to make the Generic Dao easily advisable by Spring Framework ProxyFactories to provide transactions management and other enterprise services.

/*
* Copyright 2002-2004 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.adam.dao.hibernate;

import java.io.Serializable;
import java.util.List;

import org.adam.dao.GenericDao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.util.Assert;

/**
* GenericHibernateDao that should be extended by HibernateDaos.
* @author Omar Irbouh
* @since 2005.09.12
*/
public abstract class GenericHibernateDao implements GenericDao, InitializingBean {

protected transient Log logger = LogFactory.getLog(getClass());

private Class persistentClass;
private SessionFactory sessionFactory;

public GenericHibernateDao() {
}

public GenericHibernateDao(SessionFactory sessionFactory, Class persistentClass) {
this.persistentClass = persistentClass;
this.sessionFactory = sessionFactory;
}

protected SessionFactory getSessionFactory() {
return sessionFactory;
}

public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

private Class getPersistentClass() {
return persistentClass;
}

public void setPersistentClass(Class persistentClass) {
this.persistentClass = persistentClass;
}

public void afterPropertiesSet() throws Exception {
Assert.notNull(getSessionFactory(), "sessionFactory is required");
Assert.notNull(getPersistentClass(), "persistentClass is required");
}

@SuppressWarnings({"unchecked"})
public T findById(ID id, boolean lock) throws DataAccessException {
return (T) getSession().load(getPersistentClass(), id, (lock) ? LockMode.UPGRADE : LockMode.NONE);
}

public List findByExample(T exampleInstance) throws DataAccessException {
return findByCriteria(Example.create(exampleInstance));
}

@SuppressWarnings({"unchecked"})
public T store(T entity) throws DataAccessException {
return (T) getSession().merge(entity);
}

public void delete(T entity) throws DataAccessException {
getSession().delete(entity);
}

@SuppressWarnings({"unchecked"})
public List findAll() throws DataAccessException {
return findByCriteria();
}

@SuppressWarnings({"unchecked"})
protected List findByCriteria(Criterion... criterion) {
Criteria criteria = getSession().createCriteria(getPersistentClass());
for (Criterion c : criterion) {
criteria.add(c);
}
return criteria.list();
}

protected Session getSession() {
return SessionFactoryUtils.getSession(sessionFactory, true);
}

}

This abstract class can be subclassed as follows:

/*
* Copyright 2002-2004 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.adam.dao.hibernate;

import org.adam.dao.RoleDao;
import org.adam.model.Role;
import org.hibernate.Query;
import org.springframework.dao.DataAccessException;

/**
* Hibernate implmentation of the RoleDao business interface.
* @author Omar Irbouh
* @since 2005.08.29
*/
public class HibernateRoleDao extends GenericHibernateDao implements RoleDao {

/**
* Hibernate named query used to retrieve a Role by its name.
*/
private static final String QUERY_ROLE_BY_NAME = "role.by.name";

public Role findByName(final String name) throws DataAccessException {
Query query = getSession().getNamedQuery(QUERY_ROLE_BY_NAME);
query.setParameter("name", name);
return (Role) query.uniqueResult();
}

}

GenericHibernateDao delegates to SessionFactoryUtils for Hibernate session creation / synchronisation.

Sunday, December 19, 2004

Présentation de Spring aux Groupe d'Utilisateurs Java de Québec

J'ai présenté Spring Framework lors de la demi-journée conférence du Groupe d'Utilisateur Java de Québec organisée le 9 Novembre 2004. Voici le plan de la présentation :

- Introduction
- J2EE, état actuel des choses
- Spring Framework
- Injection des dépendances
- Programmation Orientée Aspect
- Les services de Spring
- Application Context
- DAO, JDBC, ORM
- Transactions
- EJB
- MVC
- Remoting, Scheduling...
- Q&A

L'audience a exprimé un très grand intérêt au Framework Spring. Je mettrai bientôt la présentation PDF et l'application exemple sur ce site. En attendant, je vais ajouter quelques fonctionnalités à l'application exemple pour montrer l'utilisation de quelques fonctionnalités de Spring à partir du sandbox (commons-validator, groovy, jmx...)

Spring Login Interceptor

I posted on Spring Framework Forums the source of a Login Interceptor that can be used to check if the user has logged on to the Web Application.
read more...

Caching the result of methods using Spring and EHCache

I published a new article on Spring Confluence Wiki that shows how to use Spring Integration for EHCache (since Spring 1.1.1).

The article presents a Spring Interceptor that caches methods results based on method name and arguments values. Of course the interceptor is configured declaratively using Spring IoC.

Spring at Montréal JUG

I will be presenting 'Application development with Spring Framework' at Montréal JUG 8 December 2004.

Hope to see you there!

Trapping Exceptions in Spring Web

Spring Framework HandlerExceptionResolver allows to build Exception Handlers that can be configured to trap exceptions and return a ModelAndView. They work in a simillar way to Struts ExceptionHandlers.

I posted a sample on Spring Framework Forums that explains how to build and configure ExceptionHandlers in Spring.

read more...

Throw own exceptions using Hibernate & Spring Framework

A Spring Framework/Hibernate user asked for a / magic / easy / way to convert Spring Framework thrown Exception into User Defined Exception without putting a try-catch block in all my methods.

I think we can achieve this using the magic of AOP. All we have to do is create an interceptor and hock it into the applicationContext.xml without having to change one line of code into our classes nor modify the bean configuration of DAOs / Services.

Throw own exceptions using Hibernate & Spring Framework

A Spring Framework/Hibernate user asked for a / magic / easy / way to convert Spring Framework thrown Exception into User Defined Exception without putting a try-catch block in all his methods.

I think we can achieve this using the magic of AOP. All we have to do is create an interceptor and hock it into the applicationContext.xml without having to change one line of code into our classes nor modify the bean configuration of DAOs / Services.

read more...