Friday, October 26, 2012

Spring MVC using MongoDB as Database

In this tutorial we will create a simple Spring MVC 3 application that uses a document-oriented database for its persistence layer. We will be using MongoDB as our database. We will explore and discover how easy it is to integrate MongoDB with Spring MVC 3. Our application is a simple CRUD service for managing a list of Persons. We will provide functionalities for adding, deleting, editing, and viewing of all registered persons.

MongoDB
These are few benefits with MongoDB.
  • Document-oriented storage
  • Full Index Support
  • Replication & High Availability
  • Scale horizontally without compromising functionality.
  • Rich, document-based queries.
  • Atomic modifiers for contention-free performance.
  • Flexible aggregation and data processing.
  • Store files of any size without complicating your stack.
  • Enterprise class support, training, and consulting available. 
In a nutshell MongoDB uses JSON instead of SQL There's no static schema to create. All schemas are dynamic, meaning you create them on-the-fly. You can try a real-time online shell for MongoDB at http://try.mongodb.org/.

In order to complete this tutorial, you will be have to install a copy of MongoDB. You can download from http://www.mongodb.org/display/DOCS/Quickstart. The installation is really easy.

MongoDB is used if there are more number of write than reads. Some thing like Audit logs which will have frequent writes than reads and also huge data will be stored.
pom.xml 
(download source code link is provided for complete project access)


Lets start with MongoDBFactory.

MongoDBFactory.java


method "getMongo()" will be used to  get Mongo DB reference using host and port.
method "getDB()" Will be used to get reference to your DB created. This is some thing like MySql
"create database myDatabase".  This method is trying to get "myDatabase" from MongoDB.
method "getCollection()"  collections are like tables in mongodb stored as key value pairs.

Instead of factory if you want to write the same code it will look like below.
// Retrieve a db
Mongo m = new Mongo( "localhost" , 27017 );
m.getDB("mydb"); // where mydb is the database name
 
// Retrieve a collectionn
Mongo m = new Mongo( "localhost" , 27017 );
DB db = m.getDB("mydb");
db.getCollection("mycollection"); // where mycollection is the collection name
 
The same you can see in command prompt below.
 

Now our schema is based on Person class. Below is the class Person we like to store in the DB.
Person.java

Now "PersonService" java class to do CRUD operations.
PersonService.java

This service defines our basic CRUD system. We have the following public methods:
getAll() - for retrieving all persons
edit() - for editing
delete() - for deleting
add() - for adding
get() - for retrieving single person

We also have the following private methods:
init() - for initializing our database
getDBObject() - for retrieving a single Mongo object

The database is initialized once in the PersonService's constructor through the init() method:
private void init() {
  // Populate our MongoDB database
 
  logger.debug("Init MongoDB users");
 
  // Drop existing collection
  MongoDBFactory.getCollection("mydb","mycollection").drop();
  // Retrieve collection. If not existing, create a new one
  DBCollection coll = MongoDBFactory.getCollection("mydb","mycollection");
   
  // Create new object
  BasicDBObject doc = new BasicDBObject();
  // Generate random id using UUID type 4
        doc.put("id", UUID.randomUUID().toString());
        doc.put("firstName", "Naresh");
        doc.put("lastName", "Kancharla");
        doc.put("money", 1000);
        coll.insert(doc);
   
        // Create new object
        doc = new BasicDBObject();
  // Generate random id using UUID type 4
        doc.put("id", UUID.randomUUID().toString());
        doc.put("firstName", "Keerthi");
        doc.put("lastName", "Kancharla");
        doc.put("money", 2000);
        coll.insert(doc);
         
        // Create new object
        doc = new BasicDBObject();
  // Generate random id using UUID type 4
        doc.put("id", UUID.randomUUID().toString());
        doc.put("firstName", "Kanish");
        doc.put("lastName", "Gupta");
        doc.put("money", 3000);
        coll.insert(doc);
   
 }
 
If you Notice we're creating a dynamic JSON schema here with the following format:
{ 
   id:'',
   firstName:'',
   lastName:'',
   money:''
}
 
To run this flow we need Spring MVC Controller.

To view complete code below i provided GitHub source code link.

This controller declares the following mappings:
/persons - for retrieving all persons
/persons/add (GET) - displays the Add New form
/persons/add (POST) - saves the new person
/persons/delete - deletes an existing person
/persons/edit (GET) - displays the Edit form
/persons/edit (POST) - saves the edited person

