Monday 29 August 2016

How to split lines and append in div box using Jquery

Use the below code to have text shown in multiple lines inside the span

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#btnclick").click(function () {   
    var multiStr = ["Ist Line","IInd Line"];
    for (i=0;i<multiStr.length;i++){  
       var spancr='<p><span>'+multiStr[i]+'</span></p>';
       $("#divbox").append(spancr);
    }
    });
});
</script>
</head>
<body>

<div id="divbox">
 Div Box...
</div>
<button id="btnclick">Click me</button></body>
</html>

Sunday 17 July 2016

How to use change event in jquery datepicker


Below will help to call the change event related to datepicker and apply things whichever are necessary

jQuery(function($) {
$("#validtodatepicker").datepicker({}).on("change", function() {
      alert("changed value"+$("#validToDate").val());
  });

});

Wednesday 6 July 2016

How to create Enum String constants


Below is the enum declaration

public enum EnumConstant {

STRING_1("ONE"), STRING_2("TWO");
private final String stringValue;
private EnumConstant(final String s) {
stringValue = s;
}
public String toString() {
return stringValue;
}
}

Below  is the test class to know its functions

public class EnumStringTest {

public static void main(String... arg){
System.out.println("Enum value :"+EnumConstant.STRING_1);
System.out.println("Enum value :"+EnumConstant.STRING_1.toString());
System.out.println("Enum name : "+EnumConstant.STRING_1.name());
System.out.println("Position of Enum constant : "+EnumConstant.STRING_1.ordinal());
}
}

Result  :

Enum value :ONE
Enum value :ONE
Enum name : STRING_1
Position of Enum constant : 0

Other way to use is as follows

public enum EnumVariable {

STRING_1{
public String toString(){
return "ONE";
}
},
STRING_2{
public String toString(){
return "TWO";
}
}

}

Wednesday 8 June 2016

How to add missing src/test/java folder to the maven project in Eclipse

1) Create a folder test/java  under src folder
2) Right click on the project and choose Maven --> Update Project --> choose for Force update of Snapshot/Releases  and click ok.  Now  test folder should appear as src/test/java in Eclipse  project explorer

Tuesday 7 June 2016

How to configure dependencies for Spock+Groovy in maven project


Please use the below one in maven pom.xml

<!-- Groovy + Spock -->
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>${org.spockframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-spring</artifactId>
<version>${org.spockframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
   <groupId>org.codehaus.groovy</groupId>
   <artifactId>groovy-all</artifactId>
   <version>${org.codehaus.groovy.version}</version>
 </dependency>
<dependency> <!-- enables mocking of classes (in addition to interfaces) -->
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.1</version>
<scope>test</scope>
</dependency>
<dependency> <!-- enables mocking of classes without default constructor (together with CGLIB) -->
<groupId>org.objenesis</groupId>
<artifactId>objenesis</artifactId>
<version>2.1</version>
<scope>test</scope>
</dependency>

How to resolve error "Caused by: org.hibernate.MappingException: Unable to find column with logical name: "

If you come across an error as like below

Caused by: org.hibernate.MappingException: Unable to find column with logical name: DESTINATION_ID  in org.hibernate.mapping.Table
(TRAVEL_DETAIL) and its related supertables and secondary tables
at org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:582)
at org.hibernate.cfg.BinderHelper.createSyntheticPropertyReference(BinderHelper.java:25

Please  remove the referencedColumnName attribute  which is used in Travel class  because destination_id is the primary key field of TravelDetail , referencedColumnName = ""  is only necessary if it references a non-primary-key field.

@Entity
public class Travel{

@Column(name="DESTINATION_ID" , insertable=false, updatable=false)
private java.math.BigDecimal destinationId;

//bi-directional many-to-one association to TravelDetail
@ManyToOne
@JoinColumns({
@JoinColumn(name="DESTINATION_ID" , referencedColumnName = "DESTINATION_ID")
})
private TravelDetail travelDetail;

.
.
.

}

@Entity
Public class TravelDetail{
@Id
@Column(name="\"DESTINATION_ID\"")
private long destinationId;
.
.
.

}

How to create random uuid or sequence for id generator through java.util.UUID

Below is way to create random UUID ,  this uuid can be used in place of sequencer (oracle sequence creation which will be provided in hibernate/jpa entities)


import java.util.UUID;

UUID.randomUUID().toString()

How to create Sequence in Oracle


Please use the below query to create sequence in Oracle. Here
MAXVALUE  -  denotes the maximum value that can be accoomdated
CACHE  - number of the values that will be created whenever nextval call is done and then put in cache
START WITH   -  the value that will begin with
INCREMENT BY   -  the incremental value

CREATE SEQUENCE <schema_name>.<sequence_name>
  MINVALUE 1
  MAXVALUE 99999999999
  START WITH 1
  INCREMENT BY 1
  CACHE 20;

ex:
CREATE SEQUENCE  TR.TRAVEL_DETAIL_ID_SEQ
  MINVALUE 1
  MAXVALUE 999999999999999999999
  START WITH 1
  INCREMENT BY 1
  CACHE 20;

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
}

Monday 18 April 2016

How to handle Exception in Spring MVC application


Below is one way to handling errors in an spring  MVC  architecture

The class that is given provided below is an ExceptionHandler class which takes care of handing the errors that occurs in the controller and redirect to the error page

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class GlobalExceptionHandler {

private @Value("${debugmode.enabled}") Boolean isDebugModeEnabled;

@ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request, HttpSession session,  Exception e) throws Exception {
     
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) throw e;
     
        // Otherwise setup and send the user to a default error-view.
        ModelAndView mav = new ModelAndView();
        if(isDebugModeEnabled) {
        mav.addObject("exceptionMessage", e);
        } else {
        mav.addObject("exceptionMessage", null);
        }
        mav.addObject("url", req.getRequestURL());
        mav.setViewName("error");
        return mav;
    }

}

