Wednesday, 18 September 2013

Java Reflection Notes – getDeclaredAnnotations vs getAnnotations method -vs-getannotations-method

This is just going to be a very short notes about difference between the getDeclaredAnnotations and getAnnotations method of Java java.lang.Class<T> class.
I was googling for the answer but didn’t immediately got any article that explains it, so I thought why I not create it myself.
So what is the difference:
In short:
- getAnnotations basically gets all annotations that are also inherited from the parent class.
- getDeclaredAnnotations gets annotations declared ONLY on the class
If you rather believe what the code says rather than me, here’s the code:

public class CheckTest {

@Retention(RetentionPolicy.RUNTIME)
@Inherited

public @interface CustomAnnotation{
String value();
}
@CustomAnnotation("label")
public static class Parent{
}
public static class Child extends Parent{

}
/**
* @param args
*/
public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();
System.out.println("Parent class:");
System.out.println("  getDeclaredAnnotations: " +
parent.getClass().getDeclaredAnnotations().length);
System.out.println("  getAnnotations: " +
parent.getClass().getAnnotations().length + "\n");
System.out.println("Child class:");
System.out.println("  getDeclaredAnnotations: " +
child.getClass().getDeclaredAnnotations().length);
System.out.println("  getAnnotations: " +
child.getClass().getAnnotations().length);
 }
}

The output result is:

Parent class:
getDeclaredAnnotations: 1
getAnnotations: 1
Child class:
getDeclaredAnnotations: 0
getAnnotations: 1
Notice that the Child getAnnotations array length is 0, because by itself the Child class doesn't has annotations. :D

Tuesday, 17 September 2013

Accessing Generic Types At Runtime In Java

I was writing my n-th Dao implementation, this time using JPA.
I (and probably a whole lot of others) usually create a DAO per entity, parameterizing the entity type.
Specific DAO instances for entities implement the generic DAO using their entity type as type parameter. One generic DAO implementation exists, containing common operations like findById, persist, remove, etc. This generic DAO uses the class type specified by the implementing DAO classes (e.g. a Person) to manipulate or query the entity specified by this type. The (slightly) annoying problem for me has always been to instantiate that entity type in the generic DAO superclass. I’ve always done this by just creating a constructor in the generic DAO which takes a class argument containing the required Class of the entity. However, there’s a better way, which I’ll show in this post.
To start with an example, the generic DAO interface looks like this:
public interface GenericEntityDao {

   T findById(Serializable id);

   List findAll();

   ... more methods omitted
}
And its generic DAO implementation class looks something like this:
public abstract class GenericJpaDao implements GenericDao {

  private Class entityBeanType;

  @PersistenceContext
  private EntityManager entityManager;

  public T findById(Serializable id) {
     return entityManager.find(getEntityBeanType(), id);
  }

  public List findAll() {
      return entityManager.createQuery("from " + getEntityBeanType().getName() )
                          .getResultList();
  }

  protected Class getEntityBeanType() {
      return entityBeanType;
  }
  ... more methods omitted
 
}
The question is, how do we obtain the parametized type of T for the entityBeanType field to use in our queries? Earlier, I used to just instantiate this type in the constructor, like so:
public GenericJpaDao(Class entityBeanType) {
     this.entityBeanType = entityBeanType;
}

