Tuesday, 7 June 2016

Spring MVC + AngularJS Integration

This tutorial illustrates how to use or integrate the Spring MVC and AngularJS together.AngularJS is popular JS framework for building the single page web applications. Also most of the mobile applications and rich user interfaces are using the AngularJS framework. Here we will show how to use this framework in the view layer and access the Spring MVC controller to display the data. AngularJS framework is created and maintained by Google.
If you have any queries, please write it in the comments section or post it in our facebook page.
In this Spring MVC and AngularJS example, data returned from server is in the type of JSON, that will be assigned to the AngularJS object and will display to the user. Lets look at the example.
also read:

1. Spring MVC Controller

SpringContentController.java
package javabeat.net.spring.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
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.ResponseStatus;

@Controller
public class SpringContentController {
 @Autowired UserDetails userDetails;
 @RequestMapping(value="/springcontent",
   method=RequestMethod.GET,produces={"application/xml", "application/json"})
    @ResponseStatus(HttpStatus.OK)
 public @ResponseBody
 UserDetails getUser() {
  UserDetails userDetails = new UserDetails();
  userDetails.setUserName("Praveen");
  userDetails.setEmailId("praveen@gmail.com");
  return userDetails;
 }
}

2. Java Bean

UserDetails.java
package javabeat.net.spring.controller;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class UserDetails {
 private String userName;
 private String emailId;

 @XmlAttribute
 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 @XmlAttribute
 public String getEmailId() {
  return emailId;
 }

 public void setEmailId(String emailId) {
  this.emailId = emailId;
 }
}

3. Spring Configurations

spring-dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:context="http://www.springframework.org/schema/context"
 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-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 <context:component-scan base-package="javabeat.net.spring.controller" />
 <bean id="userDetails" class="javabeat.net.spring.controller.UserDetails"/>
 <mvc:annotation-driven content-negotiation-manager="contentManager"/>
 <bean id="contentManager"
                class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
                <property name="favorPathExtension" value="true"/>
                <property name="ignoreAcceptHeader" value="true" />
                <property name="defaultContentType" value="text/html" />
                <property name="useJaf" value="false"/>
                <property name="mediaTypes">
                 <map>
                     <entry key="html" value="text/html" />
                     <entry key="json" value="application/json" />
                     <entry key="xml" value="application/xml" />
                 </map>
                </property>
        </bean>
 <bean id="jspViewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
 </bean>
</beans>

4. AngularJS View

This is very simple use of the AngularJS framework. The function “Hello” can be added to the JS controler which is best practice. However, for the simplicity we have used inside the JSP page.
angular.jsp
<!doctype html>
<html ng-app>
 <head>
  <title>Spring MVC + AngularJS Demo</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
     <script>
     function Hello($scope, $http) {
         $http.get('http://localhost:8080/SpringExamples/springcontent.json').
             success(function(data) {
                 $scope.user = data;
             });
     }
     </script>
 </head>
 <body>
  <div ng-controller="Hello">
   <h2>Spring MVC + AngularJS Demo</h2>
   <p>EMail Id : {{user.emailId}}</p>
   <p>User Name : {{user.userName}}</p>
  </div>
 </body>
</html>

5. Spring MVC + AngularJS Example

If you run the above example code, you would get the below screen.
Spring MVC and AngularJS Integration Example

Spring Data JPA Tutorial using Spring Boot

This tutorial guides you through on building simple REST APIs using Spring Data JPA and Spring Boot. At the end of this tutorial, you would be able to write the applications with Spring Data JPA using Spring Boot. 
In our earlier tutorials we have covered about Spring Data JPA and JPA frameworks. But, this tutorial uses Spring Boot for building and running the application. Also I have written core concepts of Spring Data Common project in this tutorial.

Table of Contents

Here is the list of sections covered in this tutorial.
  1. What is Spring Data?
  2. Spring Boot and Spring Data JPA
  3. Spring Data Repositories
    1. CrudRepository
    2. Repository
    3. PagingAndSortingRepository
  4. JpaRepository vs CrudRepository
  5. Query Methods
  6. Domain Class
  7. REST API
  8. Service Layer
  9. Spring Boot Application
  10. Download Source Code
  11. Conclusion

What is Spring Data?

Spring Data is a high level project developed by Spring community aimed at simplifying the data access operations for the applications. There are several sub-projects maintained for the individual stores to have its own implementation of repositories.
If you are using Spring Data in your project, you are not going to write most of the low level data access operations like writing SQL query, DAO classes,  etc. Spring Data will generate everything dynamically at run-time by creating the proxy instances of your abstract repositories and perform the required operations. What you write is the abstract interfaces that define the required operations.
In this tutorials we will be using one of the sub project Spring Data JPA. Other than that Spring Data has the following sub-projects:
  • Spring Data Commons
  • Spring Data MongoDB
  • Spring Data Redis
  • Spring Data Solr
  • Spring Data Gemfire
  • Spring Data REST
  • Spring Data Neo4j

