Monday, March 31, 2014

Spring MVC Tip: Returning JSON from a Spring Controller

In my Spring MVC and Rest post, I walked through the creation of a RESTful web service with Spring MVC. Let’s now take a look at JSON.
Spring MVC, from version 3, allows you to return objects directly converted into JSON using the @ResponseBody annotation in a Controller as shown here:
@RequestMapping(method=RequestMethod.GET, value =”/movie/{name})  
public @ResponseBody Movie getMovie(@PathVariable String name, Model model){ 
    return new Movie(name);
}
In this way, AJAX interactions can be simplified, since you can deal with JSON objects after you interrogate a RESTful web service. In order to achieve that, assuming you are using Maven, you need to include the Jackson mapper dependency to your POM file as shown here:

   org.codehaus.jackson
  jackson-mapper-asl
  1.9.5
After that, you need to add to your Spring configuration file the mvc:annotation-driven configuration element and the bean with class ContentNegotiatingViewResolver:



 
   
     
     
   
 
 
   
     
       
       
       
     
   
 
 
   
     
       
     
   
 

ContentNegotiatingViewResolver, based on the supported mediaType, will determine the right view resolver. In this case the UrlBasedViewResolver would handle text/html content and the MappingJacksonView would handle application/json content. An example of a simple JSON object, containing just the name attribute, returned by the above controller could be:
{name : “Titanic”}
On the client-side, here is some JavaScript code (using jQuery) invoking the web service defined in the first snippet:
$.get(“http://www.example.com/movie/titanic”, function(data){
 // data is a JSON object
});
The callback will hold the JSON object coming from the server into the data variable. And that wraps up this tip, which will help you return objects directly converted into JSON using Spring MVC.

Friday, March 28, 2014

JPA: persisting vs. merging entites

JPA is indisputably a great simplification in the domain of enterprise applications built on the Java platform. As a developer who had to cope up with the intricacies of the old entity beans in J2EE I see the inclusion of JPA among the Java EE specifications as a big leap forward. However, while delving deeper into the JPA details I find things that are not so easy. In this article I deal with comparison of theEntityManager’s merge and persist methods whose overlapping behavior may cause confusion not only to a newbie. Furthermore I propose a generalization that sees both methods as special cases of a more general method combine.

Persisting entities

In contrast to the merge method the persist method is pretty straightforward and intuitive. The most common scenario of thepersist method's usage can be summed up as follows:

"A newly created instance of the entity class is passed to the persist method. After this method returns, the entity is managed and planned for insertion into the database. It may happen at or before the transaction commits or when the flush method is called.
 If the entity references another entity through a relationship marked with the PERSIST cascade strategy this procedure is applied to it also."




The specification goes more into details, however, remembering them is not crucial as these details cover more or less exotic situations only.

Note: If the entity has been removed from the persistence context then it becomes managed again when passed to the persist method. If the entity is detached (i.e. it was already managed) then an exception may be thrown. 

Merging entities

In comparison to persist, the description of the merge's behavior is not so simple. There is no main scenario, as it is in the case ofpersist, and a programmer must remember all scenarios in order to write a correct code. It seems to me that the JPA designers wanted to have some method whose primary concern would be handling detached entities (as the opposite to the persist method that deals with newly created entities primarily.) The merge method's major task is to transfer the state from an unmanaged entity (passed as the argument) to its managed counterpart within the persistence context. This task, however, divides further into several scenarios which worsen the intelligibility of the overall method's behavior.

Instead of repeating paragraphs from the JPA specification I have prepared a flow diagram that schematically depicts the behaviour of the merge method:




