SEVERE: Exception sending context initialized event to listener instance of class

SEVERE: Exception sending context initialized event to listener instance of class

This issue typically appear during upgrading java from java 1.7 to java 1.8, and for Java 8 spring 3 does’t work, spring 4 upgrade is compulsory.

 

Exception :

			




SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/Spring-servlet.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:548)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:725)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4994)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5492)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition;
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
    at java.lang.Class.getDeclaredMethods(Unknown Source)
    at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:570)
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:489)
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:502)
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:473)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:241)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineConstructorsFromBeanPostProcessors(AbstractAutowireCapableBeanFactory.java:1059)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1032)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:505)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1471)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1216)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
    ... 20 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.engine.FilterDefinition
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
    ... 41 more

Solution
Hibernate 3
———————————
<bean id=”transactionManager”
        class=”org.springframework.orm.hibernate3.HibernateTransactionManager”>
        <property name=”sessionFactory” ref=”sessionFactory” />
</bean>
    
<bean id=”sessionFactory”
    class=”org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean”>
</bean>

Hibernate 4
———————————
<bean id=”transactionManager”
        class=”org.springframework.orm.hibernate4.HibernateTransactionManager”>
        <property name=”sessionFactory” ref=”sessionFactory” />
</bean>

<bean id=”sessionFactory”
    class=”org.springframework.orm.hibernate4.LocalSessionFactoryBean”>
</bean>

pom.xml changes

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>4.0.0.Final</version>
</dependency>

Circle drawing and filling arc in android

Circle drawing and filling arc in android

It is always a fun to play with mathematics, everything in this world is happening because mathematics. Mathematics is everywhere, every moment. Computers, physics, chemistry, biology every area is just standing upon Math.

Being an enthusiastic developer I always love to play with mathematics, so here is an example which draws a circle and a filling arc within the circle. Definitely you will get a the code in many web sites if you just google. But i would like to explain the math that plays an important role to achieve this.

The result should look as follow.

CircleFillingAndroid
CircleFillingAndroid

Let me divide the code in three sections.

Section 1 : Drawing a circle

How to draw a circle in android using Canvas and Paint ?

Code :

   

        int screenWidth = 420;  //Give your device screen width here 
        int horizontalCentreX = screenWidth/2;
        int circleCentrex = horizontalCentreX;
        int circleCentreY = 150;
        int radius = 130;
        int arcStartingAngle = 270;
        int minutes = 15;
        int seconds = 60;
        int minsToSecondsConverionFactor= minutes * seconds; //just to fill the circle for 15 mins
        int arcRectStartingX = circleCentrex - radius;
        int arcRectStartingY = 20;
        int arcRectEndingX = circleCentrex + radius;
        int arcRectEndingY = 280;

       //Just create a bit map of size (width = screen width, height = depends on how big circle you want
         Bitmap b = Bitmap.createBitmap(screenWidth, 300, Bitmap.Config.ARGB_8888);

        Paint paint = new Paint();
        Canvas canvas = new Canvas(b);
        paint.setColor(Color.rgb(62, 176, 220));
        paint.setStrokeWidth(10);
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);
  
        canvas.drawCircle(circleCentrex, circleCentreY, radius, paint);

Section 2 : Drawing an Arc

So How to draw a filling arc in android using Canvas and Paint ?

Code :

   paint.setColor(Color.rgb(250, 64, 129));
        paint.setStrokeWidth(10);
        paint.setStyle(Paint.Style.FILL);
        final RectF oval = new RectF();
        paint.setStyle(Paint.Style.STROKE);
        oval.set(arcRectStartingX, arcRectStartingY, arcRectEndingX, arcRectEndingY);
        canvas.drawArc(oval, arcStartingAngle, ((i * 360) / minsToSecondsConverionFactor), false, paint);

Section 3 : Drawing a Point at the end of the filling arc

Here is the trick, to calculate the end point in the filling arc, we need to apply Trigonometry. Let me explain this in steps.

Observe the figure given below,

circle
circle

The figure shows Circle drawn at the centre point(CenterX,CenterY) . We have have an arc which will be continuously drawn and the arc fills the circle in the direction as shown in the figure. So our job is to find out the point(x,y) and the end of the arc.

