Thursday, December 18, 2014

Blocking the UI till your ajax request complete

Required JS plugin for block UI.<script type="text/javascript" src="js/jquery.blockUI.js"></script>
$(document).ready(function(){
  $(document).ajaxStart(function(){
  $.blockUI({ message: '<img src="images/wait.gif" /> Computation in progress...' });
  });
  $(document).ajaxComplete(function(){
   $.unblockUI();
  });
});

Wednesday, November 12, 2014

Sunday, November 2, 2014

Springs @Async and @Transactional issue

While using this combination I used to get the below error:

org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

To fix this issue we have to design out service layer/DAO.. as below.: 

Controller Code:

@Autowired
ComputationService computationService;

Below is the controller method :
@RequestMapping(value ="/saveAndBuild", method = RequestMethod.POST)
public String saveAndBuild (Model model, final HttpServletRequest request,
@ModelAttribute(REVIEW_AND_BUILD_FORM) ReviewAndBuildForm reviewAndBuildForm) {
computationService.startComputations(reviewAndBuildForm.getFile(), reviewAndBuildForm.getReportId(),computationService.updateStatusByFileId(reviewAndBuildForm.getFile()));

This is the service class which creates instances of @Async methods classes:
Here we need to say @EnableAsync at class level indicating to accept async process,

@Service
@EnableAsync

public class ComputationServiceImpl implements ComputationService {


Method which actually calls the Async methods from this interface. 
@Override
public void startComputations(Long fileId, Long reportId,VaDdFileInfo vaDdFileInfo){
asyncCompuationService.executeComputationAsync(fileId,reportId,vaDdFileInfo);


}


Below is the sample code for @Async method:

Note:Make sure here you should not include @transaction at class level or method level.You need to call another service which actually has business layer which contains the @Transcation attribute


@Override
@Async
public void executeComputationAsync(Long fileId, Long reportId,
VaDdFileInfo vaDdFileInfo) {

computationProcessService.executeComputationAsync(fileId, reportId, vaDdFileInfo);


}

Below is the actual Transactional point

/**
* {@inheritDoc}
*/
@Override
@Transactional(value = "npTransactionManager", propagation = Propagation.REQUIRED)
public void executeComputationAsync(Long fileId, Long reportId,
VaDdFileInfo vaDdFileInfo) {

try{
List<VaDdFileData> vaDdFileDataList = vaDdFileDataDao.findByFileId(fileId);



Thursday, October 30, 2014

Upgrading spring from 3.0.6. to 4.1.1.RELEASE[Respective hibernate mapping files]

Here is the changes:

Below are the artifacts which are used in the 3.0.6 release


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.0.6.RELEASE</version>
<scope>compile</scope>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.0.6.RELEASE</version>
</dependency>

<!-- Hibernate dependencies -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.5.6-Final</version>
</dependency>

Now I am updating this with spring version:
<org.springframework.version>4.1.1.RELEASE</org.springframework.version>

and the hibernate core version with  4.2.4.Final


After upgrading to this,When I started my application I got the below exception.

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
java.lang.VerifyError: (class: org/springframework/context/annotation/ConfigurationClassEnhancer$BeanMethodInterceptor, method: intercept signature: (Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;Lorg/springframework/cglib/proxy/MethodProxy;)Ljava/lang/Object;) Incompatible argument to function
at org.springframework.context.annotation.ConfigurationClassEnhancer.<clinit>(ConfigurationClassEnhancer.java:67)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:377)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanFactory(ConfigurationClassPostProcessor.java:259)


Issue because of JReble.. , I run my server with out JReble got different issue.

Issue 2#
java.lang.NoClassDefFoundError: org/hibernate/util/DTDEntityResolve


Solution :

When I got the above exception I removed the below dependency.

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
</dependency>

Hibernate 3.5 and onward contains Hibernate Annotations.

Issue 3#

NoCacheRegionFactoryAvailableException: Second-level cache is used in the application, but property hibernate.cache.region.factory_class is not given,

Solution:
Added the below property in hibernate.cfg.xml file

<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>

Now I am ready :-)

Monday, October 27, 2014

ConfigurationHolder in grails 2.4.2

ConfigurationHolder class has been removed from grails 2.4.2 

It has been replaced with Holder class

Sample code
def baseUrl = ConfigurationHolder.config.icann.base.url 

is replaced with 
def baseUrl = Holders.config.icann.base.url

Refer :http://grails.org/doc/2.4.2/guide/upgradingFrom23.html  for more information

Wednesday, October 22, 2014

Maven commands

To clean and create target folder:

mvn clean install

To set the eclipse class path:

mvn eclipse:eclipse

To clean the eclipse class path

mvn eclipse:clean

Monday, October 20, 2014

Reading a custom properties or default message properties in spring service/controller..etc


Custom properties file
Need to configure the property files in this format.

Make sure you keep the properties in your class path.

<?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:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
  <util:properties id="npAdminProperties" location="classpath:npadmin.properties" />
 </beans>

Example:

npadmin.properties file:

environment.code=DEV


To read the values from the properties files in service/controller you can inject like

private @Value("#{npAdminProperties['environment.code']}") String environment;


To read a Message properties in controller or service :

One way of doing:

@Autowired
private MessageSource messageSource;

messageSource.getMessage("domaindetector.builder.email.subject",null, Locale.ENGLISH)

Other way:
@Value("${domaindetector.builder.email.subject}")

private String domainDetecorEmailSubject;

Spring controller- Return to a specific view

Return type of a controller method should be ModelAndView

ModelAndView retryBuildersStart(Model model,
final HttpServletRequest request,..etc) {

new ModelAndView("viewName", "formName", form);
}

Wednesday, October 15, 2014

Wednesday, October 8, 2014

Springs (Profiling a method) using AOP.(logging the method execution time)

Dependencies:

pom.xml file add the below jar's:
          <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.0.6.RELEASE</version>
</dependency>

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency>

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>

Creating the pro-filer :

package com.cscinfo.npadmin.aspect;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
 * @author kvennamp
 *
 */
@Aspect
public class BusinessProfiler {

private static final Logger logger = Logger.getLogger(BusinessProfiler.class);

@Pointcut("execution(* com.cscinfo.npadmin.service.impl.*.*(..))")
    public void serviceMethods() { }

    @Around("serviceMethods()")
    public Object profile(ProceedingJoinPoint pjp) throws Throwable {
            long start = System.currentTimeMillis();
            logger.info("Going to call the method "+pjp.getSignature().getName());
            Object output = pjp.proceed();
            logger.info(pjp.getSignature().getName()+"Method execution completed.");
            long elapsedTime = System.currentTimeMillis() - start;
            logger.info(pjp.getSignature().getName()+" Method execution time: " + elapsedTime + " milliseconds.");
            return output;
    }
}


In application context.xml file write

<aop:aspectj-autoproxy />
<bean id="businessProfiler" class="com.cscinfo.npadmin.aspect.BusinessProfiler"></bean>

Here all the services classes and method are inside the
com.cscinfo.npadmin.service.impl package.

The Above pro-filer will log the method name followed by how much time it took to process.

Thursday, October 2, 2014

Set external jar in class path when using the POM file.

This is how you can add the system path jar file in pom.xml here scope must be system level

<dependency>
<groupId>com.nameprotect.tm.pronto.webservice</groupId>
<artifactId>TmProntoWebService</artifactId>
<scope>system</scope>
<systemPath>C:/work/Projects/old-np-trunk/TmProntoWebService/dist/TmProntoWebService.jar</systemPath>
<version>1.2</version>

</dependency>

Get the performance time of a method in java.

This will return the total time in milliseconds

long startTime = System.currentTimeMillis();
for(String id :ids) {
client.detail("US", id);
}
long endTime   = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println(totalTime+"<--- total time");

Monday, September 29, 2014

Can we create a hibernate file with out id field?

Answer is NO.

Here is why?
Hibernate identifies Objects (in first and 2nd level cache) using the ID of the object, so an object without an ID cannot be represented in hibernate.

Solution:
You need create a composite key combination . But finally you need to have any one of id combination. :-)

  <class name="com.cscinfo.nameprotect.db.np.dao.VaObBuildQueueView" table="VA_OB_BUILD_QUEUE_VIEW" schema="NP">
    
    <composite-id>
<key-property name="fileId" column="FILE_ID"  />
<key-property name="fileDataId" column="FILE_DATA_ID"  />
<key-property name="vaBuildRequestId" column="BUILD_REQUEST_ID"  />
</composite-id>

Friday, September 26, 2014

How to write a junit test case for a void return type?

Example code:

public void initiateArchiverBuilder(WcBrand wcBrand,
VaReportEntry vaReportEntry) {
VaBuildRequest vaBuildRequest = new VaBuildRequest();
vaBuildRequest.setObjectId(vaReportEntry.getId());
vaBuildRequest.setPriority(1);
vaBuildRequest.setBuilder("BUILDER_ARCHIVER");
vaBuildRequest.setAction("ARCHIVER_ACTION_ARCHIVE)";
vaBuildRequestDao.create(vaBuildRequest);
}

Junit :

You can verify the create method is called or not in junit.
Mockito.verify(vaReportEntryDao).create(Mockito.any(VaReportEntry.class));

To verify a Method is called or not in JUNIT which is running by MockitoJUnitRunner

We can verify a method its called or not?

This is the way to verify:

Mockito.verify(vaBuildRequestDao).create(Mockito.any(VaBuildRequest.class));

Above verify meaning we should expect a create method be called on VaBuildRequestDao.


Mockito.verify(vaBuildRequestDao,Mockito.times(2)).create(Mockito.any(VaBuildRequest.class));

Above verify meaning we are expecting the create method is called 2 times on VaBuildRequestDao .If it wont call the test case will be failed.

Friday, September 19, 2014

Composite key in hibernate

@Embeddable
public class RolesMenu {
    @Column(name = "RoleID")
    private String roleID;

    @Column(name = "MenuItemID")
    private String menuItemID;

    //getter, setter methods
}

 @Entity
 @Table(name = "RolesMenuItems")
 public class RolesMenuItems {

     @EmbeddedId
     private RolesMenu roleMenu;

  /*setter getter methods */
 }

Thursday, September 18, 2014

confirm box issue in IE.

Confirm box will never work in IE7 & 8 , When you click on cancel also it will continue the same operation.

Here is solution or fix:

if(confirm('Do you really want to delete this document?')==false){event.returnValue=false;return false;}else{return true;};

This will fix the confirm box IE issue.

Thanks,
kiran.vennampelli.

Wednesday, September 10, 2014

Formatting or customizing the jqgrid colmodel view

JqGrid colModel setup:
Here we need to add new property to customize the data for example building a hyper link instead of showing the data, we need to add property called formatter below is the sample code 
colModel : [{name : 'whois',
index : 'whois',
width : 25,
align : 'center',
sortable : false,
editable : false,
classes : "actions-col",
formatter : buildWhoisLink
},
......
]




Here is the function for buildWhoisLink

function buildWhoisLink(cellvalue, options, rowObject) {
return "<a id=\"whois_"+options.rowId+"\" onclick=\"return showWhois('"+rowObject[0]+"', "+options.rowId+");\" href=\"#\">Whois</a>";
}

Tuesday, September 9, 2014

Jquery:Call some other click event in a other function

<input type="button" id="saveUpdatedRows" value="Save" />

Simple button click function:This function will be called when save button is clicked.
$(function(){
$("#saveUpdatedRows").click(
   function(){
    //Write your logic
   }
);        

});

When you want to call same save button click function from some other function eg. like on pagination, on complete ..etc.

you can use the trigger function to trigger the click event on saveUpdatedRows function.
Code below:

$( "#saveUpdatedRows" ).trigger( "click" ); 

Wednesday, August 13, 2014

Submit a form with different actions using Jquery.


Here is the jsp:

<form:form id="clientLinkAbuseTypesForm" method="post"  commandName="clientLinkAbuseTypeForm">
...

<input type="submit" id="saveLinkAbuse" value="Save">
<input type="submit" id="cancelLinkAbuse"  value="Cancel" >

</form:form>

Here I have 2 different buttons each need to be calls different action and also need to send all form parameters. In this situation we need to change the form action's dynamically

Here I am explaining with the Jquery:

<script language="javascript">
$(document).ready(function()
{
   $("#saveLinkAbuse").click(function()
   {
        $("#clientLinkAbuseTypesForm").attr("action", "saveClientLinkAbuseTypes");
      // we can change the method type
     like $("#clientLinkAbuseTypesForm").attr("method", "get");  // or post here.
       $("#clientLinkAbuseTypesForm").submit();

   });

                 $("#cancelLinkAbuse").click(function()
    {
  
     $("#clientLinkAbuseTypesForm").attr("action", "cancelLinkAbuse");
        $("#clientLinkAbuseTypesForm").submit();

    });
}
);
</script>

From the above code you can observe the action attribute changing dynamically.. This will hit the corresponding action methods in controller with form fields...

Spring - multiple check boxes check

This Post explain you how to auto check the check box fields in Spring's at the time of loading page:


In controller you need to set the selected categories:

clientLinkAbuseTypesForm.setSelectedCategories(new Long{10,11..etc});

In Jsp page:
<c:forEach items="${displayGroup.value }" var="cateogryRec" varStatus="rec" >
<form:checkbox path="selectedCategories" value="${cateogryRec.key }" /><span id="Name"><c:out value="${cateogryRec.value }"/></span></td>


Here selectedCategories is the  Long[] selectedCategories of form ; Which contains the check box values which to make checked=true.

The spring will take care of checked=true .

Maven cobertura integration for JUNIT code coverage report

Add the below code inside the pom.xml

This should be under build tag
<build>
....
       <plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
                                <version>2.6</version>
<configuration>
<check></check>
<formats>
<format>html</format>
<format>xml</format>
</formats>
<instrumentation>
<ignores>
<!-- <ignore>com.cscinfo.dc.triage.solr.*</ignore> -->
</ignores>
<excludes>
                                                     <!--This is place where we can ignore the list of class which we really don't require junits -->
<exclude>com/cscinfo/dc/triage/solr/*.class</exclude>
</excludes>

</instrumentation>
</configuration>
</plugin>
Under the report tag add the below code
<reporting>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.6</version>
</plugin>
</plugins>
</reporting>

To generate the cobertura report run
mvn cobertura:cobertura
This will generate the html report under target/site/cobertura/index.html.