Each mapping delegates the call to the PersonService.
When the PersonService is done processing, the controller then forwards the request to a JSP page
that displays a confirmation message. Here are the JSP pages.

personpage.jsp





editpage.jsp

addpage.jsp
 
  editedpage.jsp

addedpage.jsp
deletedpage.jsp
Spring MVC Configuration xmls are defined below.

web.xml
<servlet>
 <servlet-name>spring</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>spring</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
Above web.xml we defined DispatcherServlet as "spring" so there should be a xml with name "spring-servlet.xml" for view resolution.
spring-servlet.xml

 <!-- Declare a view resolver -->
 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/" p:suffix=".jsp" />


applicationContext.xml
<!-- Activates various annotations to be detected in bean classes -->
 <context:annotation-config />

 <!-- Scans the classpath for annotated components that will be auto-registered as Spring beans.
  For example @Controller and @Service. Make sure to set the correct base-package-->
 <context:component-scan base-package="*" />

 <!-- Configures the annotation-driven Spring MVC Controller programming model.
 Note that, with Spring 3.0, this tag works in Servlet MVC only!  -->
 <mvc:annotation-driven />

When the application is initially run, we mentioned that it will drop and create a new collection. So MongoDB's console should reflect this action as well.


Now let's access the main page that shows all registered persons. To access the main page, enter the following URL in your browser:
http://localhost:8080/SpringMongoDB/main/persons
Here's what you should see:

Here's the log from MongoDB's console: Fri Oct 26 20:32:08 [initandlisten] connection accepted from 127.0.0.1:51259 #6 (3 connections now open)

Let's edit the first record in our list by clicking the Edit link. We will be redirected to the Edit Person page:


Here's the log from MongoDB's console:
Fri Oct 26 20:34:40 [conn8] update mydb.mycollection query: { _id: ObjectId('508aa5ecad8450d889bc351a'), id: "1d11324e-ee91-4e50-84ef-b7e5e141


, firstName: "Keerthi", lastName: "K", money: 2500.0 } nscanned:1 nupdated:1 keyUpdates:0 locks(micros) w:107793 108ms

After editing the person and submitting the changes, we should see the following page:


That's it. We've managed to create a simple Spring MVC 3 application that uses MongoDB
for its database. We've also seen the benefits of a document-oriented database
when we created the schema dynamically.

Download the source code:

Wednesday, October 17, 2012

Spring MVC & Spring Security Example

Topics Covered
1) Spring MVC basic wiring using annotation
2) Integrate Spring Security for login page.
3) How to use message bundle.
4) How to encrypt password instead of plain full text.
5) How to use multiple Controllers for each jsp. (ex: HelloWorldController.java will listen to hello.jsp )
6) How to use same controller for different form actions (ex LoginController.java will listen to login.jsp)



In this example,  show you how to create a Spring @MVC annotation-based hello world example
1)AbstractController or SimpleFormController no longer needed to extend, just simply annotate the class with a @Controller annotation

2)  No more declaration for the handler mapping like BeanNameUrlHandlerMapping, ControllerClassNameHandlerMapping or SimpleUrlHandlerMapping, all are replaced with a standard @RequestMapping annotation.

Maven Respository pom.xml


File: LoginController.java


This controller is defined as multi actions controller. Based on URI methods will be invoked.
In this case, if an URI pattern “/login” is requested, it will map to login() method.

We can also define entire controller for a single URI or single action. For this @RequestMapping is applied at class level and at method level @RequestMapping(method = RequestMethod.GET) to indicate which method to handle the mapping request.

Integrate Spring in our Web application
for this we have to modify web.xml
File: web.xml



DispatcherServlet looks for [servlet-name]-servlet.xml in the WEB-INF directory of your web application.
So here springDispatcher-servlet.xml holds MVC related metadata into it.

ContextLoaderListener:
1.ContextLoaderListener is defined if you want to have multiple configuraton xmls. Otherwise you can define in Dispatcher Servlet as init-param
2.So You can provide additional configuration files through this root web application context using ContextLoaderListener listener that comes with Spring MVC.
3.listener looks for /WEB-INF/applicationContext.xml by default, but you want to override it using the context parameter contextConfigLocation as shown above.

SpringSecurityFilterChain
The 'springSecurityFilterChain' filter needs to be configured to intercept all URLs so Spring Security can control access to them.