If you observe a triangle drawn with Centre of the circle and point over the arc, it will be a right angled triangle.

So by applying trigonometry

  cos(θ) = adjacent / hypotenuse
         = adjacent / radius ( because radius == hypotenuse)
         
  adjacent = cos(θ) * radius
       x   = cos(θ) * radius ( this is because point (x,y) is nothing but point is X distance (along X-Axis) aways from Centre and Y distance away (along Y-Axis).

 sin(θ) = opposite / hypotenuse
        = opposite / radius
      y = sin(θ) * radius ( this is because point (x,y) is nothing but point is X distance (along X-Axis) aways from Centre and Y distance away (along Y-Axis).

But the values we got x and y are from the centre but the centre is centreX distance aways from the left side of the screen and centreY distance away from the top side of the screen.

Hence point x on the arc must be = centreX + x distance aways from Left side of the screen
                                 = centreX + cos(θ) * radius

Hence point y on the arc must be = centreY + y distance aways from Left side of the screen
                                 = centreY + sin(θ) * radius


If you debug and observe the y value we get will increase initially and start decreasing, this depends upon the angle, angle less than or equal to 90deg will be give +ve value for cos(θ) and angle greater than 90deg will give -ve value.

Hence the above calculation always gives you end point of the filling arc along the circumference of the circle.

 

 

Amazon AWS EC2 Security Group and S3 Bucket Configuration

Amazon AWS EC2  Security Group and S3 Bucket configuration

Read our previous post : How to Create And Configure Amazon EC2 Free tier account

Amazon AWS is an awesome cloud service, It is worth writing a post on AWS service and its usage.

It is very easy to create an AWS account and use it, but most people will struck when its matter of security. Amazon setup is little bit complicated for security configuration. Please follow the steps given below to enable security group in your amazon cloud service.

Steps For Amazon EC2 Security Group:

Step 1: Go to your EC2 Service as shown in the image below

EC2
EC2

Step 2: Go to the section Security Group

Amazon Security Group
Amazon Security Group

 

Step 3: Enter Group Details 

Amazon Security group details
Amazon Security group details

 

Step 4: Add following rules 

Inbound

  • Rule 1

 Type : HTTP

 Protocol : TCP

 Port Range : 80

 Source : 0.0.0.0/0

  • Rule 2

 Type : All traffic

 Protocol : All traffic

 Port Range : All traffic

 Source : Your Ip Address ( search in google What Is My IP, copy paste the same IP here )

  • Rule 3

 Type : SSH

 Protocol : TCP

 Port Range : 22

 Source : Your Security Group Id

  • Rule 4

 Type : MYSQL

 Protocol : TCP

 Port Range : Mysql port ( 3306 )

 Source : Your Security Group Id

Outbound

  • Rule 1

 Type : HTTP

 Protocol : TCP

 Port Range : 80

 Source : 0.0.0.0/0

  • Rule 2

 Type : All traffic

 Protocol : All traffic

 Port Range : All traffic

 Source : Your Ip Address ( search in google What Is My IP, copy paste the same IP here )

  • Rule 3

 Type : MYSQL

 Protocol : TCP

 Port Range : Mysql port ( 3306 )

 Source : Your Security Group Id

Amazon S3 Bucket configuration

Step 1 : Go to Administration and Security from Amazon Services

Amazon S3 : IAM
Amazon S3 : IAM

 

Step 2 : Select Group from the IAM page

Step 3: Create new group, Give any name for the group

Step 4: The most important step is to set Policy type for the S3 bucket.

For file upload/download, Select AmazonEC2FullAccess

If this is done then your Amazon S3 is ready for use.

Step 5: Go to S3 service from the main menu

There create new bucket. Set permissions to your bucket as per your need.

File Upload to Amazon S3 bucket in Java 

Code Sample :

private static String bucketName = “”; //Give your YourS3Bucket name
private static String keyName = “”; // Give SomeKey

public final static String FOLDER_PATH = “TestFolder”;

public final static String rootServerURL = “”; //Your S3 Bucket Path => Your Amazon Instance / BucketName

BasicAWSCredentials awsCreds = new BasicAWSCredentials(“AccessKey”, “SecretKey”);

AmazonS3 s3client = new AmazonS3Client(awsCreds);

PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, fileObject);
putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead); // Read Permission for all
s3client.putObject(putObjectRequest);