How to configure Ehcache at Entity level in Spring+Hibernate+JPA application

Add the below entries in ehcache.xml which is placed in resources folder incase of maven project and otherwise in the classpath



<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="false" monitoring="autodetect"
         dynamicConfig="true">
<defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="1200" timeToLiveSeconds="1200"     overflowToDisk="true" diskPersistent="false"
     diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/>
   
     <cache name="org.hibernate.cache.internal.StandardQueryCache"  maxElementsInMemory="10000"   eternal="false"   timeToIdleSeconds="3600"  timeToLiveSeconds="3600"/>
  <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"  maxElementsInMemory="10000"  eternal="true"/>  
     <cache name="com.traveldesk.TravelDetail"  eternal="true"  maxElementsInMemory="10000"/>  
</ehcache>


The annotation @cache  helps in making the entity as a cacheable one

@Entity
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
@Table(name="TRAVEL_DETAIL" , schema="travel")
@NamedQuery(name="TravelDetail.findAll", query="SELECT d FROM TravelDetail d")
public class TravelDetail implements Serializable { }


The properties that are to be provided in the persistence.xml are as follows


<property name="hibernate.cache.region_prefix" value=""/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider" />
            <property name="hibernate.cache.use_second_level_cache" value="true" />
            <property name="hibernate.cache.use_query_cache" value="true" />
            <property name="hibernate.generate_statistics" value="true" />
            <property name="hibernate.cache.use_structured_entries" value="true" />                
            <property name="net.sf.ehcache.configurationResourceName" value="META-INF/ehcache.xml" />
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory" />



How to configure SLF4j & Logback Logger in Spring+Hibernate applications

Add the below dependencies in the pom.xml

 <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${slf4j.version}</version>
      </dependency>

 <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>${logback.version}</version>
      </dependency>



if it is a maven project , place the below logback.xml in travel-desk\src\main\resources\. Place the **logback-appenders.xml and **logback-loggers.xml in path specified in {-Dapp.configs=c:\<path>}, try to add {-Dapp.configs=c:\<path>} in vm-arguments of  the application server that  you have configured in Eclipse IDE or whichever IDE you use.

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true" scanPeriod="60 seconds" scan="true">

<contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
<resetJUL>true</resetJUL>
</contextListener>

<!-- To enable JMX Management -->
<jmxConfigurator/>
<include file="${app.configs}/travelDesk/travelDesk-logback-appenders.xml"/>
<include file="${app.configs}/travelDesk/travelDesk-logback-loggers.xml"/>
</configuration>


 Try to add {-Dapp.logs=<path>}  in vm-arguments of  the application server that  you have configured in Eclipse IDE or whichever IDE you use. Below is an snippet from **appenders.xml

/travelDesk-logback-appenders.xml

<included>
  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%date{ISO8601} %-5p [%t][%c] %m%n</pattern>
    </encoder>
  </appender>
 
  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${app.logs}/travelDesk/travelDesk.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <!-- daily rollover -->
      <fileNamePattern>${app.logs}/travelDesk/travelDesk.%d{yyyy-MM-dd}.log</fileNamePattern>
      <!-- keep 50 days' worth of history -->
      <maxHistory>50</maxHistory>
    </rollingPolicy>
    <encoder>
      <pattern>%X{NDC0}%X{NDC1}%X{NDC2}%X{NDC3}%date{ISO8601} %-5p [%t][%c] %m%n</pattern>
    </encoder>
  </appender>
