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.io.IOException;
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);
 }

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

          if (kind == OVERFLOW) continue;
          
          // The filename is the
          // context of the event.
          @SuppressWarnings("unchecked")
          Path fileName = ((WatchEvent)event).context();
             
          if(!fileName.equals(fileToWatch))
              continue;
             
          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) {
          break;
      }
  }
 }

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

An example of use:

new Thread(new FileWatcher(filePath){
               @Override
               public void modify() {
                  System.out.println("modified");
               }
           }).start();

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.
Solution:
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 "";
   }
}

Output:

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.
   static{
      // 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
      Bean.addInterface(cp.get(IBean.class.getName()));

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

      // its body
      ctConstructor.setBody(";");

      // addition of the constructor
      Bean.addConstructor(ctConstructor);

      // 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
      Bean.addMethod(getField); 

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

      // add method to CtClass
      Bean.addMethod(setField); 

      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();
bean.setField("example");
assertEqual("example",bean.getField());

The exceptions aren't handled to increase the readability.
This technique is used in the development of JMapper Framework: http://code.google.com/p/jmapper-framework/ You can download the source.jar or checkout the code from svn.

giovedì 10 gennaio 2013

JMapper Framework 1.1.1 released!

With this released the features added are:

Inherited configuration

Now we can define a common configuration/conversions in the superclass, less code, less redundance and less maintenance.

Implicit conversion between arrays and collections

With this features we can configure arrays with collections and vice versa, with any type of items (primitive, wrapper and mapped).

OneToMany method changed

To prevent unexpected behavior in case of singleton pattern usage in multi-threaded environment, the definition of the target class will be done through the passage of the class as input to the method. For more information: http://code.google.com/p/jmapper-framework/

venerdì 4 gennaio 2013

how to generate the hql query from the instance

In some cases we have the need to transform an object in an hql query considering only the valued properties, going in introspection also. For example, we have the following class:
class Bean{

   Integer id;
   String description;
   String other;

   // getter and setter..
}
The scope is to include in the HQL query only the valorized properties of this bean. then we immediately think of a cascade of if:
String hql = "Select Bean from Bean";
boolean isWhere = true;

if(bean.getId() != null) {
   if(isWhere){
      hql += " Where ";
      isWhere = false; 
   }else{
      hql += " and ";
   }
   hql += "Bean.id = " + bean.getId();
}

if(bean.getDescription() != null) {
   if(isWhere){
      hql += " Where ";
      isWhere = false; 
   }else{
      hql += " and ";
   }
   hql += "Bean.id = " + bean.getDescription();
}

// etc..
The result is a HQL query generated at runtime, but the code written isn't generic and you must in all cases write custom code. Follows an algorithm created by me, a recursive function that permits to write hql query in every situation:
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;

class Generate {

   private boolean isWhere;
 
   public String hql(Object obj){
        isWhere = true;
        String alias = ob.getClass().getSimpleName().toLowerCase();
        return hql(obj, alias, true);
   }

   private String hql(Object ob, String alias, boolean isFirst){
     
      Class<? extends Object> obClass = ob.getClass();
      StringBuilder sb = new StringBuilder();
  
      if (isFirst)
         sb.append("SELECT "+alias+" FROM "+obClass.getSimpleName()+" as "+alias);

      try {

         for (Field field : obClass.getDeclaredFields()) {
              
            Class<?> fieldType = field.getType();
            String fieldName = field.getName();
    
            if(!isCollection(fieldType) && !isSerialVersionUID(fieldName)){
 
               Object fieldValue = null;
   
               try{ fieldValue = obClass.getMethod(mGet(fieldName)).invoke(ob);
               }catch(Exception e){
                  // some fields don't have get method
                  // for example serialVersionUID    
               }
     
               if (fieldValue != null)

                  // if the field is complex type it goes into introspection
                  if (isFk(fieldType))
                     sb.append(hql(fieldValue, alias+"."+fieldName, false));
                  
                  else { 
                     if (isWhere) { 
                        sb.append(" WHERE ");
                        isWhere = false;
                     } else 
                        sb.append(" AND ");
   
                     sb.append(alias+"."+fieldName+" = "+getValue(fieldValue, fieldType));
                  }
             }
          }
      } catch (Exception e) { /** to handle **/ }

      return sb.toString();
   }
    
   private String getValue(Object value, Class<?> field) {

        StringBuilder sb = new StringBuilder();
 
        try { if (field.equals(String.class)
               || field.equals(Character.class)
               || field.equals(char.class))    sb.append("'"+value+"'");

              else
                 if(field.equals(Date.class))  sb.append("to_timestamp('"+value+"')");
                 else                          sb.append(value);
     
        } catch (Exception e) { /** to handle **/ }

        return sb.toString();
   }
 

   public static final ArrayList basicTypes = 
   
   new ArrayList(){
      private static final long serialVersionUID = -5567529960231273742L;

      {
        add(byte.class.getName());
        add(short.class.getName());
        add(int.class.getName());
        add(long.class.getName());
        add(float.class.getName());
        add(double.class.getName());
        add(char.class.getName());
        add(boolean.class.getName());
        add(Byte.class.getName());
        add(Short.class.getName());
        add(Integer.class.getName());
        add(Long.class.getName());
        add(Float.class.getName());
        add(Double.class.getName());
        add(Character.class.getName());
        add(Boolean.class.getName());
        add(String.class.getName());
        add(Date.class.getName());
      }
   };
 
   private boolean isCollection(Class<?> aClass){
      return Collection.class.isAssignableFrom(aClass);
   }
 
   private String mGet(String s) {
      return "get" + s.substring(0, 1).toUpperCase() + s.substring(1);
   }
 
   private boolean isSerialVersionUID(String field) {
      return field.equals("serialVersionUID");
   }

   private boolean isFk(Class<?> field) {
      return !basicTypes.contains(field.getName());
   }
} 
The exceptions aren't handled so to focalize the attention on the algorithm. An example of use:
   Bean bean = new Bean(2013,"description");
   
   String hql = new Generate().hql(bean);

   assertEqual("SELECT bean FROM Bean as bean WHERE bean.id = 2013 and bean.description = 'description'", hql);