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 »

Bean Validation (JSR-303) and validating Cron Expressions, extending constraints

To validate cron expressions using bean validation stuff, the best practice is to write your own custom validators and to use quartz framework’s cron expression facilities.
To write your custom validator, you need to implement

ConstraintValidator<A extends java.lang.annotation.Annotation,T>

from javax.validation.* package.

public class CronExpressionValidator implements
        ConstraintValidator<CronExpression, String> {
 
    public void initialize(CronExpression cronExpression) {
        //To change body of implemented methods use File | Settings | File Templates.
    }
 
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        return org.quartz.CronExpression.isValidExpression(s);
    }
}

To validate cron expressions in isValid() method, the isValidExpression() static method is used from Quartz Framework. To add Quartz to our maven project add the following dependency into your pom:

        <dependency>
            <groupId>org.opensymphony.quartz</groupId>
            <artifactId>quartz</artifactId>
            <version>1.6.5</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

CronExpression defined as parameterized type is the annotation class that we will use for cron constraints and seems like following;

@Documented
@Constraint(validatedBy = CronExpressionValidator.class)
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface CronExpression {
    String message() default "Cron expression is not valid!";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

@Documented indicates that annotations with a type are to be documented by javadoc and similar tools by default.
@Constraint(validatedBy=CronExpressionValidator.class) defines validator class.
@Target defines that this annotation is applicable to methods, fields, annotation types, constructors and parameters.
@Retention defines that the annotation is a runtime annotation not a compile time annotation like @SupressWarnings, @Override etc.

We are now ready to annotate our fields, parameters etc. with our new constraint just like this:

class MyCronBean {
    @NotNull
    @CronExpression
    private String cronExpression;
    /** setters and getters */
}

Netbeans: Adding a project license to your project

I see lots of questions in Netbeans forums about Templates and project license and developers has problems with configuring it. If you want to add a project license and associate it with your project, you need to add a license property in your project configuration file. The property file “nb-configuration.xml” lies in your project folder, in my case:

Erhan-Bagdemirs-MacBook-Pro:NetBeansProjects merodach$ pwd
HOME/NetBeansProjects

You have to add just”” in your properties:

<properties xmlns="http://www.netbeans.org/ns/maven-properties-data/1">
     ...
    <netbeans.hint.license>mylicense</netbeans.hint.license>
     ...
</properties>

and create a new licence file under:
HOME/.netbeans/6.9/config/Templates/Licenses

after a new installation of Netbeans (i have the version 6.9.1), there was no License folder. If you can’t see this folder, just create it and create a license file accordingly:
HOME/.netbeans/6.9/config/Templates/Licenses/license-mylicense.txt

The name of the license file is important and must follow this naming template:
license-${project.license}.txt

${project.license} is the property which you added with ““.

Open “Template Manager” on your IDE, following the menu path “Tools > Templates”. For Java classes the template seems like this if you open template in your editor:
null
and you can see the path to your license and how it is associated with your project. We make no changes in the template and just create now a new java class to test our license (in my case, apache’s open source license):

null

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