Thursday, February 4, 2016

java.lang.LinkageError: loader constraint violation org/slf4j/ILoggerFactory

Getting following exception bringing up a Spring Application on Weblogic 11g while trying to instantiate a Spring Controller.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController' defined in
URL [zip:D:/weblogic/servers/AdminServer/tmp/_WL_user/cservice-ws-ear-1/fd4930/war/WEB-INF/lib/_wl_cls_gen.jar!/
com/testapp/web/controller/TestController.class]:
Instantiation of bean failed; nested exception is java.lang.LinkageError: loader constraint violation:
when resolving method "org.slf4j.impl.StaticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory;"
the class loader (instance of weblogic/utils/classloaders/ChangeAwareClassLoader) of the current class, org/slf4j/LoggerFactory,
and the class loader (instance of weblogic/utils/classloaders/GenericClassLoader) for resolved class, org/slf4j/impl/StaticLoggerBinder,
have different Class objects for the type org/slf4j/ILoggerFactory used in the signature
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1076)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1021)

Fix:

This is happening due to the conflict between my ear lib and weblogic provided slf4j jars. I found a workaround to run this ear on my local. I set the prefer-web-inf-classes to false in weblogic.xml under WEB-INF

<wls:prefer-web-inf-classes>false</wls:prefer-web-inf-classes>

The above would use the file provided by weblogic even if it exists in ear lib.

Here is sample weblogic.xml

<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee       http://java.sun.com/xml/ns/javaee/javaee_5.xsd       http://xmlns.oracle.com/weblogic/weblogic-web-app       http://xmlns.oracle.com/weblogic/weblogic-web-app/1.3/weblogic-web-app.xsd">

<wls:container-descriptor>
<wls:prefer-web-inf-classes>false</wls:prefer-web-inf-classes>
</wls:container-descriptor>
    <wls:context-root>deskrev</wls:context-root>

</wls:weblogic-web-app>

Caused By: org.springframework.beans.factory.BeanCreationException: Could not autowire field:

Getting following exception bringing up a Spring Application while trying to instantiate a Spring bean. I have defined the bean and autowired it in my spring controller:

Here is my service. Spring should be instantiated when I bring up the application.

@Service("nameFinderService")
@Lazy(true)
public class NameFinderServiceImpl implements INameFinderService {

}

Here is my Controller where I have autowired the above service:

@Controller
public class MainController{

@Autowired
private INameFinderService nameFinderService;

}

Full Stacktrace:

Caused By: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.nmservice.web.service.INameFinderService com.nmservice.web.base.controller.MainController.nameFinderService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.nmservice.web.service.INameFinderService] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:241)



Fix : The package specified in component-scan in spring configuration was specified to a more specific package as I had my spring files in that package, The new spring bean existed one level higher in package. That was the reason it could not find the bean.

I change the following one level up,

from this
<context:component-scan base-package="com.nmservice.web.base" />
to 
<context:component-scan base-package="com.nmservice.web" />

And the issue got resolved.

Tuesday, February 2, 2016

Android Studio - Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.design.widget.CoordinatorLayout"

Getting following exception while trying to run a Test app. My Activity extends AppCompatActivity.

The exception is thrown when I call setContentView with activity name under onCreate() method.

setContentView(R.layout.activity_welcome_screen);

I see the underlying issue is following :

Suppressed: java.lang.ClassNotFoundException: android.support.design.widget.CoordinatorLayout

Here is the full stack trace:

Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.design.widget.CoordinatorLayout" on path: DexPathList[[zip file "/data/app/com.mobile.app.android-2/base.apk"],nativeLibraryDirectories=[/data/app/com.
is.mobile.app.android-2/lib/arm64, /vendor/lib64, /system/lib64]]
            at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
            at android.view.LayoutInflater.createView(LayoutInflater.java:578)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:750)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:483) 
            at android.view.LayoutInflater.inflate(LayoutInflater.java:415) 
            at android.view.LayoutInflater.inflate(LayoutInflater.java:366) 
            at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256) 
            at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)                         
            at android.app.Activity.performCreate(Activity.java:6550) 
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1120) 
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3108) 
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3263) 
            at android.app.ActivityThread.access$1000(ActivityThread.java:197) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687) 
            at android.os.Handler.dispatchMessage(Handler.java:102) 
            at android.os.Looper.loop(Looper.java:145) 
            at android.app.ActivityThread.main(ActivityThread.java:6897) 
            at java.lang.reflect.Method.invoke(Native Method) 
            at java.lang.reflect.Method.invoke(Method.java:372) 
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 
            Suppressed: java.lang.ClassNotFoundException: android.support.design.widget.CoordinatorLayout
            at java.lang.Class.classForName(Native Method)
            at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
            at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
            ... 23 more
             Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