Comparison

  • persist deals with new entities (passing a detached entity may end up with an exception.)
  • merge deals with both new and detached entities
  • persist always causes INSERT SQL operation is executed (i.e. an exception may be thrown if the entity has already been inserted and thus the primary key violation happens.)
  • merge causes either INSERT or UPDATE operation according to the sub-scenario (on the one hand it is more robust, on the other hand this robustness needn't be required.)
Note: Both SQL operations are postponed at or before the transaction commits
or flush is called

  • persist makes a previously removed entity managed again
  • merge throws an exception if a previously removed entity is passed
  • persist makes the passed entity managed
  • merge copies the state of the passed entity to the managed entity
  • persist does not return any value
  • merge returns the managed entity - the clone of the passed entity
  • both methods ignore a managed entity and turn their attention to the entities referenced through PERSIST, resp. MERGE, relationships
  • In contrast to merge, passing a detached entity to persist may lead to throwing an exception.

So, when should I use persist and when merge?

persist
  • You want the method always creates a new entity and never updates an entity. Otherwise, the method throws an exception as a consequence of primary key uniqueness violation.
  • Batch processes, handling entities in a stateful manner (see Gateway pattern)
  • Performance optimization
merge
  • You want the method either inserts or updates an entity in the database.
  • You want to handle entities in a stateless manner (data transfer objects in services)
  • You want to insert a new entity that may have a reference to another entity that may but may not be created yet (relationship must be marked MERGE). For example, inserting a new photo with a reference to either a new or a preexisting album.


Design flaws

The persist method implements inserting a new entity. The merge method implements both inserting and updating. There is apparently one method missing, which would implement updating without inserting. I can go on in generalization and think about possibility to define a custom behavior that occurs when an entity is being combined with the persistence context. From this point persisting, merging and updating would be mere three strategies how to combine an incoming entity with the content of the persistence context. The EntityManager interface would contain one general method, let's call it combine(entity, strategy), that would take two arguments: the entity and the strategy used for combining the entity with the persistence context. The strategy would be an interface having two main implementations: PersistStategy and MergeStrategy which would comply with thepersist, resp. merge method. In this design both methods would simply delegate their invocations to the combine method passing the corresponding strategy instance.
The concept of cascade policies could be also generalized: instead of using the values from the CascadeType enumeration a programmer would use the class of the strategy itself as a value for the strategy attribute (or other) of the relationship annotations.
Instead:
   @OneToOne(cascade=CascadeType.PERSIST)
public Address getAddress() {
return address;
}
the code would look like this:
   @OneToOne(cascadeStrategy=PersistStrategy.class)
public Address getAddress() {
return address;
}
If the programmer wanted to declare a relationship through which the update-only entity combination strategy would be propagated to an associated entity, he/she would do it as follows:
   @OneToOne(cascadeStrategy=UpdateOnlyStrategy.class)
public Address getAddress() {
return address;
}
Some generalization should be also done in generating SQL command. Considering that the persist and merge strategies result in generating INSERT or UPDATE SQL command, there should be also some mechanism that would allow a custom strategy to generate its own SQL commands.

Monday, March 24, 2014

MySQL error code: 1175 during UPDATE in MySQL Workbench

It is look like that MySql run with safe-updates option. It mean you can't update or delete record without key (ex. primary key) on where clause.
Try use:
SET SQL_SAFE_UPDATES = 0;
or you can modify your query to follow the rule (use primary key on where clause).

Friday, March 21, 2014

doubly linked list

Insertion at the Rear of a Doubly-Linked List

Case 1: List is not empty

Assume that our linked list contains one or more nodes and that we have allocated a new list node using the pointer newNode. A diagram of the list might look like this:

To insert the new node at the rear of the list, we have to set three pointers: the prev pointer in newNode,\ the next pointer in the current last node in the list, and tail, which needs to be updated to point to the new last node in the list. (The next pointer in newNode has already been set to NULL by the constructor, so we don't need to change that.) Once we've finished, the list should look like this:

Here is the C++ code to perform these three steps:
  1. newNode->prev = tail;
  2. tail->next = newNode;
  3. tail = newNode;
The order of these steps is important. We can code Steps 1 and 2 in either order with no problems, but Step 3 must be done last. (Why?)

Case 2: List is empty

The steps above work as long as there is at least one node in the linked list. But what if the list is empty?

If we use the same steps as above:
  1. newNode->prev = tail;
  2. tail->next = newNode; // Since tail == NULL, this step causes a segmentation fault
  3. tail = newNode;
To insert the new node at the rear of an empty list, we once again have to set three pointers: the prev and pointer in newNodehead, which needs to point to the new first node in the list, and tail, which needs to be updated to point to the new last node in the list. Once we've finished, the list should look like this:

So, for an empty list, the correct C++ code to perform these three steps is:
  1. newNode->prev = tail; // Since tail == NULL, newNode->prev will be set to NULL as well
  2. head = newNode;
  3. tail = newNode;
To combine the two cases and minimize repetition of code, we can
  • Perform Step 1
  • Decide which version of Step 2 to perform based on whether or not the list is empty
  • Perform Step 3

Insertion at the Front of a Doubly-Linked List

The steps for insertion at the rear of a doubly-linked list and the steps for insertion at the front of a doubly-linked list are symmetric. This means that to write the code for push_front(), take the code you've written for push_back() and
  1. change every occurrence of head to tail, and vice versa
  2. change every occurrence of next to prev, and vice versa

Deletion at the Rear of a Doubly-Linked List

Case 1: List contains more than one node

Assume that our linked list contains two or more nodes:

The steps in C++ to remove the last node in the list look like this:
  1. LNode* delNode = tail; // Save address of node to delete in a pointer
  2. tail = delNode->prev; // Point tail at the new last node in the list
  3. tail->next = NULL; // Set the new last node's next pointer to NULL
  4. delete delNode;
Here's a diagram of the list just after Step 3:

Case 2: List contains one node

The steps above work as long as there are at least two nodes in the linked list. But what if the list only contains one node?

If we use the same steps as above:
  1. LNode* delNode = tail; // Save address of node to delete in a pointer
  2. tail = delNode->prev; // This makes tail NULL, which is what it should be
  3. tail->next = NULL; // Segmentation fault!
  4. delete delNode;
Once again, this is a special case that needs to be handled a bit differently. The correct sequence of steps in this case is:
  1. LNode* delNode = tail; // Save address of node to delete in a pointer
  2. tail = delNode->prev; // This makes tail NULL
  3. head = NULL; // If tail == NULL, head should be as well since the list is now empty
  4. delete delNode;
Here's a diagram of the list just after Step 3:

As with insertion, to combine the two cases and minimize repetition of code, we can
  • Perform Steps 1 and 2
  • Decide which version of Step 3 to perform based on whether or not the list is now empty (i.e., tail == NULL)
  • Perform Step 4

Deletion at the Front of a Doubly-Linked List

The steps for deletion at the rear of a doubly-linked list and the steps for deletion at the front of a doubly-linked list are also symmetric. This means that to write the code for pop_front(), take the code you've written for pop_back() and
  1. change every occurrence of head to tail, and vice versa
  2. change every occurrence of next to prev, and vice versa

Thursday, March 20, 2014

Exception handling in Weblogic 10.3

So who else hates checked exceptions as much as I do? As much as I like Java, this is one of the things that has always driven me nuts. So, my first goal is always to eliminate throwing checked exceptions in any project that I write. Doing this in Weblogic 10.0 and 10.3 was not such an easy feat. 

First, I created my exceptions that extended RuntimeException. This resulted in all EJB methods that throw any unchecked exception wrapping the underlying exception in a EJBException, leading to lots and lots of ugly ejb.getCausedByException() calls, which I found to be flaky at best. 

Finally, I found documentation on the @ApplicationException annotation in EJB 3 and figured this would be my savior. No such luck, they were still being wrapped in the base EJBException. After much head-scratching and googling, I came across a JBoss bug report saying that @ApplicationException is ignored in the cases where you build your EJB components into a separate jar file (which is about 98% of the time). Their solution was to add an ejb-jar.xml file with application-exceptions defined in them. So, trying this in Weblogic, still no worky. Grrr... One last thing, not sure why I did it, but out of pure stubbornness and inability to reconcile with those awful getCausedByException() calls, I made my exceptions extend EJBException instead of RuntimeException. Presto! No more wrapping.

So, in summary, to create an unchecked exception that will NOT be wrapped in an EJBException, do the following:

1) Create your exception class that extends EJBException.
2) Create an ejb-jar.xml file that looks somewhat like this to declare your application exceptions that you do not want to be wrapped in an EBException:

