Friday 23 October 2015

How to create a simple maven Restful webservice project using Spring MVC

Here we are going to create a simple restful web service in spring  that returns a model object in JSON format.
 Pre-requisites:-Apache Maven 3.1.1 installed.
                          Eclipse, with jdk7
                          Apache Tomcat 7(To run your service)
                          Postman client for chrome(To test the service)
                          m2e plugin for eclipse
Step 1: Go to your project folder in command prompt and create a maven web project skeleton by using below command

mvn archetype:generate -DgroupId=com.rest.example -DartifactId=RestApp -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
RestApp project will be created in your project folder. Check the folders.

Step 2: To convert the maven project to eclipse project, please run below command from RestApp folder.This will add eclipse compatibility to your project.

mvn eclipse:eclipse -Dwtpversion=2.0

Step 3: Import the project in eclipse
Open the newly created RestApp project in eclipse by importing the existing project.Inside src/main folder create a java folder along with webapp and resources folders.
Add the java folder also to source in Java build path.
Step 4: Define your rest servlet in web.xml as follows

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>restServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/rest-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>restServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
Step 5:Create your rest-servlet.xml file in WEB-INF folder as follows:


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans    
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">   
       
              <mvc:annotation-driven/>
                     <bean id="resource" class="com.rest.example.RestControllerExample"></bean>
       
</beans>
Step 6: Create your controller class and model class.
Here we are going to add request mapping to both our controller class and handler method.@RestController is a convenience annotation that does nothing more than adding the @Controller and @ResponseBody annotations.

package com.rest.example;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/rest/data/")
public class RestControllerExample {

@RequestMapping(value="get/msg", method = RequestMethod.GET,headers="Accept=application/json")
public  Message getRestMessage(){
                Message msg=new Message();
                msg.setMsgHeader("Rest Test");
                msg.setContent("Successfully retrived your msg in json format");
                return msg;                
}
}
Model object:-

package com.rest.example;

import java.io.Serializable;

public class Message implements Serializable {
private static final long serialVersionUID = -5319000110698008607L;
private String msgHeader;
private String content;
public String getMsgHeader() {
       return msgHeader;
}
public void setMsgHeader(String msgHeader) {
       this.msgHeader = msgHeader;
}
public String getContent() {
       return content;
}
public void setContent(String content) {
       this.content = content;
}
}
Step 7: Update the pom.xml file with required dependencies.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.rest.example</groupId>
  <artifactId>RestApp</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>RestApp Maven Webapp</name>
  <url>http://maven.apache.org</url>
    <properties>
        <springframework.version>4.0.6.RELEASE</springframework.version>
    </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>    
              <dependency>
                     <groupId>com.fasterxml.jackson.core</groupId>
                     <artifactId>jackson-databind</artifactId>
                     <version>2.2.3</version>
              </dependency>  
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>
    
    
  </dependencies>
       <build>
              <finalName>RestApp</finalName>
              <plugins>
                     <plugin>
                           <groupId>org.apache.maven.plugins</groupId>
                           <artifactId>maven-compiler-plugin</artifactId>
                           <version>2.1</version>
                           <configuration>
                                  <source>1.7</source>
                                  <target>1.7</target>
                           </configuration>
                     </plugin>
                       <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
                </configuration>
            </plugin>
              </plugins>
       </build>
</project>

After converting your project to maven project using a m2e plugin, your project structure will be as shown below. Please change the JDK version in project facet to 1.7 if you are facing any compilation errors.

You have probably noticed that we have added jackson2 converter also in pom.xml file.This is for JSON conversion of the object returned from the handler method.Once the response object is returned by the handler method, MappingJackson2HttpMessageConverter kicks in and convert it to JSON response.
That  is why Included below depedncy in pom.xml.
      
 <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.2.3</version>
 </dependency>
This will convert returning objects to json format by default


Step 8: Build and run your restful service
Run mvn install from the command prompt to build the war file. Deploy the war file to tomcat webapp folder. That's it. Start the server and hit the service in postman. You will get the message as shown below.

{
    "msgHeader": "Rest Test",
    "content": "Successfully retrived your msg in json format"


}



Tips:--
Convert  to maven project in eclipse using m2e plugin if required
To fix compiler version change on maven update using m2e plugin, add below in pom.xml

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>2.1</version>
  <configuration>
    <source>1.6</source>
    <target>1.6</target>
  </configuration>