In the above web.xml ContextConfigLocation is referring to 2 xmls.
1) springDispatcher-Servlet.xml   2) spring-Security.xml
Below are the xmls.

File: springDispatcher-Servlet.xml

After the controller has returned, DispatcherServlet looks for a view resolver to resolve the view name that it got from the ModelAndView object. You will use InternalResourceViewResolver for resolving view names to JSP.
What this resolver does is take the view name, prepend the prefix and append  the suffix, and look for a resource with the produced name.

File: spring-Security.xml
  1. login-page=”/login” – The login form will be “/login”
  2. default-target-url=”/welcome” – If authentication success, forward to “/welcome”
  3. authentication-failure-url=”/loginfailed” – If authentication failed, forward to “/loginfailed”
  4. logout-success-url=”/logout” – If logout , forward to “/logout”
LoginController.java is shown in the above will handle /login and /welcome URIs.

Error Messages
In Spring Security, when authentication is failed, following predefined error messages will be displayed :
Spring display : Bad credentials

Default Spring’s error message is not user friendly enough. We can override error message and display custome
messgaes.


Spring Security stores messages in "messages.properties" inside "spring-security-core.jar".To override it,find which key generate what error message in spring security message.properties file, and redefine it with your own properties file.Create a new properties file, put it on project classpath, and override the Spring’s "key" with your custom error message.

In this case, just override "AbstractUserDetailsAuthenticationProvider.badCredentials".

File : mymessages.properties
     AbstractUserDetailsAuthenticationProvider.badCredentials=Invalid username or password

To load above properties file, define ResourceBundleMessageSource in Spring bean configuration file.

This is define in above springDispatcher-Servlet.xml
<bean id="messageSource"     class="org.springframework.context.support.ResourceBundleMessageSource">
       <property name="basenames">   
         <list>
           <value>mymessages</value>   
          </list>
        </property>
</bean>

JSP ViewsIn custom login form, you have to follow Spring Security standard name :

1.j_spring_security_check - Login service
2.j_spring_security_logout - Logout service
3.j_username - Username
4.j_password - Password

To display authentication error messages, use this :
${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}

File : login.jsp
   
File : hello.jsp 
Output
The flow is like this. 1) Login.jsp after successfully login spring-Security.xml will take to /welcome. 2) LogingController.java has /welcome method for URI. 3) /welcome method in Controller take to hello.jsp with username as message. (see LoginController.java) 4) see hello.jsp below screen

5) Above hello.jsp has text box. hello.jsp has action as "moveToEmailPage". URI "moveToEmailPage" is define in another
controller as shown below.

6) URI "moveToEmailPage" method in controller is forwarding to "HelloWorldThirdPage". Now view resolver will
forward request to HelloWorldThirdPage.jsp.
Image: HellowWorldThirdPage.jsp


To Access source code. Please click below link
https://bitbucket.org/nkancharla/javaexamples/src/5f8c707a30cd741f5c282fd855b9b6dfb6ead820/SpringSecurity1?at=master

Monday, October 15, 2012

Run JavaScript from Java

Scripts can be executed from within java in the JVM. Let us take javascript language for this example. There are couple of important classes in this package and they are,
ScriptEngineManager and ScriptEngine.

ScriptEngineManager: It has 2 roles
1) Discovery of Script Engine.
2) Storing data in context. (This is shared across programs)

ScriptEngine:
This is an interface available in javax.script. Here we have to specify the scripting language.

Below is the example.



You can access source code from below link.
https://bitbucket.org/nkancharla/javaexamples/src/9582af48772c496f004485762c45dbea690cf551/InvokeJavaScript/src/InvokeJavaScript.java?at=master



Sunday, June 24, 2012

Java Shutdown Hooks