</included>


Below are the lines from  **loggers.xml
travelDesk-logback-loggers.xml

<included>
<!-- Loggers -->
<logger name="com.traveldesk" level="debug"/>
<logger name="org.springframework.integration" level="warn"/>

<root level="warn">
<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
</root>
</included>










Tuesday 22 March 2016

How to set deploy explodable in Jboss server

If you come across the issue like creating a empty file called xxxx.war.dodeploy in jboss/standalone/deployments folder then its best to set some extra arguments to make it work.

Under standalone.xml which can found at jboss-eap-6.x\standalone\configuration just append the below one
auto-deploy-zipped="true" auto-deploy-exploded="true"
in the below tag 
<deployment-scanner path="deployments" relative-to="jboss.server.base.dir" 

So that it may look like as below
<subsystem xmlns="urn:jboss:domain:deployment-scanner:1.1">
            <deployment-scanner path="deployments" relative-to="jboss.server.base.dir" scan-interval="5000" auto-deploy-zipped="true" auto-deploy-exploded="true"/>
        </subsystem>


This change is advisable to be used used in development or local environment and not in production or other environments.

How to resolve the error "java.lang.IllegalStateException: No transactional EntityManager available"


If you get the below error while using Spring+JPA+Hibernate then try to wrap the method with
import org.springframework.transaction.annotation.Transactional;

@Transactional

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: No transactional EntityManager available
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)

JBWEB000071: root cause
java.lang.IllegalStateException: No transactional EntityManager available
org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:267)
com.sun.proxy.$Proxy39.unwrap(Unknown Source) org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: No transactional EntityManager available
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)

JBWEB000071: root cause
java.lang.IllegalStateException: No transactional EntityManager available
org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:267)
com.sun.proxy.$Proxy39.unwrap(Unknown Source)

How to call Stored Procedure in JPA 2.1

Repository class is as follows

@NamedStoredProcedureQuery(name = "getBalance", procedureName = "getTravelDetails", resultClasses = { TravelDetail.class }, parameters = {
              @StoredProcedureParameter(name = "travelDate", type = Date.class, mode = ParameterMode.IN),
              @StoredProcedureParameter(name = "travelDestination", type = String.class, mode = ParameterMode.IN),

              @StoredProcedureParameter(name = "travelPackage", type = Integer.class, mode = ParameterMode.OUT),
              @StoredProcedureParameter(name = "travelTimings", type = Integer.class, mode = ParameterMode.OUT)})

public class TravelDetail {    
       private Date travelDate;
       private String travelDestination;
       private String travelPackage;
       private Date travelTimings;

  //gettter & setter methods

}


Class that uses the repository

@PersistenceContext
       private EntityManager entityManager;

       @Override
       public void getTravelDetails(Date travelDate,String travelDestination) {
              StoredProcedureQuery storedProcedure = entityManager
                           .createStoredProcedureQuery("getTravelDetails");

              storedProcedure.registerStoredProcedureParameter("travelDate", Date.class,
                           ParameterMode.IN);

              storedProcedure.registerStoredProcedureParameter("travelDestination", String.class,
                           ParameterMode.IN);

              storedProcedure.registerStoredProcedureParameter("travelPackage",String.class,
                           ParameterMode.OUT);
              storedProcedure.registerStoredProcedureParameter("travelTimings", Date.class,
                           ParameterMode.OUT);
           

              storedProcedure.setParameter("travelDate", "20/02/2015");
              storedProcedure.setParameter("travelDestination", "Mount Alps");

              // execute SP

              storedProcedure.execute();

              String travelPackage =  storedProcedure.getOutputParameterValue("travelPackage").toString();        
           

              Date travelTimings = (Date)storedProcedure.getOutputParameterValue("travelTimings");
           
       }

How to execute procedure in Oracle Sql developer


Use the following query to execute procedure in Oracle Sql developer , procedure that is called should be in a format   <schema_name>.<procedure_name>


 SET SERVEROUTPUT ON
var InParam1 varchar2(100)
var InParam2 varchar2(100)

var OutParam1 NUMBER
var OutParam2 NUMBER


BEGIN  
    :InParam1 := 'A04';
    :InParam2 := '4103640874079701';
 
    travel_schema.travel_detail_proc(:InParam1, :InParam2, :OutParam1,:OutParam2);
 
    dbms_output.put_line('OutParam1=='  || :OutParam1 );
    dbms_output.put_line('OutParam2=='  || :OutParam2 );
    dbms_output.put_line('OutParam3=='  || :OutParam3 );
    dbms_output.put_line('OutParam4=='  || :OutParam4 );