02-02 11:46:56.471 28238-28238/com.mobile.app.android I/Process: Sending signal. PID: 28238 SIG: 9

Saturday, January 30, 2016

org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned

org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): com.test.TestDO
    at org.hibernate.id.Assigned.generate(Assigned.java:34)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:101)
    at org.hibernate.event.internal.DefaultMergeEventListener.saveTransientEntity(DefaultMergeEventListener.java:255)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:235)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:173)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:849)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:831)
    at org.hibernate.engine.spi.CascadingActions$6.cascade(CascadingActions.java:260)
    at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:379)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:304)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:146)
    at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:412)
    at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:344)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:307)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:146)
    at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:95)
    at org.hibernate.event.internal.DefaultMergeEventListener.cascadeOnMerge(DefaultMergeEventListener.java:468)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:327)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:170)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:69)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:839)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:821)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:826)



Fix:

If you have specified Auto Increment for the Primary Key field, then you can specify "identity" as a generator class in hibernate config file as shown below:



<hibernate-mapping>
    <class name="com.test.service.dataobjects.TestDO" table="test">
    <id name="test" column="testId">
        <generator class="identity"/>
    </id>

....
....
</hibernate-mapping>

Friday, December 4, 2015

Microservices Architecture with exmaple

Microservices are a way to break down a monolithic application into small, simple and independent services that work together, where each is responsible fro a specific function. This brings scalability

The basic concept of microservices also talks about the

Features of MicroServices:
- Service Oriented Approach
- Componentization via Services
- Organized around business capabilities
- Products not projects
- Smart end point dump pipes
- Decentralized governance
- Decentralized data management
- Infrastructure automation
- Design for failure
- Evolutionary design

Tools for building Micro Services

- Scriptable cloud infrastructire to automate continuos delivery release pipelines
- Reliable Messaging Infrastructire to allow service chirography
- Highly productive development framework
- Containerless runtime to allow deployment of one executable per service

Spring Boot

- It makes it easy to create stand-alone, production-grade Spring based Applications.
- Embed Tomcat or Jetty Directly (no need to deploy WAR files)
- Automatically configure Spring whenever possible
- Provide production ready features such as metrics, health checks and externalized configuration.

Create a Spring Boot Application :

References :
This is an example to package and run a spring boot application as a microservice. It will bring up the spring application with an embedded web server.  The executable jar includes all the required libraries to run this as an independent service. Following are the details :

  • The code can be downloaded from github:
https://github.com/SanjayIngole/demo-microservice-springboot/archive/master.zip
  • There is runnable microservice jar as well that can be downloaded from following location:
https://github.com/SanjayIngole/demo-microservice-springboot/blob/master/DemoMicroServices/target/demo-0.0.1.jar

  • To run this microservic. It will bring up the spring application with an embedded web server. 
java -jar demo.jar
  • A test page can be used to upload the sample xml and obtain JSON response.
