venerdì 1 maggio 2015

JMapper Framework philosophy

There are a lot of java mapping framework, each of them developed on a basic principle.
For example MapStruct applies loose coupling using annotations, Orika the same using API, Model Mapper is convention based etc...

JMapper Framework instead applies the DRY principle ( Don't repeat yourself ) using Annotations:
the mappings are defined on fields so that they are used as configuration, 
the loose coupling imposes to repeat this information.

However, with JMapper, you can choose to apply loose coupling using the XML configuration.

The second objective of JMapper is the Relational Mapping:

The relational mapping is the ability to map one bean toward many other and viceversa.


Thinks you have a service that applies a method called "checkExistence" that needs of the fields: name and surname. This service takes as input a general object that can be everything, in our case takes three different bean: Consultant, Employee and Manager. This beans have in common only this two fields and we have need to map only these toward the service's bean.


With JMapper you need to configure only the service's bean toward the others.


@JGlobalMap(classes={Consultant.class, Employee.class, Manager.class})
class ServiceBean{

     String name;
     String surname;

     //getters and setters..


class Service {

RelationalJMapper<ServiceBean> mapper = new RelationalJMapper<>(ServiceBean.class);

   public void checkExistence(Object bean){
        ServiceBean serviceBean =  mapper.manyToOne(bean);
        // some logic  


DRY principle + relational mapping  = interesting implementations

Are you curious? have a look to the relational mapping wiki page, there a lot of complete and more complex examples.

p.s. JMapper has more other interesting features as static/dynamic conversions, enrichment, mapping type etc.., don't worry in the next articles i'll describe all of it ;)

lunedì 19 gennaio 2015

How to write a good XML schema

XML Schema is a formal description of a grammar for a markup language based on XML.
 There are a lot of guides and articles about this, i suggest to visit W3C XML Schema (XSD) as start point,
 for grammar analysis: W3C XML Schema (XSD) Validation online.

The purpose of this article is to give you some tips on how to write a better xml schema.

 It's very important to know default values of all tag, for several reasons:
 - define all parameters as maxOccurs, minOccurs, optional, use etc.. for all tag makes the xsd difficult to read and modify.
 - Alternatively define a few, ignoring the default values, leads to abnormal behavior, found only with test
Here you can found all default values for all tag.

Make your xsd more readable, for this purpose you can use:
 - complexType to externalize a attribute type, for example:

        <xs:element name="employee">
          <xs:element name="firstname" type="xs:string"/>
          <xs:element name="lastname" type="xs:string"/>
  <xs:element name="student">
         <xs:element name="firstname" type="xs:string"/>
         <xs:element name="lastname" type="xs:string"/>

<xs:element name="employee" type="personinfo">
<xs:element name="student" type="personinfo">

<xs:complextype name="personinfo">
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>

 - import an external xsd and use it with namespace
 - add comments as markers, it permits to go fast on the interested point, you have to think that not everyone uses XML tools.

 - use extension or restriction of complexContent if your element is almost equal to an existing.

 follow an example of extention:

<xs:element name="employee" type="fullpersoninfo">

<xs:complextype name="personinfo">
    <xs:element name="firstname" type="xs:string"/>
    <xs:element name="lastname" type="xs:string"/>

<xs:complextype name="fullpersoninfo">
    <xs:extension base="personinfo">
        <xs:element name="address" type="xs:string"/>
        <xs:element name="city" type="xs:string"/>
        <xs:element name="country" type="xs:string"/>

an example of restriction:

<xs:complextype name="customer">
    <xs:element name="firstname" type="xs:string"/>
    <xs:element name="lastname" type="xs:string"/>
    <xs:element name="country" type="xs:string"/>

<xs:complextype name="Norwegian_customer">
    <xs:restriction base="customer">
        <xs:element name="firstname" type="xs:string"/>
        <xs:element name="lastname" type="xs:string"/>
        <xs:element fixed="Norway" name="country" type="xs:string"/>

 Few tips but if used makes the development, of large XSD file, sustainable.

lunedì 29 settembre 2014

java File Watcher

With the new features of java 7 was introduced the WatchService class, with it we know all action done on the watched folder.
But there isn't an implementation that permits to watch a single file so.. follows a my implementation called FileWatcher:

import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;

public class FileWatcher implements Runnable{

 private final WatchService watcher;
 private Path fileToWatch;
 public FileWatcher(String filePath) throws IOException {
  Path path = Paths.get(filePath);
  this.fileToWatch = path.getFileName();
  path.getParent().register(watcher, ENTRY_CREATE,ENTRY_DELETE,ENTRY_MODIFY);

 public void run() {
  for (;;) {
   // wait for key to be signaled
      WatchKey key;
      try {
          key = watcher.take();
      } catch (InterruptedException x) {
      for (WatchEvent event: key.pollEvents()) {
          WatchEvent.Kind kind = event.kind();

          if (kind == OVERFLOW) continue;
          // The filename is the
          // context of the event.
          Path fileName = ((WatchEvent)event).context();
          if(kind == ENTRY_CREATE) create();
          if(kind == ENTRY_DELETE) delete();             
          if(kind == ENTRY_MODIFY) modify();

      // Reset the key -- this step is critical if you want to
      // receive further watch events.  If the key is no longer valid,
      // the directory is inaccessible so exit the loop.
      boolean valid = key.reset();
      if (!valid) {

 public void modify() {}
 public void delete() {}
 public void create() {}

An example of use:

new Thread(new FileWatcher(filePath){
               public void modify() {

giovedì 3 ottobre 2013

Vaadin Tree: how to edit node

Change the tree nodes is possible and I will show you how to do.
Purpose: change the value of the selected node.
Object selectedNode = tree.getValue();
tree.setItemCaption(selectedNode, "new value");

Make good use of it :)

venerdì 5 luglio 2013

Java Calendar

In this post i show how to obtain the calendar of the current month, and how to know the days of the week.
First of all you need to obtain three parameters, number of days of the current month, the month and the year.

GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date());
int numDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);

To know which day of the week the date belongs:

for (int date = 1; date <= numDays; date++) {
   cal.set(year, month, date);
   String dayName = dayName(cal.get(Calendar.DAY_OF_WEEK));
   System.out.println(date + "-" + month + "-" + year + " " + dayName);    

String dayName(int day) {
   switch (day) {
      case Calendar.MONDAY:   return "Monday";
      case Calendar.TUESDAY:  return "Tuesday";
      case Calendar.WEDNESDAY:return "Wednesday";
      case Calendar.THURSDAY: return "Thursday";
      case Calendar.FRIDAY:   return "Friday";
      case Calendar.SATURDAY: return "Saturday";
      case Calendar.SUNDAY:   return "Sunday";
      default:                return "";


1-6-2013 Monday
2-6-2013 Tuesday
3-6-2013 Wednesday
4-6-2013 Thursday
5-6-2013 Friday
6-6-2013 Saturday
7-6-2013 Sunday
8-6-2013 Monday
9-6-2013 Tuesday
10-6-2013 Wednesday

lunedì 18 febbraio 2013

merge optimized of two arrays

the first code that you might think to write is:
String[] newArray = new String[firstArray.length + secondArray.length];
int index = 0;
for(int i = 0; i < firstArray.length: i++){
   newArray[index++] = firstArray[i];

for(int i = 0; i < secondArray.length: i++){
   newArray[index++] = secondArray[i];
This code is simple but slow, the best way to do this is to use system methods, as follow:
String[] newArray = Arrays.copyOf(firstArray, firstArray.length + secondArray.length);
System.arraycopy(secondArray, 0, newArray, firstArray.length, secondArray.length);  
This algorithm is three times faster and short.
good optimization :)

domenica 13 gennaio 2013

Class generation with Javassist

With this post you will see how it's easy to create at runtime a class with javassist.
We will go to create a simple javaBean that extends an interface.
The interface is defined at development time as follows:
public interface IBean {

   public String getField();

   public void setField(String field);


Now we will create the Bean class at runtime that extends the IBean interface:
public class Generate {
   // If a program is running on a web application server such as JBoss and Tomcat,
   // the ClassPool object may not be able to find user classes.
   // In that case, an additional class path must be registered to the ClassPool.
      // ClassPool initialization
      ClassPool.getDefault().insertClassPath(new ClassClassPath(IBean.class));

   public static IBean bean(){

      ClassPool cp = ClassPool.getDefault();

      // creation of the class
      CtClass Bean = cp.makeClass("Bean");
      // addition of the interface

      // creation of an empty constructor
      CtConstructor ctConstructor = new CtConstructor(new CtClass[]{}, Bean);

      // its body

      // addition of the constructor

      // addition of the String field
      Bean.addField(new CtField(cp.get(String.class.getName()), "field", Bean));

      // creation of getField method
      CtMethod getField = CtNewMethod.make("public String getField(){ return field; }",Bean);

      // add method to CtClass

      // creation of setField method
      CtMethod setField = CtNewMethod.make("public void setField(String field){ this.field = field; }",Bean);

      // add method to CtClass

      return (IBean) Bean.toClass().newInstance();


In this mode we can create an instance of IBean dynamically, using the IBean interface at development time:
IBean bean = Generate.bean();

The exceptions aren't handled to increase the readability.
This technique is used in the development of JMapper Framework: You can download the source.jar or checkout the code from svn.