giovedì 1 ottobre 2015

Partial mapping with JMapper

Hi guys,

with this post i will illustrate how is possible define a mapping strategy with JMapper.
The classic scenario is a mapping where value from source must be passed to destination, but there are cases where what we need is pass from source only valorized fields or.. we want that only the null fields of destination will be mapped.. this cases are handled very well by JMapper.

The following example will use these classes:

class Destination {              class Source {

   @JMap String name;               String name;
   @JMap Integer age;               Integer age;
   @JMap String company;            String company;

   // getters and setters..         // getters and setters..

}                                }

JMapper istance generation:

JMapper<Destination, Source> mapper = new JMapper<>(Destination.class, Source.class);

Ok, it's arrived the moment to see what Jmapper permits to do.

We want to take only the valued fields of Source:

Destination destination = new Destination("empty", null, "Anonymous");
Source source = new Source("Alessandro", 30, null);

Destination result = mapper.getDestination(destination, source, MappingType.ALL_FIELDS, MappingType.ONLY_VALUED_FIELDS);
Destination[ name="Alessandro", age=30, company="Anonymous"]
We want just fill null fields of Destination:

Destination destination = new Destination("empty", null, "Anonymous");Source source = new Source("Alessandro", 27, null);

Destination result = mapper.getDestination(destination, source, MappingType.ONLY_NULL_FIELDS, MappingType.ALL_FIELDS);

Destination[ name="empty", age=30, company="Anonymous"]

There are a lot of other combinations.. try to find yourself    :)

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 :)