Lambda Expressions in java – A Java 8 feature

What are Lambda Expression – Java 8 new feature?

Lambda expressions refers to what we had anonymous classes in the older versions of java.

So the very next straight forward thing comes to our mind, if already java is having anonymous classes why a replacement for the same is needed?

Why are Lambda Expressions needed, even if anonymous classes already exist?

The answer goes very simple, Lambda expressions when used makes our code more lighter as compared to when we use anonymous classes.

For Example:

Consider there is a class called Person
To sort the Person class by name if we use anonymous class we have to use the following code

Collections.sort(list, new Comparator() {
  @Override
  public int compare(Person p1, Person p2) {
       return p1.getName().compareTo(p2.getName());
  }
 });

But if we use Lambda expressions it will reduce to just 1 line, as show below,

Collections.sort(list, (Person p1, Person p2) -> p1.getName().compareTo(p2.getName()));

reduces lot of bulky codes.

Lets Discuss one example in detail:

We all are aware of Service Oriented Architecture if not please go through the tutorial 

Calling services will always be time consuming (in general all network calls are considered slow), so we handle those requests asynchronously. If the call is asynchronous then in order to get the response from the service we expect a call back to be called which will return us the result.

The following example demonstrates rather tries to simulate such a scenario,
Consider the following class “ThreadCallableClass” which will make the call to service,

//CallBack.java
package com.dhi.callback;

@FunctionalInterface
public interface CallBack {
	void operationCompelte(String args);
}


//ThreadCallableClass.java

package com.dhi.thread;

import java.util.concurrent.Callable;

import com.dhi.callback.CallBack;

public class ThreadCallableClass implements Callable{
	
	public ThreadCallableClass(CallBack callBack) {
		this.callBack = callBack;
	}

	CallBack callBack;

	String str;
	
	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}
	
	@Override
	public String call() throws Exception {
		System.out.println("service is getting called with the value: " + str);
		//code to call the service to fetch some details
		callBack.operationCompelte(str);
		return "return " + str;
	}

}

//MAIN.JAVA

package com.dhi.main;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.dhi.thread.ThreadCallableClass;

public class MainClass {

	public static void main(String[] args) {
		List list = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			list.add("dhi" + i);
		}

		ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(
				1000);
		ExecutorService executorService = new ThreadPoolExecutor(10, 100, 20,
				TimeUnit.SECONDS, arrayBlockingQueue);
		for (String eachStr : list) {
			ThreadCallableClass callable = new ThreadCallableClass((String test1) -> {System.out.println(" call back getting called for the service for "+ test1);});
			callable.setStr(eachStr);
			executorService.submit(callable);
		}
		System.out.println("after thread pool");
		executorService.shutdown();
	}

}

//Person.java
package com.dhi.main;

import java.io.Serializable;

public class Person implements Serializable{
	
	String name;
	String mob;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getMob() {
		return mob;
	}
	public void setMob(String mob) {
		this.mob = mob;
	}

}


Download Code
DhiJava8LambdaFeature

Spring3 Issue with java8

Spring3 Issue with java8

Most common problem every one face during upgrading java to java8

Problem: All is well in your java spring3 web application, suddenly you start getting,






java.lang.IllegalArgumentException
at org.springframework.asm.ClassReader.(Unknown Source)
at org.springframework.asm.ClassReader.(Unknown Source)
at org.springframework.asm.ClassReader.(Unknown Source)
at org.springframework.core.type.classreading.SimpleMetadataReader.(SimpleMetadataReader.java:52)
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80)
at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101)
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76)
at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:298)
at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300)
at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:230)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:153)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:130)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:285)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:223)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4961)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5455)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)


			




Solution:

This issue is due to update of java to java 8, Following are the solutions for the same,

  1. You still intend to use java8 then spring must be upgraded to 4 or
  2. Change back the version of java to java7.