END;
/

DataSource Connection with JPA

Below code helps to check the persistence connection

final AbstractApplicationContext context =
TravelRepository repos = (PbfBalanceChangesViewRepository) context.getBean("travelRepository");
TravelView travelView=repos.findByRouteNo("002");

System.out.println(travelView.getAvailBalNew());

aplication-context.xml will look as like below

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:repository="http://www.springframework.org/schema/data/repository"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository-1.7.xsd">

  <context:property-placeholder location="file:///${app.configs}/travel/traveldetails.properties" />

<context:annotation-config />
  <context:component-scan base-package="com.travel"/>
  <!-- Repositories -->
  <jpa:repositories base-package="com.travel.repository"
  entity-manager-factory-ref="travelEmf"
  transaction-manager-ref="transactionManager"/>
<!-- Transactions -->
  <tx:annotation-driven transaction-manager="transactionManager" />


  <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    <property name="database" value="ORACLE"/>
    <property name="showSql" value="true"/>
    <property name="generateDdl" value="false"/>
    <!-- <property name="databasePlatform" value="org.eclipse.persistence.platform.database.OraclePlatform"/> -->
    <property name="databasePlatform" value="org.hibernate.dialect.Oracle10gDialect"/>
  </bean>

  <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
  <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
  <!-- read: http://stackoverflow.com/questions/9136202/defining-hibernateexceptiontranslator-no-persistence-exception-translators-foun -->
  <bean class="org.springframework.orm.hibernate4.HibernateExceptionTranslator"/>

  <jdbc:embedded-database id="dataSource" type="H2">  
<jdbc:script location="classpath:META-INF/sql/travel-schema.sql" />    
  </jdbc:embedded-database>    
 
  <bean id="travelEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
<property name="persistenceXmlLocation" value="classpath:/META-INF/persistence-LOCAL.xml"/>  
    <property name="persistenceUnitName" value="travelPU-LOCAL"/>
    <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
  </bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="travelEmf" />
</bean>    
 
</beans>

Persistence.xml is as follows

<persistence>
    <persistence-unit name="travelPU" transaction-type="RESOURCE_LOCAL">
        <class>com.travel.TravelDetail</class>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527 TravelDB"/>
            <property name="javax.persistence.jdbc.user" value="travel_app"/>
            <property name="javax.persistence.jdbc.password" value="travel_app"/>
        </properties>
    </persistence-unit>

</persistence>



How to get radio button value from html page to controller through Spring MVC + Thymeleaf



<form action="#"
th:action="@{/searchTravelDetails}"
th:object="${searchTravelFormVO}" method="post">
<label th:text="#{global.travel.bus}" >Bus</label>
<input type="radio" name="radiobutton"  value="1"  th:checked="*{bus}"/>
<label th:text="#{global.travel.train}" >Train</label>
<input type="radio"  name="radiobutton" value="0"   th:checked="*{train}" />
</form>


public class SearchTravelFormVO {
   private boolean bus;
   private boolean train;
}


 @RequestMapping(value = "/searchTravelDetails", method = RequestMethod.POST)
public String travelDetailByFilterCriteria(@Valid SearchTravelFormVO searchTravelFormVO,BindingResult bindingResult, Model m,HttpServletRequest request) {

String radiobtnb24=request.getParameter("radiobutton");
}

How to call Get & Put methods using the same request mapping in Spring MVC



@Controller
@RequestMapping(value = "/show-view-and-update")
public class TravelDetailsUpdateController {

 @RequestMapping(method = RequestMethod.GET)
 public String showView(Model m,HttpServletRequest request) {
  return "show-travel-details"
 }
 @RequestMapping( method = RequestMethod.PUT)
 public ModelAndView updateTravelDetails(@Valid TravelDetailsUpdateVO travelDetailsUpdateVO){
  return new ModelAndView("show-travel-details");
 }

}

How to minus months from the current date in java


Simple way to  subtract certain number of months from the current date is as follows


import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;


      SimpleDateFormat format = new SimpleDateFormat("dd MMMM yyyy");
      Calendar c = Calendar.getInstance();
      c.setTime(new Date());
      c.add(Calendar.MONTH, -1);
      Date d = c.getTime();
      String res = format.format(d);
     
Java 8 has the below feature of subtracting months

      Calendar c = Calendar.getInstance();
      LocalDateTime.from(c.toInstant()).minusMonths(1);

How to iterate over list in selection box with thymeleaf + Jquery



