Tuesday 31 May 2016

How to convert Java Object to JSON string


import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;


ObjectMapper mapper  = new ObjectMapper();
TravelVo travelVo = new TravelVo();
                         travelVo.setDestination("Kashmir");
String jsonString = mapper.writeValueAsString(travelVo);

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.5</version>
</dependency>

How to Convert JSON value to Java Object




import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

try {
ObjectMapper mapper  = new ObjectMapper();
TravelVo travelVo = mapper.readValue(jsonValue, TravelVo.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Add the below dependency in pom
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.5</version>
</dependency>

How to call Spring MVC controller by making form submit through JQuery


In  JS file  the following entry will be present  where in the radio button value is obtained and set  them as parameter value

$("button#checkdetail").click(function(e) {
var selectedVal=$("input[name='detaildata']:checked").val();
$("#detail-form").attr("action", "/<application-name>/show-detail/{"+ selectedVal+"}");
        $( "#search-form").submit();
});

In Spring Controller , the request mapping will have the path variable to obtain the data as follows

@RequestMapping(value = "/show-detail/{selectedVal}", method = RequestMethod.POST)
public String showDetailPage(@PathVariable String selectedVal,
Model m, HttpServletRequest request) {
return "detail-page";
}

In Html Page
<form id="detail-form" name="detail-form">
           <input type='radio' id='detaildata'  name='detaildata' value='ByCar'/>
          <input type='radio' id='detaildata'  name='detaildata' value='ByVan'/>
                  <button type="submit"  id="checkdetail"  name="checkdetail" >Submit</button>
       </form>

Thursday 26 May 2016

How to install Meteor on Windows 10

Download the Meteor from the below link "Download the Meteor installer for Windows."

https://github.com/meteor/windows-preview

After the file named "InstallMeteor.exe" is downloaded  , double click on it.  Choose signup and provide details or skip step.Now the meteor is installed on your machine

Restart the machine.After the restart right click on the windows icon and click command prompt(Admin)

Then go to the desired folder where you would like to  create a website related files
 run the command meteor create mywebblog
say c:\installable\meteor>meteor create mywebblog

Go to the folder mywebblog say
c:\installable\meteor>cd mywebblog

Run the command meteor from the command prompt , windows will ask to allow access as firewall may block , please choose allow access
c:\installable\meteor\mywebblog>meteor

The below lines will be displayed

=> Started proxy.
=> Started MongoDB.
=> Started your app.

=> App running at: http://localhost:3000/
   Type Control-C twice to stop.


Then open browser and provide http://localhost:3000/ , page will appear with content as

Welcome to Meteor!






Wednesday 25 May 2016

How to process two un-related tables using JPA EntityManager

Please use the below lines of code to join un-related tables and populate data into appropriate entity objects here travelDetailEntity & travelEntity are said to be JPA Entities

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@PersistenceContext
private EntityManager em;

String query =
    "select travelDetail, travel from  travelDetailEntity as travelDetail, travelEntity as travel "+
    "where  travelDetail.location = 'location' and travelDetail.id = travel.id";
List<Object[]> results = em.createQuery(query).getResultList();

for (Object[] travelDetailAndtravel: results) {
    travelDetailEntity travelDetail = (travelDetailEntity) travelDetailAndtravel[0];
    travelEntity travel = (travelEntity) travelDetailAndtravel[1];  
}

How to load or include a html file in JQuery

Use the below lines of code in js file to load the html page into the div

$(document).ready(function() {
    $('#loadSearchPage').load('html/search.html');
});

use the below code in search.html,

<div id="loadSearchPage"></div>

Monday 23 May 2016

How to write simple Angular JS script through angular factory- Generating Random Number


Create a javascript or js file  and name it testangular.js as like below, please take care in naming the module name in say  angular.module , ang.factory  and while calling the function with appropriate name

var ang= angular.module('appFactory', []);
ang.factory('angularFactory', function() {
 return {
   generateRandomNumber: function() {
    var randomNumber=Math.random();
    return randomNumber;
   },
   title:"Testing Factory Pattern in AngularJS"
  }
});


ang.controller('controllerFactory', ['$scope','angularFactory', function($scope,angularFactory){  
 $scope.randomNumber =0;
 $scope.title ='';
 $scope.getRandomNumber=function(){
  $scope.randomNumber =angularFactory.generateRandomNumber();
  $scope.title =angularFactory.title;
    }
 
 }]);

Create a html file as like below

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
  <script src="../js/angular.js"></script>
  <script src="testangular.js"></script>

</head>
<body ng-app="appFactory">
  <div ng-controller="controllerFactory" >
   <h1 ng-show="title">{{title}}</h1>  
   <button ng-click="getRandomNumber()" >Get Random Number</button>
   Random Number :   <input type='text' ng-model="randomNumber" size="10"/>
 </div>
</body>
</html>

Sunday 22 May 2016

How to send JSON object as Response in Spring MVC

Add the below dependency in maven pom.xml

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>

ObjectMapper  class helps to convert the object to json.

import org.codehaus.jackson.map.ObjectMapper;

@RequestMapping(value = "/<request_mapping_name>", method = RequestMethod.POST )
       public @ResponseBody String getMessage()  {
               List<String> errorList = new ArrayList();
               errorList.add("validation fails");

              ObjectMapper mapper  = new ObjectMapper();
               String json = null;
                            json =  mapper.writeValueAsString(errorList);
return json;
}
 

Tuesday 17 May 2016

How to check the constraints in Oracle

Use the below query to check all the constraints in Oracle.

select * from all_cons_columns;

select * from all_constraints where constraint_name='<constraint_name>'

Thursday 12 May 2016

Tuesday 3 May 2016

How to use MVEL expression language

Add the below dependency in pom.xml

   <properties>
       <mvel.version>2.2.0.Final</mvel.version>
</properties>

<dependencies>
<dependency>
<groupId>org.mvel</groupId>
         <artifactId>mvel2</artifactId>
<version>${mvel.version}</version>
</dependency>
</dependencies>

Below code helps to evaluate an expression through MVEL

A & B are said to be the fields that are part of the expression and these are substituted with values from the Mapfor evaluation.

   String prefValue = "(A <= B)";
Serializable expression = MVEL.compileExpression(prefValue);

Map<String, BigDecimal> expressionVariables = new HashMap<String, BigDecimal>(2);
expressionVariables.put("A", new BigDecimal(10));
expressionVariables.put("B", new BigDecimal(20));

System.out.println( (Boolean)MVEL.executeExpression(expression, expressionVariables));

Sunday 1 May 2016

How to use Specification in Spring JPA


Create specification like below

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;

public class TravelDetailSpecification {

public static Specification<TravelDetail> applyTravelDetailQuery() {
return new Specification<TravelDetail>() {
@Override
public Predicate toPredicate(Root<TravelDetail> root,
CriteriaQuery<?> query, CriteriaBuilder builder) {
Predicate predicate = builder.conjunction();
final Join<TravelDetail, TravelDetailCode> travelDetailCode = root
.join(TravelDetail_.id, JoinType.LEFT);

predicate = builder.and(predicate, builder
.isNotNull(travelDetailCode
.<String> get(TravelDetailCode_.price)));

predicate = builder.and(predicate, builder.equal(root.get(TravelDetail.id), id));

query.orderBy(builder.asc(root.get(TravelDetail_.place)));

return predicate;
}
};
}

}

Create entity like below
@Entity
@Table(name="TRAVEL_DETAIL", schema="TRAVEL")
@NamedQuery(name="TravelDetail.findAll", query="SELECT f FROM TravelDetail f")
public class TravelDetail implements Serializable {
private static final long serialVersionUID = 1L;

@Id
private long id;

private string package;

private BigDecimal price;

//get set methods
}

How to convert entity into value object or bean using Model Mapper

Converting the mapper is as like below

TravelDetail travelDetail = new TravelDetail();
travelDetail.setId(123);
travelDetail.setPackage(4000);

ModelMapper mapperFromDto = new ModelMapper();
TravelDetailVO travelDetailVO = mapperFromDto.map(travelDetail, TravelDetailVO.class);

Entity is crated as like below

@Entity
@Table(name="TRAVEL_DETAIL", schema="TRAVEL")
@NamedQuery(name="TravelDetail.findAll", query="SELECT f FROM TravelDetail f")
public class TravelDetail implements Serializable {
private static final long serialVersionUID = 1L;

@Id
private long id;

private string package;

private BigDecimal price;

//get set methods
}


The bean or value object is created , the variables and its datatype should match with the variables and the datatype of entity

public class TravelDetailVO implements Serializable {
private static final long serialVersionUID = 1L;

private long id;

private string package;

private BigDecimal price;

//get set methods
}

Add the dependency given below in pom.xml

                 <!-- Model Mapper -->
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>0.7.4</version>
</dependency>

How to delete entity in Spring+Hibernate+JPA


Create the interface for the particular entity as like below

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface TravelDetailRepository extends
JpaRepository<TravelDetail, Long> , JpaSpecificationExecutor<TravelDetail>{
}

Entity is created below , use the JPA tools by right clicking on the project in Eclipse providing the datasource from where the entity has to be created

@Entity
@Table(name="TRAVEL_DETAIL", schema="TRAVEL")
@NamedQuery(name="TravelDetail.findAll", query="SELECT f FROM TravelDetail f")
public class TravelDetail implements Serializable {
private static final long serialVersionUID = 1L;

@Id
private long id;

//get set methods
}

Implementing the DAO as like below

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Repository
public class TravelDetailDaoImpl {
@Autowired
private TravelDetailRepository travelDetailRepository;
public void delete(TravelDetail travelDetail) {
travelDetailRepository.delete(travelDetail);
}
}

How to make Ajax request from Anchor tag to a Spring MVC controller through JQuery

Add the below dependency in pom.xml

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>

Add the below anchor link in the html or jsp page

 <a  name="check" id="check">Check Status</a>

Add the below script in .js file, be careful while providing the request attributes with double quotes

$("a#check").click(function(e) {
var requestdata={"TravelCode":"C001","TravelPackageNo": 100};
$.ajax({
"url": "check-status",
"type": "POST",
"contentType": "application/json",
"data": requestdata,
"global": true,
"complete": function(jqXHR, textStatus) {
},
"error": function(jqXHR, textStatus, errorThrown) {
$().endLoading();
}
});
});

Use the below code in the spring controller, the value provided should the same as given in the url attribute of the ajax request

@RequestMapping(value = "/check-status", method = RequestMethod.POST)
public @ResponseBody String checkStatus(@RequestBody TravelViewVo travelViewVo,
Model m, HttpServletRequest request) {

}

Class TravelViewVo {
 private String TravelCode;
private int  TravelPackageNo;

// set & get methods
}