1234567891011121314
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd" version="3.0">
com.blogspot.andrewshouldhave.UnwrappableUncheckedException
true
view rawgistfile1.xsl hosted with ❤ by GitHub


And there you have it.

Wednesday, March 19, 2014

Diagram of Exception Hierarchy

In Java, exception can be checked or unchecked. They both fit into a class hierarchy. The following diagram shows Java Exception classes hierarchy.
Red colored are checked exceptions. Any checked exceptions that may be thrown in a method must either be caught or declared in the method’s throws clause. Checked exceptions must be caught at compile time. Checked exceptions are so called because both the Java compiler and the Java virtual machine check to make sure this rule is obeyed. Green colored are uncheck exceptions. They are exceptions that are not expected to be recovered, such as null pointer, divide by 0, etc.
Exception-Hierarchy-Diagram

Sunday, March 16, 2014

What is a Spring “stereotype”?

The JavaDoc says a bit about it.
Annotations denoting the roles of types or methods in the overall architecture (at a conceptual, rather than implementation, level).
The noun definition of sterotype from Merriam-Webster says this:
something conforming to a fixed or general pattern; especially : a standardized mental picture that is held in common by members of a group and that represents an oversimplified opinion, prejudiced attitude, or uncritical judgment
It seems that it is for suggesting a role of particular class that is being annotated. This seems to make sense because it is often recommended that you annotate your Controller classes with @Controller, Service classes with @Service, and so on.
In general, Spring suggests that they make nice point-cut demarcations for your AOP needs. (besides the obvious component-scanning functionality)