<select th:field="*{travelId}" class="span2 form-control add-on">
<option value="NONE">----Select----</option>
<option th:each="travelDetail: ${session.travelDetailsList}"
th:value="${travelDetail}" th:text="${travelDetail}">
This will be replaced - is only used for natural templating
</option>
</select>

How to write enum constant with constructor

Below code helps to have enum through constructor


public enum ResultCode {

   ResultCode_0("Balance was successfully updated.", "0"),
   ResultCode_11("Nothing to do.", "11"),
 

   private final String errorDesc;
   private final String errorCode;
   

   private States(String errorDesc, String errorCode) {
       this.errorDesc= errorDesc;
       this.errorCode= errorCode;       
   }

    // setter and getter
}

How to include message property file in Spring

Please include the below lines of code in application-context.xml and specify the exact path of the message property files. Here in the below example the files such as messages_en.properties are included in META-INF/messages  folder.

<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
p:basename="classpath:META-INF/messages">
<property name="defaultEncoding" value="UTF-8" />
<property name="fileEncodings" value="UTF-8" />
</bean>

Sunday 20 March 2016

How to resolve the error "javax.naming.NameNotFoundException: env/spring.liveBeansView.mbeanDomain"

If you come across such a error as like below

Converted JNDI name [java:comp/env/spring.liveBeansView.mbeanDomain] not found - trying original name [spring.liveBeansView.mbeanDomain]. javax.naming.NameNotFoundException: env/spring.liveBeansView.mbeanDomain -- service jboss.naming.context.java.module....env."spring.liveBeansView.mbeanDomain"

try to add the below lines in web.xml



<context-param>
                <param-name>spring.profiles.active</param-name>
                <param-value>dev</param-value>
        </context-param>
        <context-param>
                <param-name>spring.profiles.default</param-name>
                <param-value>dev</param-value>
        </context-param>
        <context-param>
                <param-name>spring.liveBeansView.mbeanDomain</param-name>
                <param-value>dev</param-value>
        </context-param>

How to resolve issue "No Spring WebApplicationInitializer types detected on classpath"

If the project is maven project and if you see such a error as like below

"No Spring WebApplicationInitializer types detected on classpath"

then check whether webapp folder is present under src/main/webapp and not outside.If webapp folder is present outside then try to place them under src/main/webapp.

Also check whether the Maven dependencies are added in the class path by Right clicking on the project and choose Deployment Assembly then add the maven dependency path)


How to create native query in Hibernate

Below is the simple way to create native query in Hibernate

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

@PersistenceContext
private EntityManager entityManager;

String query = "select travel_destination,travel_package where travel_date=?";
Query q = entityManager.createNativeQuery(query).setParameter(1, travelDate);
q.getResultList();

Tuesday 15 March 2016

How to resolve the error "Servlet.service() for servlet dispatcher threw exception: org.hibernate.SessionException: Session is closed!"

If you try to get a connection from the entitymanager

                      ((SessionImpl)entityManager.getDelegate()).connection();

and still get an exception as below

Servlet.service() for servlet dispatcher threw exception: org.hibernate.SessionException: Session is closed!

then try to use like the below one to get the connection and dont forget to wrap up the method with @Transactional or open a transaction from a session.

@PersistenceContext
private EntityManager entityManager;

 Session session = entityManager.unwrap(Session.class);
 SessionImplementor sessionImplementor = (SessionImplementor) session;
 Connection cc = sessionImplementor.getJdbcConnectionAccess().obtainConnection();



How to Call Stored Procedure through Hibernate + JPA

Following code will help to call the procedure through preparecall

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;


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

import org.hibernate.Session;
import org.hibernate.engine.spi.SessionImplementor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

public class TravelDetailsDAOImpl{
@PersistenceContext
private EntityManager entityManager;

   @Transactional
public void getTravelDetails(String place,Date date) {

Session session = entityManager.unwrap(Session.class);
SessionImplementor sessionImplementor = (SessionImplementor) session;
Connection cc = sessionImplementor.getJdbcConnectionAccess().obtainConnection();
 
 CallableStatement callableStatement = cc.prepareCall("{call stored_procedure(?,?,?,?)}");
 callableStatement.setString(1, "Mount Alps");//Parameter #1 - place
 callableStatement.setString(2, "20/02/2015");////Parameter #2 - travel date

 callableStatement.registerOutParameter(3, Types.INTEGER); //Output # 1
 callableStatement.registerOutParameter(4, Types.INTEGER); //Output # 2
 
 callableStatement.execute();

 Integer outputValue = callableStatement.getInt(3);
 Integer outputValue1 = callableStatement.getInt(4);

 }
}