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);

 }
}

Saturday 12 March 2016

Creating Entity classes for tables which do not have any primary key in Hibernate

Create a class with composite keys

@Embeddable
public class ClassificationPK implements Serializable {
    @Column(name="EMPLOYEE_NAME")
private String username;
@Column(name="EMPLOYEE_PHONE_NUMBER")
private String userDet;
}


@Entity
@Table(name="EMPLOYEE", schema="employee_detail")
@NamedQuery(name="Employee.findAll", query="SELECT i FROM Employee i")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;

@Column(name="EMPLOYEE_NAME" , insertable=false, updateble=false)
private String userName;

@Column(name="EMPLOYEE_DETAILS")
private String userDet;

@Column(name="EMPLOYEE_PHONE_NUMBER" , insertable=false, updateble=false)
private String userDet;

}

How to resolve Error "Error occurred during initialization of VM" in Eclipse Kepler


If you get the below error in Eclipse Kepler while starting JBOSS server or any other server

Error occurred during initialization of VM
Could not reserve enough space for 1048576KB object heap
Picked up JAVA_TOOL_OPTIONS: -Djava.vendor="Sun Microsystems Inc."
Java HotSpot(TM) Server VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0

Then try to modify as like below by double clicking on the Jboss server from Servers tab in Eclipse and then click on "Open launch configuration" . Edit the vm arguments  under the Arguments
if  Xms & Xmx  value is set to 1024 lower them to 512
-server -Xms512m -Xmx512m -XX:MaxPermSize=256m