Release Train

Spring Data project has several store specific projects as mentioned above. Needless to say, each of the above module has its own release cycle and team working on for the improvements. When you are downloading the dependencies for your application, each module mentioned above should have the compatibility with each other.
To resolve the compatibility issue, a BOM (Bill of Materials) is published with a curated set of dependencies on the individual project. The release trains have names, not versions, to avoid confusion with the sub-projects.
The latest release named as Gosling-RELEASE and you have to add the following entries in yourpom.xml file.
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-releasetrain</artifactId>
            <version>Gosling-RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Spring Data JPA

Spring Data JPA, it is part of the Spring Data family, aims to provide the JPA based repositories that aims to simplify the implementation of data access layer using JPA.
spring data jpa

Spring Boot and Spring Data JPA

I am going to write a simple REST APIs for managing a book store application and store the details in H2 database, an in-memory database most commonly used for the development purposes. My final pom.xml file would look like this:
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.2.5.RELEASE</version>
 </parent>
 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
  </dependency>
 </dependencies>
If you look at the above configurations,
  • spring-boot-starter-parent loads all the default configurations required for the basic spring boot applications.
  • spring-boot-starter-data-jpa dependency will download the files required for spring data jpa.
  • spring-boot-starter-webis required because it is web based application to expose the REST endpoints.
The above configurations sufficient to get started developing our simple REST APIs application using Spring Data JPA.
In the coming sections I will explain some of the interfaces in spring data and the purpose of them.

Spring Data Repositories

When you are working with spring data technologies, it is important to understand the repositories concept. Spring data provides the abstract repositories, that are implemented at run-time by the spring container and perform the CRUD operations. As a developer we have to just provide the abstract methods in the interface. This reduces the amount of boilerplate code required to write data access layers.
The following are the three base interfaces defined in the spring data commons project.

Repository

It is the central interface in the spring data repository abstraction. This is a marker interface. If you are extending this interface, you have to declare your own methods and the implementations will be provided by the spring run-time. For this interface also we have to pass two parameters:type of the entity and type of the entity’s id field. This is the super interface for CrudRepository.

CrudRepository

CrudRepository provides methods for the CRUD operations. This interface extends the Repository interface. When you define CrudRepository, you have to pass the two parameters:type of the entity and type of the entity’s id field. This interface has the following methods:
  • S save(S entity)
  • T findOne(ID primaryKey)
  • Iterable findAll()
  • Long count()
  • void delete(T entity)
  • boolean exists(ID primaryKey)
If you are extending the CrudRepository, there is no need for implementing your own methods. Just extend this interface and leave it as blank. Required implementations are provide at run time.
Look at our example:
public interface BookRepository extends JpaRepository<Book,Long> {
}
We have used JpaRepository, which is the special version specific to the JPA technology. Unless until you are using any of the JPA specific things in your applications, it is highly recommended to use the CrudRepository, because it will not tie your application with any specific store implementations.
The above code is sufficient to perform the basic operations like find, save, delete.

PagingAndSortingRepository

This is extension of CrudRepository. It is specialized version for the paging operations. The implementation of this class look like this:
public interface PagingAndSortingRepository<T, ID extends Serializable>
  extends CrudRepository<T, ID> {
  Iterable<T> findAll(Sort sort);
  Page<T> findAll(Pageable pageable);
}

JpaRepository vs CrudRepository

Both, JpaRepository and CrudRepository are base interfaces in Spring Data. Application developer has to choose any of the base interfaces for your own repository. It has two purposes,
  • One is to allow spring data to create proxy instance for your repository interface.
  • Second one is to inherit the maximum default functionality from the base interfaces without declaring your own methods.
When we look at both of the interfaces, the clear differences are:
  • CrudRepository is part of Spring Data Commons project and declared under the packageorg.springframework.data.repository. Where as JpaRepository is part of store specific implementation and declared under the packageorg.springframework.data.jpa.repository.
  • CrudeRepository extnds from Repository interface. Where as JpaRepository extends from PagingAndSortingRepository which inturen extends from the CrudeRepository.
  • JpaRepository returns List type of entities and CrudRepository returns Iterable type of entities.
  • It is general recommendation that not to use the store specific base interfaces as they expose the underlying persistence technology and tighten the coupling between them and the repository. It is always good idea to choose any of the generic base interfaces like CrudRepository or PagingAndSortungRepository.
The below diagram shows the repository module structure.
Drawing1