What is Shutdown Hook
We know that in some situations we will have to do some clean-up operations  when the user shuts down our application. Sometimes  the user does not always follow the recommended procedure to exit the application. Java provides an API for programmers to execute code in the middle of the shutdown process,this in turn make sure that our clean-up code is always executed.
This article shows how to use a shutdown hook to guarantee that clean-up code is always run, regardless of how the user terminates the application.
Shutdown Hook is a simple thread which is registered in JVM.
It can be registered by using addShutdownHook (Thread hook). It is a method of java.lang.Runtime class
Some Important points to be remembered:
1) When JVM starts shut down process,  it starts execution of its all registered shutdown Hook  concurrently.
2) You can use Shutdown hook if you want to display messages or execute some code before JVM shut down.
3) We cannot register Shutdown Hook during shut down process. It will through IllegalStateException.
4) We cannot guaranteed that during JVM shutdown process all the registered Shutdown hook complete their execution.
5) If the VM crashes due to an error in native code then no guarantee can be made about whether or not the hooks will be run.
Now lets see one complete example which will demonstrate the use of shutdown hook.
Example
The below example code provides two classes
1)  ShutdownHookDemo
and
2) A subclass of Thread named ShutdownHook.
After instantiation of the public class ShutdownHookDemo , its begin method is called. The begin method creates a shutdown hook and registers it with the current runtime.
ShutdownHook shutdownHook = new ShutdownHook();
Runtime.getRuntime().addShutdownHook(shutdownHook);
When the user press any key, the program exits. But still the the virtual machine will run the shutdown hook and print the message “Im Shutting down” 

lets a create class which actually does the job to be done while VM is shutting down
Output
Im inside start
Im Shutting down
When finalizers will run, before, during, or after shutdown hooks?
Finalization-on-exit processing is done after all shutdown hooks have finished. Otherwise a hook may fail if some live objects are finalized prematurely.

For more information please go through this link



Monday, May 28, 2012

Resource Injection Using Spring

Many times we would come across reading a file into application. File can be located anywhere in the system or network.
To handle such file accessing tasks, Spring provides an interface called as “Resource” contained in the package org.springframework.core.io. To stream in the file, this interface has a method called as getInputStream(). we can get input stream from FileSystemResource, URLResource and ClassPathResource.


Spring’s resource loader provides a very generic getResource() method to get the resources like (text file, media file, image file…) from file system , classpath or URL. You can get the getResource() method from the application context.

Without this getResource() method, you will need to deal with different resources with different solution, like File object for file system resource, URL object for URL resource. Spring really did a good job with this super generic getResource() method, it really save our time to deal with resources.

Here’s an example to show how to use getResource() to load a text file from


1) The following code will read a file named sample.txt located in the src folder in the current working directory using class FileSystemResource.

2) For the files which you usually access using the url protocol like http://, ftp://, file:// etc, we have UrlResource. The following code will read a file named sample.txt present in C drive and that can be accessed from your browser using file:// protocol.


3) For the resources that are present on your classpath, you can use ClassPathResource. The following code will read in a file named sample.txt present in the classpath.


Injecting Resources
  Resource Injection(Static resources): Here we inject resources like the usual Spring Injection. This way is used for loading static resources i.e. when we know the resource which is required beforehand.

 Resource Loader(Dynamic Resources): Here we use Resource Loader interface to help us a resource we require. This way is used for loadind dynamic resources i.e which will be loaded based on some business logic .


Resource Injection: for static resources


In the above class, we have created a property of type Resource. And in the below context xml file we have injected this property with the path of the file we want spring to provide us with.

resourceContext.xml

SpringResourceTest.java


In the above test class, we get this bean in the usual way and when you get the textFile property from this bean, you can successfully read the information from this resource object. Now let us see the second way i.e how to access dynamic resources.


resourceContext.xml resource path has no prefix, so because the application context itself is going to be used as the ResourceLoader, the resource itself will be loaded via a ClassPathResource, FileSystemResource, or ServletContextResource (as appropriate) depending on the exact type of the context.
If there is a need to force a specific Resource type to be used, then a prefix may be used. The following two examples show how to force a ClassPathResource and a UrlResource (the latter being used to access a filesystem file).

<property name="template" value="classpath:some/resource/path/myTemplate.txt">

<property name="template" value="file:/some/resource/path/myTemplate.txt"/>


Resource Loader Injection: for dynamic resources



The above class has a property of type ResourceLoader. This ResourceLoader will be used to dynamically load a resource.To tell the spring about injecting value into this, we have used the @Autowired annotation. With annotations, we need not create setter methods for our properties. Only thing we have to do is to tell Spring framework that we are using the annotation, so in addition to the injecting values based on the property tags from the xml, it has to read class level annotations also. We do this by adding in the content xml file as seen below.

resourceContext.xml


SpringResourceTest.java
In our test class, we get this bean in the usual way and call its loadDynamicResource. This method internally uses the ResourceLoader to return a Resource dynamically.