Steps to change in eclipse,

  1. Right click on the project and goto properties.
  2. Select “Java Build Path”.
  3. Goto “Libraries” tab.
  4. Select JRE System Lib (sometimes the name will mislead, it will be showing java7 but internally it will be pointing to java8).
  5. Click on “Edit” button present on the right side.
  6. Select “Alternate JRE” and click on “Installed JRE”.
  7. Click on “Add” è “Standard VM”.
  8. Click on “Directory” and select the JRE7 home.
  9. An entry for jre7 will be present, check the check box present against jre7.
  10. Click “Ok”
  11. Click on “Finish”.
  12. Click “Ok” again.
  13. Click on “Project” menu and then “Clean”
  14. Wait till the build completes.

You are good with all now again.

Jersey ClientHandlerException : A message body writer for Java type, class org.json.JSONObject, and MIME media type,

lientHandlerException: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class org.json.JSONObject, and MIME media type, application/json,

com.sun.jersey.api.client.ClientHandlerException: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class org.json.JSONObject, and MIME media type, application/json, was not found
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:149)
    at com.sun.jersey.api.client.Client.handle(Client.java:648)
    at com.sun.jersey.api.client.WebResource.handle(WebResource.java:670)
    at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
    at com.sun.jersey.api.client.WebResource$Builder.post(WebResource.java:563)
    at com.knowledgecess.test.service.impl.TestServiceImpl.getQuestions(TestServiceImpl.java:48)
    at com.knowledgecess.test.action.TestAction.demotest(TestAction.java:70)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:453)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:292)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:255)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:236)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:236)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:90)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:192)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:511)
    at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:432)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
Caused by: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class org.json.JSONObject, and MIME media type, application/json, was not found
    at com.sun.jersey.api.client.RequestWriter.writeRequestEntity(RequestWriter.java:288)
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:204)
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:147)
    ... 74 more
knowledgecess







Solution :
Just find jsonInput, second parameter for post() in the below code add toString to jsoninput data

ClientResponse clientResponse = webResource
                .accept(MediaType.APPLICATION_JSON)
                .type(MediaType.APPLICATION_JSON)
                .post(ClientResponse.class, jsonInput);

FIX –

ClientResponse clientResponse = webResource
.accept(MediaType.APPLICATION_JSON)
.type(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, jsonInput.toString());

Java Jar files; Java Libraries; JSON lib;

Java Jar files and Uses

JAR:  aopalliance-repackaged-2.2.0.jar 

Usage: aop alliance will be internally used by

Note : Google Guice Core is a powerful library released by Google for dependency injection, this works with java 6 and above ( download )

JAR:  apache-mime4j-0.6.jar

Usage: apache mime will be used for mime message parsing. This jar internally used by 

  • commons-io
  • commons-logging
  • junit like testing libraries
  • log4j 

JAR : commons-io

Usage – commons io provides utility classes, stream implementations, file filters,file comparators, endian transformation classes

JAR : asm-3.3.jar

Usage : asm jar will be used to analyse the byte code and analyse the frameworks

Note: asm is used by certain code generation libraries like cglib

JAR : gson-2.3.jar 

Usage : gson used to convert java objects into json object. Can be used in struts and springs to convert java objects. ( Documentation )

 JAR : persistence-api-1.0.jar

 Usage : The Java Persistence API provides Java developers with an object/relational mapping facility for managing relational data in Java applications

Dependencies :

  • Servlet-API
  • Javax.inject 

JAR : hk2-api-2.2.0.jar 

Usage : This is called hundred kilobyte kernal for glassfish server, It forma the core glassfish server architecture

 

Hibernate NoSuchBeanDefinitionException : Java Hibernate Exception

Hibernate NoSuchBeanDefinitionException : Java Hibernate Exception

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.cess.service.Employee.EmployeeService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=EmployeeServiceImpl)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:949) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:818) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486) … 25 more

Solution – 

This issue is a strange issue in hibernate autowire for bean objects, the solution will be as follows but no technical description why so ? 🙂

@Autowired
@Qualifier("EmployeeServiceImpl")
EmployeeService employeeService;  //EmployeeService is an interface


			