Query Methods

  • Query methods are used for finding the information from database and that are declared in the repository interface.
  • Query methods can return one result or more than one result.
  • This also supports passing parameter to database queries by sending through parameter binding or named parameters.
  • If you want to implement query methods, implement Repository interface and write your own methods.
Here is a simple example of how to write query methods:
public interface BookOwnRepository extends Repository<Book,Long>{
 List<Book> findByName(String name);
 List<Book> findByPrice(long price);
 List<Book> findByNameAndAuthor(String name, String author);
}
  • Using query methods are most convenient way to write our own queries to fetch data from the database. Spring data jpa allows more powerful query formation using the methods names and parameter.
  • In the above example class, we have used only a few naming conventions are forming the query.
    • findBy… – this is the prefix, anything follows this prefix will be used for framing the query
    • findByName – In this method, only the matching names are returned. Here we are pasing only one parameter name.
    • findByNameAndAuthor – In this method, we are using the “And” to add more information to the query by search either using name or author. In the similar way, you can use the “Or” delimiter.

Domain Class

Here is the simple domain class Book used for this tutorial.
Book.java
@Entity
public class Book implements Serializable{
 private static final long serialVersionUID = 1L;
 @Id
 long id;
 @Column(name="name")
 String name;
 @Column(name="author")
 String author;
 @Column(name="price")
 long price;
        //Getters and Setters Here
}
  • @Entity used for marking that this POJO is used as entity in the database.

REST API

I have written a simple REST API by annotating @RestController  (this annotation introduced from Spring 4.0). This class will be interface between client application and the database layer. It exposes the API for add, find, list and delete books to the database.
Look at the example code:
@RestController
@RequestMapping(value = "/books")
public class BooksController {
 @Autowired
 private BookService bookService;
 @RequestMapping(value = "/add/{id}/{name}/{author}/{price}")
 public Book addBook(@PathVariable int id, @PathVariable String name, @PathVariable String author,
   @PathVariable long price) {
  Book book = new Book();
  book.setId(id);
  book.setName(name);
  book.setAuthor(author);
  book.setPrice(price);
  bookService.saveBook(book);
  return book;
 }
 @RequestMapping(value = "/delete/{id}")
 public void deleteBook(@PathVariable int id) {
  Book book = new Book();
  book.setId(id);
  bookService.delete(id);
 }
 @RequestMapping(value = "/")
 public List<Book> getBooks() {
  return bookService.findAll();
 }

 @RequestMapping(value = "/{id}")
 public Book getBook(@PathVariable int id) {
  Book book = bookService.findOne(id);
  return book;
 }
 @RequestMapping(value = "/search/name/{name}")
 public List<Book> getBookByName(@PathVariable String name) {
  List<Book> books = bookService.findByName(name);
  return books;
 }
 @RequestMapping(value = "/search/price/{price}")
 public List<Book> getBookByPrice(@PathVariable int price) {
  List<Book> books = bookService.findByPrice(price);
  return books;
 }
 @RequestMapping(value = "/search/{name}/{author}")
 public List<Book> getBookByNameAndAuthor(@PathVariable String name, @PathVariable String author) {
  List<Book> books = bookService.findByNameAndAuthor(name, author);
  return books;
 }
}
There is no explanation required for this class, as we have already covered in detail about theRestControllers and Spring Rest Services.

Service Layer

I have written a service layer that will be in between REST API and Spring Data repositories. This is not a good practice to directly invoke the data access APIs from our REST, so I have written service layer for that purpose.
BookService.java
public interface BookService {
 public List<Book> findAll();
 public void saveBook(Book book);
 public Book findOne(long id);
 public void delete(long id);
 public List<Book> findByName(String name);
 public List<Book> findByNameAndAuthor(String name, String author);
 public List<Book> findByPrice(long price);
}
BookServiceImpl.java
@Service
@Transactional
public class BookServiceImpl implements BookService{
 @Autowired
 private BookRepository bookRepository;
 @Autowired
 private BookOwnRepository bookOwnRepository;

 public List<Book> findAll(){
  return bookRepository.findAll();
 }
 public List<Book> findByName(String name){
  return bookOwnRepository.findByName(name);
 }
 public List<Book> findByPrice(long price){
  return bookOwnRepository.findByPrice(price);
 }
 public List<Book> findByNameAndAuthor(String name, String author){
  return bookOwnRepository.findByNameAndAuthor(name,author);
 }
 public void saveBook(Book book){
  bookRepository.save(book);
 }
 public Book findOne(long id){
  return bookRepository.findOne(id);
 }
 public void delete(long id){
  bookRepository.delete(id);
 }
}
  • We would require @Transaction annotation to perform the database transactions.
  • @Service annotation to indicate that it is service class
  • @Autowired is used for injecting the repository dependency to service layer.
  • One thing if you note, I have injected both the repositories in the service layer. I have used both of them only for the example purpose, in your application you better choose any one repository type and write everything on the single repository.
  • This service class is merely a delegation mode to invoke the repositories.