https://github.com/SanjayIngole/demo-microservice-springboot/blob/master/DemoMicroServices/src/main/resources/testpage.html
  • You can use a docker or boxfuse to deploy this on cloud. I use boxfuse to deploy my microservices to aws. You can setup a boxfuse account (https://console.boxfuse.com/) and configure your aws instance, and then download boxfuse command line client.

  • Package your project using maven, which will package all dependent jars in one file.
    • mvn package
  • And then deploy it using boxfuse command, this deploy this application on configured aws instance. 
    • boxfuse run demo:0.0.1


Tuesday, December 1, 2015

aws mysql connection issues

I just set up a new spring mvc + hibernate application on aws instance via elastic beanstalk.
I created a new MySql db and was able to access it through my localhost, but I couldn't connect to mysql through my beanstalk application deployed on aws instance. 

I was able to fix these issues, and thought its worth sharing the solution as many others developers might be facing the same issue.  The connectivity issue could happen for different reasons, but in my 
case it was security groups that caused the issue.

First thing to make sure you correctly created you db instance, try to ping it from console.

>>>  nc -zv test.xxxxxxxxx.us-west-2.rds.amazonaws.com 3306
Connection to mgdb.czivgxrqpb9q.us-west-2.rds.amazonaws.com port 3306 [tcp/mysql] succeeded!

The aws troubleshooting guide is helpful and I would recommend to read it first.
http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Troubleshooting.html#CHAP_Troubleshooting.Connecting

Here is my spring-hibernate configuration file just for the reference:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<bean id="appDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://xxxxxxx.us-west1.rds.amazonaws.com:3306/mgdb?zeroDateTimeBehavior=convertToNull"/>
    <property name="username" value="xxxxxx"/>
    <property name="password" value="xxxxxx"/>
</bean>

<bean id="appSessionFactory" 
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="appDataSource"/>
    <property name="mappingResources">
        <list>
            <value>employee.hbm.xml</value>        
        </list>
    </property>
    <property name="hibernateProperties">
        <value>hibernate.dialect=org.hibernate.dialect.HSQLDialect</value>
    </property>
</bean>

<bean id="hibernateTemplate" 
class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory">
        <ref bean="appSessionFactory"/>
    </property>
</bean>

</beans>

  • First Connectivity issue:

28-Nov-2015 23:58:47.504 ERROR [localhost-startStop-1] <unknown>.<unknown> Unable obtain JDBC Connection
 com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Caused by: java.net.ConnectException: Connection refused

Fix:

Initially I was getting Connection refused exception but this was gone once I updated the security group to enable all traffic to my ElasticBeanstalk application. 

I have updated the security group to accept All traffic with default IP as shown here. 
(This is okay for testing if you are troubleshooting the connectivity issue, but its a good idea to set specific protocols and destination for more security)


  • Second Connectivity issue :

org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Caused by: java.net.ConnectException: Connection timed out

Fix :
After resolving first issue I was still getting Connection timed out error. Going further in aws documentation I found that we also need to enable the DB Security group to make it accessible from EC2. 

As per aws docs - A DB security group controls network access to a DB instance that is not inside a VPC. By default, network access is turned off to a DB instance. You can specify rules in a security group that allows access from an IP address range, port, or EC2 security group. 

More can be found at this link:
http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithSecurityGroups.html

To change this, go to you DB instance and select "See Details" from "Instance Actions" dropdown.
On the details page click on the security group for your db instance.

Check the inbound and outbound settings for your DB security group. For testing purpose I am setting it to accept All traffic but its always recommended to configure more specific protocols and ip addresses, specially if its production database.

Inbound:


Outbound:





Tuesday, October 20, 2015

No converter found for return value of type: class java.util.ArrayList

I am testing a Spring MVC application , I am calling a database service which returns an ArrayList. I want to return this ArrayList as a Json response to my Jsp, where I am going to iterate through it and render search results through jquery.

 @RequestMapping(value = "/web/getprofiles", method = RequestMethod.GET)
    public @ResponseBody
    List getProfiles(HttpServletRequest request) {
        ArrayList<SearchDO> searchResults = profileService.getProfileSearch();
     return searchResults;

    }

Getting following exception while returning the ArrayList from Controller method :

Oct 20, 2015 10:45:20 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/web] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.ArrayList] with root cause
java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.ArrayList
at org.springframework.util.Assert.isTrue(Assert.java:68)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:124)

I am running this application on tomcat 7.0 with jdk 1.8 and Spring version 4.2.1.RELEASE.

Fix:

The exception here indicates that spring can not find a suitable converter to return ArrayList as a Json object as expected. To resolve this configure the resource resolver in your spring configuration xml.
Make you have specified <annotation-driven /> in spring configuration.



Spring configuration xml

          

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<context:component-scan base-package="com.testweb.controllers" />

<beans:bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <beans:property name="useNotAcceptableStatusCode"
        value="false" />
    <beans:property name="contentNegotiationManager">
        <beans:bean
            class="org.springframework.web.accept.ContentNegotiationManager">
            <beans:constructor-arg>
                <beans:bean
                    class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
                    <beans:constructor-arg>
                        <beans:map>
                            <beans:entry key="html" value="text/html" />
                            <beans:entry key="json" value="application/json" />
                        </beans:map>
                    </beans:constructor-arg>
                </beans:bean>
            </beans:constructor-arg>
        </beans:bean>
    </beans:property>

    <beans:property name="viewResolvers">
        <beans:list>
            <beans:bean
                class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
            
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean id="jspView"
                class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                <beans:property name="prefix" value="/WEB-INF/views/" />
                <beans:property name="suffix" value=".jsp" />
            </beans:bean>
        </beans:list>
    </beans:property>

    <beans:property name="defaultViews">
        <beans:list>
            <beans:bean
                class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
        </beans:list>
    </beans:property>
</beans:bean>

</beans:beans>


             



Make sure you have added required jackson dependencies in your pom.xml

<!-- Jackson JSON Mapper -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.2</version>
</dependency>

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

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.2</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.5.2</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.5.2</version>

</dependency>