</plugin>


Saturday 19 September 2015

How to use parse db from your node application


Here I am going through the simple steps to demonstrate how to access parse DB from
your node application.

To know more about parse db please visit www.parse.com

If you have your node based web app ready, you can include parse db in your app in two ways

1. Java Script.

Step 1: Include parse script as a bower_component. Use below command for this.
        bower install parse
Step 2: Create a test class in parse db.
        Register in parse.com and create a sample test app db with some columns.
       After creation of your tables, get the keys for external use from settings page.
Step 3: Initialize parse.
                      Parse.initialize('application id','Java script key');
Step 4: Querying the parse db from script

        Here I am going to query the data from Test class in below function
$scope.getLocation = function(val) {
    var locations=[];
    var Etest = Parse.Object.extend("Your class name from parse DB");
    var query = new Parse.Query(Etest); 
//add filters in your query
    query.startsWith("name", val.toLowerCase());
//querying
   return query.find({
        success: function(results) {
     
        },
         error: function(error) {
       alert("Error: " + error.code + " " + error.message);
      }
     }).then(function(results){
   
//returning the results to front end
      for (var i = 0; i < results.length; i++) {
           var object = results[i];
           locations.push(object.get('name')
          }
      return locations;
     });


2. As an $http Rest request.

  For accessing the parse db as a rest api request , we don't need to use parse script.
Step 1:We need to add below information to request header.
$http.defaults.headers.common['X-Parse-Application-Id']
    ='Application Id';
    $http.defaults.headers.common['X-Parse-REST-API-Key']
    ='Rest Api Key';

Step 2: Accessing from your java script function.
We need to pass $htttp to your controller script
$scope.data = {};
$http.get('https://api.parse.com/1/classes/etest')
    .success(function (data){       
     
    $scope.data.test =data.results;
    console.log('data'+$scope.data.test);
    })
    .error(function (response){
        $scope.data.error = response.error || response;
    });

 
 




Wednesday 26 August 2015

How to create a simple web app using bootstrap and angular features

Before starting , we need to install below tools.
We have already seen installation of node js  from
http://simpleapphub.blogspot.in/2015/08/simple-web-app-in-node-js.html
Now let us go through below steps:-

Step 1: Install node if not done already

Step 2: Install git from http://git-scm.com/
Git is a free distributed version control system designed to handle everything from small to very large project. Use below option while installing. Use default choice for all other options.


After the successful installation of git , you can verify it by using below command.


Step 3:Installation of bower.

Bower is a packaging manager for browser components. If we have already installed node & git , we can install bower using below command.
npm install -g bower

On running below command , you can verify the globally installed components using npm.
npm list -g --depth=0
Step 4: Installation of grunt tool.

 npm install -g grunt

In order to get started, you'll want to install Grunt's command line interface (CLI) globally.
This will put the grunt command in your system path, allowing it to be run from any directory.

Step 5: Installation of yo.
Yo provides certain generators that you can use to create your web app template. 
 npm install -g yo
Above command will install yo package. We can use the different template generators provided by yo. Here we are going to use angular generator with necessary bower components. 
 First we need to install angular-generator using below command.
npm install -g generator-angular
Step 6: Everything is set-up now. You can verify this as shown below.

Now we can go to our project directory  and start creating our web app using generator.
command: yo angular
You can include bootstrap also while installing. Please follow the instructions as shown below.
 


All the bower modules installed is present in bower.json  generated.

Step 6: If everything installed perfectly, we an start running our web app by using below command.
grunt serve
 We can see that index.html is loaded with a default bootstrap provided from yo tool. You can use sublime editor for further editing your web app as you like

 
Possible errors:-
If you encounter below error on running yo angular

module.js:338
    throw err;
    ^
Error: Cannot find module 'figures'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (C:\Users\Administrator\AppData\Roaming\npm\node_modul
es\generator-karma\node_modules\yeoman-generator\node_modules\inquirer\lib\objec
ts\separator.js:7:15)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
 Solution: Try uninstalling generator-angular. After that re-install it again.
npm uninstall -g generator-angular

If the problem persists after the re-installation , try below steps:-
install rimraf module  to delete node-modules. please run below commands to install & delete node_modules using rimraf
            npm install -g rimraf
            rimraf node_modules
            npm clean cache