Change the above @Qualifier as below 
@Qualifier("employeeServiceImpl")

Note : the only change is instead of capital E in EmployeeServiceImpl, it should be small 'e' employeeServiceImpl
If it is reverse case then do make it Capital .

Hibernate QueryException : could not resolve property:

Hibernate QueryException :  could not resolve property:

org.hibernate.QueryException: could not resolve property: DP of: com.cess.pojo.Customer
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:67)
at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:61)
at org.hibernate.persister.entity.AbstractEntityPersister.getSubclassPropertyTableNumber(AbstractEntityPersister.java:1402)
at org.hibernate.persister.entity.BasicEntityPropertyMapping.toColumns(BasicEntityPropertyMapping.java:54)
at org.hibernate.persister.entity.AbstractEntityPersister.toColumns(AbstractEntityPersister.java:1377)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getColumns(CriteriaQueryTranslator.java:457)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getColumnsUsingProjection(CriteriaQueryTranslator.java:417)
at org.hibernate.criterion.SimpleExpression.toSqlString(SimpleExpression.java:68)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getWhereCondition(CriteriaQueryTranslator.java:357)
at org.hibernate.loader.criteria.CriteriaJoinWalker.(CriteriaJoinWalker.java:113)
at org.hibernate.loader.criteria.CriteriaJoinWalker.(CriteriaJoinWalker.java:82)
at org.hibernate.loader.criteria.CriteriaLoader.(CriteriaLoader.java:91)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1577)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:306)
at com.cess.dao.impl.CusomerDaoImpl$1.execute(CustomerDaoImpl.java:77)
at com.cess.framework.TransactionWrapper.run(TransactionWrapper.java:41)
at com.cess.dao.impl.CustomerDaoImpl.getCustomers(CustomerDaoImpl.java:43)
at com.cess.service.impl.CustomerServiceImpl.getCustomers(customerServiceImpl.java:39)
at com.cess.controller.CustomerController.Customers(CustomerController.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:822)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)

			




Solution –
Instead of using nested paths directly in Criteria API (unlike HQL), create nested criteria instances and use aliases on each “entity.property”
Example –






Criteria criteria = sessionObject
.createCriteria(Customer.class, "C")
.createAlias("C.department", "D")
.createAlias("D.Section", "S")
.createAlias("S.SubSection", "SB")

SEVERE: Exception sending context initialized event to listener instance of class

SEVERE: Exception sending context initialized event to listener instance of class

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map '/project' bean method
public java.util.ArrayList com.cess.controller.UserProjectController.UserProject(com.cess.pojo.Class)
to {[/get],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already '/userinfo' bean method
public java.lang.String com.cess.controller.UserController.userInfo(com.cess.pojo.User) mapped.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1486)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:524)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.IllegalStateException: Ambiguous mapping found. Cannot map '/project' bean method
public java.util.ArrayList com.cess.controller.UserProjectController.UserProject(com.cess.pojo.Class)
to {[/get],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already '/userinfo' bean method
public java.lang.String com.cess.controller.UserController.userInfo(com.cess.pojo.User) mapped.
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.registerHandlerMethod(AbstractHandlerMethodMapping.java:179)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:145)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:107)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:87)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:150)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1483)
... 22 more

Solution
If your controller class are as follows







			




@Controller("/userinfo")
public class UserController {
@RequestMapping(method=RequestMethod.POST)
 public String userInfo(@RequestBody User user){
 }
}

@Controller("/userproject") 
public class UserProjectController {

@RequestMapping(method=RequestMethod.POST)
  public String userProject(@RequestBody UserProject userProject){
  }
}

//Then Use value Element of @RequestMapping as follows
@Controller
public class UserController {
 
 @RequestMapping(value = "/getuserinfo", method=RequestMethod.POST)
 
  public String userInfo(@RequestBody User user){

  }
}


@Controller
public class UserProjectController {
 //Note value in both controller requestMapping should be different
 
 @RequestMapping(value = "/getuserproject",method=RequestMethod.POST)
  public String userProject(@RequestBody UserProject userProject){

  }
}