Spring Boot Application

Note : This example application for Spring Data JPA using Spring Boot is continuously improved and updated in the same location. So, there could be variation in this tutorial and what is actually you are seeing in the source code. But, everything works fine :).
Here is the final piece of code to bootstrap this application using spring boot. Ensure that this class is written in the same or above the level of package. When you run the spring boot application, it will consider the package where main class is located as the base package and start the @ComponentScan from that package.
Here is the package structure of the application:
spring data jpa project structure
@SpringBootApplication
public class Application {
 public static void main(String[] args) {
  SpringApplication.run(Application.class, args);
 }
}
  • You can run this application through command line using the command spring-boot:run
If you have any issues on running this application, please contact me.

Download the Source Code

Conclusion

In this tutorial I have explained how to write REST APIs using Spring Data JPA and Spring Bootframeworks. I hope this tutorial will be much useful and complete guide for learning Spring Data JPA. If you have any difficulty in understanding any of the concepts, please contact me through comments section. Enjoy working with spring data and power of simplicity.

Indian Gas BRIEF Introduction

BRIEF


Indane is today one of the largest packed-LPG brands in the world. Indian Oil pioneered the launch of LPG in India in the 1970s and transformed the lives of millions of people with the introduction of the clean, efficient and safe cooking fuel. LPG also led to a substantial improvement in the health of women in rural areas by replacing smoky and unhealthy chullahs with Indane. It is today a fuel synonymous with safety, reliability and convenience.
LPG is a blend of Butane and Propane readily liquefied under moderate pressure. LPG vapour is heavier than air; thus it normally settles down in low-lying places. Since LPG has only a faint scent, a mercaptan odorant is added to help in its detection. In the event of an LPG leak, the vapourisation of liquid cools the atmosphere and condenses the water vapour contained in it to form a whitish fog, which is easy to observe. LPG in fairly large concentrations displaces oxygen leading to a nauseous or suffocating feeling.
Suraksha LPG hose, flame retardant aprons and energy efficient Green Label stoves are recommended to enhance safety measures while using LPG as fuel.

2010

  • 5.8 million customers covering every corner of India
  • Every second LPG cooking gas connection in India is an Indane
  • The world’s highest LPG bottling plant – situated 3500 metres above sea level – is at Leh
  • Each day, the Indane distribution network delivers 1.20 million cylinders
  • Of the 57.41 million families served by 5500 Indane distributors, 27% are in semi-urban and rural markets
  • Indane sales network is backed by 45 Indane Area Offices

Indian Gas CUSTOMER CARE Numbers

CUSTOMER CARE



  • In order to have a more convenient, easy and effective way to enable the customer to air their complaints and follow up on such complaints, IOC has started the service of using unique toll free numbers for the complaint registration through call centers from 2nd October 2008. Across the country IOC has a unique number18002333555, easy for the customers to remember.
  • Through this single common number any customer can query or register complaints in the call centers being operated by all three oil companies.
  • The call centers are operated region wise to facilitate the customers to lodge complaints in local language. Customers are given a registration number and those wish to know about the status of the complaints can call up the call centers in the same toll free numbers.
  • The complaint lodging is in a manual mode for 8am to 8 pm and an IVRS mode during 8pm to 8 am.

Sunday, 5 June 2016

Binary Search Tree Traversal Implemented in Java

Most of the students fresh out of their engineering studies or those who are still studying will have the concept of Binary Search Trees fresh in their minds. But with most of the people who have been out of college for many years now will kind of be having a not so clear idea of Binary Search trees unless they have been using it or related concepts at their work. Also you can read the extensive concepts about this topic on any of the popular data structure book in the store.

In this tutorial I would show how to implement a Binary Search Tree (BST) in Java and also show the following operations:
  1. Inserting/Building a BST
  2. Finding maximum value node in BST
  3. Finding minimum value node in BST
  4. Inorder Traversal of BST
  5. Preorder Traversal of BST
  6. Postorder Traversal of BST

Java 8 Release and Features

Finally, Java 8 arrives on March 18, 2014. This release has been announced at EclipseCon 2014. It is the first major release in Java after two years of time. Java 8 comes with lot of new features which are new to the Java programming itself. From today you can download Java 8 and use it in your project. Some of the notable improvements and features in Java 8 are listed below. We have already covering many of the features here at Java 8 Tutorials.

Spring HTML ESCAPE and ESCAPE BODY Tags ( and )

Spring Tag Library

Spring MVC provides a JSP tag library (Spring Form) for making it easier to bind form elements to Model data. Spring Framework also provides you with some tags for evaluating errors, setting themes and outputting internationalized messages.