Spring annotations @Repository and @Service

The @Repository annotation (introduced in Spring 2.0) and @Service annotation (introduced in Spring 2.5) are specialization of the @Component annotation.
The main advantage of using @Repository or @Service over @Component is that it's easy to write an AOP pointcut that targets, for instance, all classes annotated with @Repository.
Also, the specialized annotations help to clearly demarcate application layers (in a standard 3 tiers application).

Friday, March 14, 2014

Double-logging in Hibernate

All I can think of:
  1. Check that your log4j config doesn't have multiple appenders defined at different levels? If you have your appender attached to the org.hibernate logger, and attached again to the org.hibernate.SQL logger, then you'll see this twice (unless you turn off additivity for the lower-level logger).
  2. You don't have the hibernate.show_sql property set on your SessionFactory? That doesn't enable logging to log4j (you do that through log4j config), it just dumps to the console. If your log4j is dumping to the console too you'll see it twice. However, that looks like a log4j format log line, not the console dumps done by hibernate, so that seems unlikely. Worth mentioning though.

Monday, March 10, 2014

What is an API?

An Application Programming Interface(API) is often referred to in various contexts making it difficult for non programmers or new programmers to grasp what an API actually is. To make the confusion worse it's meaning has evolved from what it was originally intended to more of a concept or umbrella term. Time to clear up the confusion.
Let me delve into what an API actually is, so no matter your profession you will have a correct and complete understanding of an “API”. We will do this in a few parts. First will get a general but shallow understanding of what an API is. Then we will dissect the word “Application Programming Interface” primarily to understand why it was named such.  Finally we take a look at what a real API might look like and even work with a few very simple API's so you have a practical understanding that will be sure to stick (note: anyone can do this you don't need to be a programmer.)

GETTING A GENERAL UNDERSTANDING OF AN API

wikiAn application programming interface (API) is a specification intended to be used as an interface by software components to communicate with each other.
TaylorAn Application Programming Interface is a set of instructions on how one program can be worked with by another outside program.
So what the heck does that mean? Lets clear this up a bit. As a programmer the way we develop big complex programs is by writing lots of little programs and then putting them all together. For example: Lets say the big program is (the evil) Facebook, a little program that we might need to write so we can use it in the bigger program is a “Poke” program.
The “Poke Program” allows one user to poke another user. The user that is poked is then notified that they were poked and may choose to poke back if the wish.
So to complete the Facebook program we need to write lots of other little programs such as a “like program”, “add friend program”, “login program” , “chat program” and so on. We call all these little programs our library of programs or code library. Once we are done we realize that by letting others use some of our little programs we can grow our facebook platform even more. Facebook does just that and documents and allows anyone the ability to use a number of these little programs.
All of the little programs that Facebook lets others use is known as the “Facebook API”.
I will go into how exactly how “anyone has the ability to use” a little facebook program in the section below.
Facebook API
Screen shot of just a few of the “Little Programs” that make up the Facebook API.

BREAKING DOWN THE WORD “APPLICATION PROGRAMMING INTERFACE”

So to understand the word "Application Programming Interface" we need to back up a second and look at how it originated. So before the web was around, when we talked about programming were were generally talking about either System programming (Windows OS) or application programming (software that ran on top of windows OS, calculators, minesweeper, paint etc...). In order for the application programmers to be able to develop their applications they needed to tap into or interface with the Windows operating system. So naturally Windows offered the .Windows Application Programming Interface. - which was a manual on how application programs could tap into the Windows OS.
As the web and many other technologies evolved the term API seemed to stick even for software and technology that was not specific to the "Application Programming" Context. So now the term API is commonly used to refer to any sort of program to program interface. I'd suggest a better name would be "Program to Program Interface" - but after giving "PPI" a google it looks pretty soundly used - maybe we could take over "PTPI" from these guys http://www.ptpi.org/
Another player that helped the term "API" stick was the commonly referred to "Advanced Programming Interface" also acronym-ed "API". The "Advanced Programming Interface" was a manual on how to work with complex pieces of software.
So there we have it the term "API" is born and brought into the modern age. The common misuse of the word becomes widely accepted and "API" becomes the bona fide term for how one program is able to interact with another program. I will keep pushing for the acronym PPI to become widely accepted..... but I wouldn't hold your breath.

REAL LIFE USAGE OF API'S