public JpaPersonDao extends GenericJpaEntityDao implements PersonDao {
   public PersonDao() {
      super(Person.class);
   }
}
But this is a bit silly, since we already know from the type parameter that the entity we’re interested in has type Person.
However, there is an easier way out: we can use Java’s ParameterizedType class to obtain information about the declared generic type. As stated in the javadoc:
/**
* ParameterizedType represents a parameterized type such as
* Collection<String>.
*
* A parameterized type is created the first time it is needed by a
* reflective method, as specified in this package. When a
* parameterized type p is created, the generic type declaration that
* p instantiates is resolved, and all type arguments of p are created
* recursively.

Thus, it seems that ParameterizedType contains the information that we want. How do we obtain an instance of it? The answer lies in Java’s getGenericSuperclass method, defined on the Class object. This returns a Type representing the superclass of this Class. The Javadoc of the method states the following:
* If the superclass is a parameterized type, the Type
* object returned must accurately reflect the actual type
* parameters used in the source code. The parameterized type
* representing the superclass is created if it had not been
* created before.


The Type interface itself is just a marker interface, containing no methods. Depending on the case at hand, an Type extending the Type interface will be returned. In our case, we’ll use the getGenericSuperclass method on a class extending our GenericJpaDao class. Thus, the superclass is JpaGenericDao, which is a parameterized type. In this case, the actual the Type object returned by getGenericSuperClass will be a ParameterizedType instance. This class contains a methodgetActualTypeArguments, which returns an array containing all generic type parameters used in the source code.
This is precisely what we desire, so in our GenericJpaDao class constructor, can get rid of the Class argument, and instead do the following:
  @SuppressWarnings("unchecked")
  public GenericJpaDao() {
    this.entityBeanType = ((Class) ((ParameterizedType) getClass()
        .getGenericSuperclass()).getActualTypeArguments()[0]);
  }
We know there’s precisely one type argument in our class, so we can take the first element of the array that is returned, which provides the Class of our entity. Thus we can get rid of all the annoying constructors with Class arguments, and handle determination of the entity type in just one place.
This may not provide the highest amount of code reduction you have ever experienced, but it’s a neat trick in any case.

Monday, 16 September 2013

Java: Change one date format to another formate


  1. static public String FormatDate(String input) throws ParseException {

  2.         if (input != null) {
  3.             SimpleDateFormat oldFormate = new SimpleDateFormat();
  4.             oldFormate.applyPattern("yyyyMMddHHmmss");
  5.             //  System.out.println("input::"+input);

  6.             Date dt = oldFormate.parse(input);
  7.             // System.out.println("Date::"+dt);
  8.             SimpleDateFormat newFormate = new SimpleDateFormat();
  9.             newFormate.applyPattern("dd-MM-yyyy HH:mm:ss");

  10.             return newFormate.format(dt);
  11.         }
  12.         else
  13.         {
  14.             return input;
  15.         }
  16.     }

Tuesday, 10 September 2013

JavaFX Sketch Pad


package jayfx;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class Draw2 extends Application {
private Path path;
private Group lineGroup;
private static final Double DEFAULTSTROKE = 3.0;
private static final Double MAXSTROKE = 30.0;
private static final Double MINSTROKE = 1.0;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Drawing Tool");
final Group root = new Group();
Scene scene = new Scene(root, 600, 400);
// A group to hold all the drawn path elements
lineGroup = new Group();
// Build the slider, label, and button and their VBox layout container
Button btnClear = new Button();
btnClear.setText("Clear");
btnClear.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
lineGroup.getChildren().removeAll(lineGroup.getChildren());
}
});
Slider strokeSlider = new Slider(MINSTROKE, MAXSTROKE, DEFAULTSTROKE);
Label labelStroke = new Label("Stroke Width");
VBox utilBox = new VBox(10);
utilBox.setAlignment(Pos.TOP_CENTER);
utilBox.getChildren().addAll(btnClear, labelStroke, strokeSlider);
// Build the sample line and its layout container
final Line sampleLine = new Line(0, 0, 140, 0);
sampleLine.strokeWidthProperty().bind(strokeSlider.valueProperty());
sampleLine.setStroke(Color.BLUE);
StackPane stackpane = new StackPane();
stackpane.setPrefHeight(MAXSTROKE);
stackpane.setPrefWidth(sampleLine.getEndX() + MAXSTROKE);
stackpane.setAlignment(Pos.CENTER);
stackpane.getChildren().add(sampleLine);
// Build the color label and its layout container
final Label colorLabel = new Label("color: blue");
StackPane stackpane2 = new StackPane();
stackpane2.setPrefHeight(MAXSTROKE);
stackpane2.setPrefWidth(sampleLine.getEndX() + MAXSTROKE);
stackpane2.setAlignment(Pos.CENTER_LEFT);
stackpane2.getChildren().add(colorLabel);
// Build the HBox layout container for the two stackpane's
HBox lineBox = new HBox(20);
lineBox.setAlignment(Pos.CENTER);
lineBox.getChildren().addAll(stackpane, stackpane2);
// Build the color picker and use a flowpane
FlowPane flow = new FlowPane();
flow.setVgap(2);
flow.setHgap(2);
flow.setPrefWrapLength(400);
// Get the declared fields for the Color class
Field[] colorFields = Color.class.getDeclaredFields();
for (Field fieldname : colorFields) {
int mods = fieldname.getModifiers();
// Only look at the field if it's public, static, and NOT 'TRANSPARENT'
if (Modifier.isPublic(mods) && Modifier.isStatic(mods)
&& !(fieldname.getName().equals("TRANSPARENT"))) {
try {
Color c = Color.web(fieldname.getName());
// Make a rectangle with that field name's color
final Rectangle r = new Rectangle(15, 15, c);
// Configure the rectangle
r.setCursor(Cursor.HAND);
Tooltip t = new Tooltip(fieldname.getName().toLowerCase());
Tooltip.install(r, t);
r.setUserData(t.getText());
r.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
sampleLine.setStroke(r.getFill());
colorLabel.setText("color: " + ((String) r.getUserData()));
}
});
flow.getChildren().add(r);
} catch (IllegalArgumentException e) {
// just ignore it if for some reason we can't make
// a color
}
}
}
// Build the layout container for the VBox utility box and the flowpane
HBox toolBox = new HBox(10);
toolBox.setAlignment(Pos.TOP_CENTER);
toolBox.getChildren().addAll(utilBox, flow);
// Build the canvas
final Rectangle canvas = new Rectangle(scene.getWidth() - 20, scene.getHeight() - 230);
canvas.setCursor(Cursor.CROSSHAIR);
canvas.setFill(Color.LIGHTGRAY);
canvas.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
path = new Path();
path.setMouseTransparent(true);
path.setStrokeWidth(sampleLine.getStrokeWidth());
path.setStroke(sampleLine.getStroke());
lineGroup.getChildren().add(path);
path.getElements().add(new MoveTo(me.getSceneX(), me.getSceneY()));
}
});
canvas.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
path = null;
}
});
canvas.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
// keep lines within rectangle
if (canvas.getBoundsInLocal().contains(me.getX(), me.getY())) {
path.getElements().add(new LineTo(me.getSceneX(), me.getSceneY()));
}
}
});
// Build the VBox container for the lineBox, canvas, and toolBox
VBox vb = new VBox(20);
vb.setLayoutX(10);
vb.setLayoutY(20);
vb.getChildren().addAll(lineBox, canvas, toolBox);
root.getChildren().addAll(vb, lineGroup);
primaryStage.setScene(scene);
primaryStage.show();
}
}

Java RMI Architecture