So now you should generally understand what an API is, but may not really understand how one can work with or use an “API”. Let's take the facebook API and discuss in detail what it may look like and how one can work with it. So for all of the little programs that make up the Facebook API: “like program”, “add friend program”, “login program” , “chat program”, “poke program” facebook will have a snibbit of documentation. (Every API documentation looks a little different but generally try to follow some common format shown below.)
Lets look at what the “Poke Program” documentation may look like this
NOTE: THIS IS NOT A REAL API JUST AN EXAMPLE
Program name : Poke

Details: “Poke” allows one user to poke another user. The user that is poked is notified of the poke and may choose to poke back.

Usage: When being used the little poke program needs to know the id of the user who is doing the poking and the id of the user who is getting poked.

Description: Poke program may be accessed over http at the following url, the “from_poker” parameter should be a integer and the “to_poker” should be and integer.

Url: http://www.facebook.com/api/poke?from_poker=123&to_poker=234
So if (this were real and) you went to the following url in your browser “http://www.facebook.com/api/poke?from_poker=123&to_poker=234” you would have just made user “123” poke user “234” - Congrats. We will do some real examples in a second.
So this is an example of accessing an API over the web, this is how most API's today are accessed and will generally be what people are talking about when they say “API”. Fun fact -  API's that are accessed over the web are called “Web Services” and use the HTTP protocol.
The cool thing about these API's is that non programmers could potentially work with them (and we will in a moment) as all they have to do is type a URL with some particular parameters into a browser.
There are also other ways of working with API's that require one to write code, but the principle is the same: there is some little program written by party 1 that is now letting party 2 use that program. Example:  The “poke program” may also be accessed in some programming language by including the “facebook code library” and then calling the little poke program.
Include facebook_code_library;

call facebook_poker(123,234);
This piece of code has the same effect as going to the Facebook “Poke URL”,  we simply used a different protocol to work with the API.
So now you should have a good understanding of what an API is even how to work with one. In order to not dumb people down it's worth mentioning that not all API's are accessible over the web, some may only be accessible by using a particular programming language. The windows operation system for example has an API that is very confusing and only accessible through programming languages known by the uberist off Geeks.
REAL LIFE API EXAMPLES
And now the fun stuff - lets look at few Web API's so we can get a feel for how they are used.
First lets take look at this awesome “Zip Code Catcher API” built by some unknown stud developer.
Here is the documentation:
Name: Zip Code Catcher

Description: Lets a user download all the zip codes that lie within a given circle.

Url Parameters:
shape: circle (may be able to take in additional shapes in the future)
center: Is a [lat,lng] points on the earth radius: Is the radius of the circle given in meters.

API Urlhttp://www.woodstitch.com/rest/zip_codes.php?shape=circle&center=[34.08,-118.26]&radius=17455
If you hit that example URL the “Zip Code Catcher” will download all the zip codes within a 17,455m (ruffly 10 mile) radius of the center point [34.08,-118.26] which just so happens to be Los Angeles. You can change the center or the radius to get different results - pretty cool huh.
Here is another cool API that you could use, that allows a user to give a keyword topic as a parameter and then outputs a paragraph of text about that topic. If you want to build your own API just snag some web hosting from this list and start coding out.
Name: Keyword to Paragraph tool

Description: lets the user input a keywords and returns a unique paragraph of content about that keyword

URL Parameters:
pass: “allowme”
keyword: any keyword that the user want a topic on

API URL: http://assets.giverose.com/contentspinner/get_topic_content.php

Examplehttp://assets.giverose.com/contentspinner/get_topic_content.php?pass=openup&topic=big bird

So hit that url and you will see that it gives you a paragraph of unique content about big bird. Pretty Cool huh!
Note:  Some API's such as this one require a password, this gives  the person who owns the API control over how the want other to use their programs. 
I trust that no one will use this API for SPAM or any unethical and shady business practices... O wait thats the only things it's good for. What hack is building these tools anyway :)
I hope after reading this you have a better understanding of what an API is, how they work and are used in day to day business. Questions, comments, feedback and suggestions are welcomed.

Friday, March 7, 2014

Comparing two array in java

public static void compareArrays(int[] array1, int[] array2) {
        boolean b = true;
        if (array1 != null && array2 != null){
          if (array1.length != array2.length)
              b = false;
          else
              for (int i = 0; i < array2.length; i++) {
                  if (array2[i] != array1[i]) {
                      b = false;    
                  }                 
            }
        }else{
          b = false;
        }
        System.out.println(b);
    }
http://stackoverflow.com/questions/14897366/comparing-two-array-in-java