Using the service layer in custom authentication-provider ( Spring security 3.2) - spring

I dont understand why i cant use the the service layer(file: Userservice ) in the authentication-provider (file: userDetailsService ). In result i had the error below, but when i used Repository layer(file: Repository) all are fine.
i would like to encapsulate the Repository layer(Spring data Jpa) and use only Service layer for all needs.why is not possible in this case ?
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#1': Cannot resolve reference to bean 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0' while setting constructor argument with key [3]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0': Cannot resolve reference to bean 'org.springframework.security.authentication.ProviderManager#0' while setting bean property 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.ProviderManager#0': Cannot resolve reference to bean 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager': Cannot resolve reference to bean 'daoAuthenticationProvider' while setting constructor argument with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'daoAuthenticationProvider' defined in class path resource [spring/applicationContext/applicationContext-security.xml]: Cannot resolve reference to bean 'authService' while setting bean property 'userDetailsService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.dubovskiyM.mvc.service.User_service com.dubovskiyM.mvc.security.AuthServiceImpl.user_service; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.dubovskiyM.mvc.service.User_service] 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)}
userDetailsService
#Service
public class AuthServiceImpl implements UserDetailsService {
private final Logger log = LoggerFactory.getLogger(getClass());
#Autowired
User_service user_service;
#Transactional
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
log.trace("START-------------------------------------");
Signup details = user_service.findByLogin(username);
log.trace(details.getLogin()+"---------------------"+details.getPassword());
Collection<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
SimpleGrantedAuthority userAuthority = new SimpleGrantedAuthority(
"ROLE_USER");
SimpleGrantedAuthority adminAuthority = new SimpleGrantedAuthority(
"ROLE_ADMIN");
if (details.getRole() == 1)
authorities.add(userAuthority);
else if (details.getRole() == 2) {
authorities.add(userAuthority);
authorities.add(adminAuthority);
}
UserDetails user = new User(details.getLogin(),
details.getPassword(), true, true, true, true, authorities);
return user;
}
}
Security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="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.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http pattern="/resources/**" security="none" />
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/"
access="permitAll"/>
<intercept-url pattern="/login"
access="permitAll"/>
<intercept-url pattern="/logout"
access="permitAll"/>
<intercept-url pattern="/errors/**"
access="permitAll"/>
<intercept-url pattern="/com/dubovskiyM/mvc"
access="hasRole('ROLE_USER')"/>
<access-denied-handler error-page="/errors/403"/>
<form-login login-page="/login"
login-processing-url="/j_spring_security_check"
username-parameter="j_username"
password-parameter="j_password"
authentication-failure-url="/login/form?error"
default-target-url="/default"/>
</http>
<authentication-manager>
<authentication-provider ref="daoAuthenticationProvider">
</authentication-provider>
</authentication-manager>
<beans:bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="authService" />
<!--<beans:property name="passwordEncoder" ref="passwordEncoder" />-->
</beans:bean>
<beans:bean id="authService"
class="com.dubovskiyM.mvc.security.AuthServiceImpl" />
<!--<beans:bean id="passwordEncoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />-->
</beans:beans>
User_service
#Service
#Transactional
public class User_service {
#Autowired
private User_repository user_repository;
#Transactional(readOnly = false)
public void save(Signup signup){
user_repository.save(signup);
}
#Transactional(readOnly = true)
public Signup findByLogin(String login){
Signup signup = user_repository.findByLogin(login);
return signup;
}
#Transactional(readOnly = true)
public Signup findByLoginAndPassword(String login,String password){
Signup signup = user_repository.findByLoginAndPassword(login, password);
return signup;
}
}
Repository
#Repository
public interface User_repository extends JpaRepository<Signup,Long> {
Signup findByLogin(String login);
Signup findByLoginAndPassword(String login,String password);
}
servet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<!-- Scan for components under this package -->
<!-- Scan for components under this package expept Repository -->
<context:component-scan base-package="com.dubovskiyM.mvc">
<context:exclude-filter expression="org.springframework.stereotype.Repository" type="annotation"/>
</context:component-scan>
<!-- <!– Ensures that any resource requests not handled by Spring MVC mappings will be delegated back to the Servlet container –>
<mvc:default-servlet-handler />-->
<!--Enable jpa for repository access-->
</beans>

The problem is that spring have no knowledge of User_service bean.
User_service bean is not declared in your context configuration neither you enable a classpath scan of component annotated classes. (given your posted configurations)
Try to turn on component scan with the following xml declaration (possibly defining a stereotype attribute:
<context:component-scan base-package="your.package" />
or declare your bean in context configuration.
Hope this helps!

Related

Spring NotWritablePropertyException and Invalid property 'lazyInit' of bean JndiObjectFactoryBean

We are using WAS8.5 based JNDI data source configuration. While server start up, this datasource is not getting created. Hence throwing
org.springframework.beans.factory.BeanCreationException by saying "Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'lazyInit' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'lazyInit' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?"
We are not trying to set lazyInit property in our application. What could be the issue here? Is anything missed here?
Spring-context.xml:
<beans
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans">
<context:annotation-config/>
<jee:jndi-lookup id="ds_app1" jndi-name="java:comp/env/jdbc/ds_app1" />
<!-- SQL Session factories -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property ref="ds_app1" name="dataSource"/>
<property name="configLocation" value="classpath:/conf/xml/mybatis-config.xml" />
<property name="mapperLocations" value="classpath:/conf/xml/mapper/*.xml"/>
</bean>
</beans>
Same piece of code is working in another environment with same WAS8.5 server with same set of data source configurations. In our application, we are using spring4.3.8,mybatis3.x and java8. Here we are injecting datasource beans using xml configuration(dao-spring-context.xml)
Expected output would be data source should be injected to sql session factory bean.but actual result is getting the below exception.
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sqlSessionFactory' defined in class path resource [conf/xml/dao-spring-context.xml]: Cannot resolve reference to bean 'ds_app1' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ds_app1': Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'lazyInit' of bean class [org.springframework.jndi.JndiObjectFactoryBean]: Bean property 'lazyInit' is not writable or has an invalid setter method.
Does the parameter type of the setter match the return type of the getter?
This approach worked for me
1) Create a post processor
package org.test;
import org.springframework.bean.PropertyValue;
import org.springframework.bean.PropertyValues;
import org.springframework.bean.factory.config.InstantiationAwareBeanPostProcessorAdapter;
import java.beans.PropertyDescriptor;
#Component
public class CustomJndiInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {
#Override
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {
if (bean instanceOf org.springframeworkf.jndi.JndiObjectFactoryBean) {
for (PropertyValue pv: pvs.getPropertyValues()) {
if ("lazyInit".equals(pv.getName())) {
pv.setOptional(true);
}
}
}
}
}
2) Include this bean in your spring context xml
<bean id="customJndiInstantiationAwareBeanPostProcessor" class="org.test.CustomJndiInstantiationAwareBeanPostProcessor"/>

Unable to create mongotemplate in spring

Error:
19-Feb-2016 00:00:16.731 SEVERE [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.data.mongodb.core.MongoTemplate com.test.app.service.PersonService.mongoTemplate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.data.mongodb.core.MongoTemplate]: Constructor threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.core.convert.support.ConversionServiceFactory.createDefaultConversionService()Lorg/springframework/core/convert/support/GenericConversionService;
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.2.xsd">
<context:component-scan base-package="com.test.app" />
<mvc:annotation-driven/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- Factory bean that creates the Mongo instance -->
<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
<property name="host" value="localhost" />
</bean>
<!-- MongoTemplate for connecting and querying the documents in the database -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongo" ref="mongo" />
<constructor-arg name="databaseName" value="test" />
</bean>
<!-- Use this post processor to translate any MongoExceptions thrown in #Repository annotated classes -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="personController" class="com.test.app.controller.PersonController" />
<bean id="personService" class="com.test.app.service.PersonService" />
<bean id="person" class="com.test.app.model.Person" />
</beans>
I am seeing many posts regarding this error , but no answers to fix this.
The version of spring-core need match the version of spring-data.
Below is my part pom.xml:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<!-- Spring data mongodb -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.8.2.RELEASE</version>
</dependency>
It's fixed.
It's almost the same thing only annotation driven. In the Supplier I'm just casting mongoTemplate (You may not want that). So If you use the spring config everything should work fine.
Regarding your version in XML try creating the mongo factory from SimpleMongoDbFactory with a MongoClient and the database name, Then just give your MongoTemplate bean your factory, and that's it.
Spring Config:
#Configuration
public class SpringConfig {
#Bean
public MongoDbFactory mongoDbFactory() throws UnknownHostException{
return new SimpleMongoDbFactory(new MongoClient(),"games");
}
#Bean
public MongoTemplate mongoTemplate() throws UnknownHostException{
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
return mongoTemplate;
}
}
After that I created a supplier (Google Guava in this case) which may not be needed in your case
public class MongoOperationSupplier implements Supplier<MongoOperations>{
#Override
public MongoOperations get() {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
return mongoOperation;
}
}
An annotated class:
#Document(collection="game_suspicious_event")
public class SuspiciousEvent {
#Id
private String id;
private String apiKey;
private String userUniqueId;
private Date date;
private String ip;
private String additionalInformation;
public SuspiciousEvent(){}
public SuspiciousEvent(String apiKey,String userUniqueId,Date date, String ip, String additionalInformation){
this.apiKey=apiKey;
this.userUniqueId=userUniqueId;
this.date=date;
this.ip=ip;
this.additionalInformation=additionalInformation;
}
public String getApiKey() {
return apiKey;
}
}
Then to use:
final MongoOperations mo = new MongoOperationSupplier().get();
mo.save(new SuspiciousEvent(......));
Hope it helps.

Facing issues while implementing Spring Security with http-basic authentication for spring rest API

Hi i am new to spring security and trying to implement it in my project.
I am trying to use UserDetailsService of spring security to achieve the security.
well i have configured every thing from web.xml to spring-security.xml
i am facing an compilation issue while autowiring the DAO class in the class that implements UserDetailsService. If i do not autowire then the code is compiling successfully and when i am testing the code from postman i am getting an error as follow's
12:13:45.738 [http-nio-8080-exec-3] DEBUG o.s.s.a.DefaultAuthenticationEventPublisher - No event was found for the exception org.springframework.security.authentication.InternalAuthenticationServiceException
12:13:45.738 [http-nio-8080-exec-3] DEBUG o.s.s.w.a.w.BasicAuthenticationFilter - Authentication request for failed: org.springframework.security.authentication.InternalAuthenticationServiceException
and below is my web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/root-context.xml
classpath:spring-security.xml
</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
and my spring-security.xml files contains
<?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:security="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.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-4.1.xsd">
<context:annotation-config/>
<bean id="authenticationEntryPoint" class="user.app.security.DemoAppEntryPoint">
<constructor-arg name="loginFormUrl" value="/auth/login"/>
</bean>
<security:http use-expressions="true" create-session="stateless" entry-point-ref="authenticationEntryPoint" >
<security:intercept-url pattern="/auth/login" access="hasAnyRole('UserAppAdmin','HR','manager')" />
<security:intercept-url pattern='/user/**' access="hasAnyRole('UserAppAdmin','HR','manager')"/>
<security:http-basic />
<security:csrf disabled="true"/>
</security:http>
<bean id="userappAuthenticationProvider" class="user.app.security.UserappAuthenticationProvider" />
<security:authentication-manager>
<security:authentication-provider user-service-ref="userappAuthenticationProvider">
</security:authentication-provider>
</security:authentication-manager>
</beans>
my UserappAuthenticationProvider class
public class UserappAuthenticationProvider implements UserDetailsService{
// Is it neccessary to autowire this object
// And this is causing problem when i am trying to autowire it's giving compilation error
private FarmerDAO farmerdao;
#Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
UserLogin farmer = farmerdao.getUserByLogin(userName);
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
UserApp principal = null;
principal = new UserApp(authorities,farmer.getUserId(), farmer.getUserName(), farmer.getRtn(), farmer);
String role=farmer.getRole();
System.out.println(farmer);
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return principal;
}
}
The compilation error is as follow if autowire:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [user.app.service.FarmerDAO] 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)}
And one thing when i am testing from postman and debugging the application.
the request comes till the line
FarmerLogin farmer = farmerService.getUserByLogin(userName);
of UserappAuthenticationProvider class and throws the error as show at the beginning of the post.
Please suggest me if i am missing some part so, that i can successfully authenticate the user.
In the code you've provided here, there is no sign of defining the farmerdao bean in the xmls, and the userappAuthenticationProvider does not have any setter for it and its bean did not set the property to it. so I think this is your problem.
In my experience, it is better to use one mode, xml or annotation. and I prefer xml.
the result will be like this :
<bean id="farmerdao" class="user.app.security.FarmerDaoImpl">
<!-- set the required attributes to connect your dao to the DB -->
<bean>
<bean id="userappAuthenticationProvider" class="user.app.security.UserappAuthenticationProvider">
<property name="farmerdao" ref="farmerdao"/>
</bean>
and of course you need to define a setter for farmerdao in your UserappAuthenticationProvider.

spring integration-mqtt type converter issue

Trying to run the sample spring-integration mqtt project from web.
I have imported the mqtt-context in root context. After the war is deployed I am running the RunMqtt.java file. But getting the following issue. If running in standalone mode , the same file does not give any issue.
Stack Trace
Creating instance of bean 'startCaseAdapter'
16:50:54.147 DEBUG [main][org.springframework.beans.BeanUtils] No property editor [org.springframework.integration.mqtt.core.MqttPahoClientFactoryEditor] found for type org.springframework.integration.mqtt.core.MqttPahoClientFactory according to 'Editor' suffix convention
16:50:54.148 TRACE [main][org.springframework.beans.TypeConverterDelegate] Field [topic] isn't an enum value
java.lang.NoSuchFieldException: topic
at java.lang.Class.getField(Class.java:1579)
at org.springframework.beans.TypeConverterDelegate.attemptToConvertStringToEnum(TypeConverterDelegate.java:336)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:257)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:107)
at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:64)
at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:47)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:706)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1133)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1036)
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.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.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.iux.ieg.test.mqtt.RunMqtt.test(RunMqtt.java:24)
at com.iux.ieg.test.mqtt.RunMqtt.main(RunMqtt.java:46)
16:50:54.150 TRACE [main][org.springframework.beans.factory.support.DefaultListableBeanFactory] Ignoring constructor [public org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter(java.lang.String,java.lang.String,org.springframework.integration.mqtt.core.MqttPahoClientFactory,java.lang.String[])] of bean 'startCaseAdapter': org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'startCaseAdapter': Unsatisfied dependency expressed through constructor argument with index 2 of type [org.springframework.integration.mqtt.core.MqttPahoClientFactory]: Could not convert constructor argument value of type [java.lang.String] to required type [org.springframework.integration.mqtt.core.MqttPahoClientFactory]: Failed to convert value of type 'java.lang.String' to required type 'org.springframework.integration.mqtt.core.MqttPahoClientFactory'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.springframework.integration.mqtt.core.MqttPahoClientFactory]: no matching editors or conversion strategy found
16:50:54.150 TRACE [main][org.springframework.beans.TypeConverterDelegate] Converting String to [class [Ljava.lang.String;] using property editor [org.springframework.beans.propertyeditors.StringArrayPropertyEditor#821075]
16:50:54.150 TRACE [main][org.springframework.beans.TypeConverterDelegate] Field [clientId] isn't an enum value
java.lang.NoSuchFieldException: clientId
at java.lang.Class.getField(Class.java:1579)
at org.springframework.beans.TypeConverterDelegate.attemptToConvertStringToEnum(TypeConverterDelegate.java:336)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:257)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:107)
at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:64)
at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:47)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:706)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1133)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1036)
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.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.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.iux.ieg.test.mqtt.RunMqtt.test(RunMqtt.java:24)
at com.iux.ieg.test.mqtt.RunMqtt.main(RunMqtt.java:46)
Configuration
Web-application-config.xml
<?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"
xsi:schemaLocation="
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">
<!-- This file will be the root context file for web app. All other context
will be imported here -->
<!-- Security context . Now the spring security with basic authentication
implemented. OAuth2 will be implemented -->
<import resource="security-config.xml" />
<!-- rest service call context -->
<import
resource="classpath:META-INF/spring/integration/rest/applicationContext-http-int.xml" />
<!-- Sftp context -->
<import
resource="classpath:META-INF/spring/integration/sftp/SftpInboundReceive-context.xml" />
<import
resource="classpath:META-INF/spring/integration/sftp/SftpOutboundTransfer-poll.xml" />
<!-- mqtt context -->
<import resource="classpath:META-INF/spring/integration/mqtt/mqtt-context.xml" />
<!-- Mail Context -->
<import
resource="classpath:META-INF/spring/integration/mail/mail-imap-idle-config.xml" />
<import
resource="classpath:META-INF/spring/integration/mail/mail-pop3-config.xml" />
<!--Component scan base package -->
<context:component-scan base-package="com.iux.ieg" />
<!-- All the property configuration moved to parent context file to solve
the propert not found exception -->
<!-- <context:property-placeholder order="1" location="classpath:/sftpuser.properties,
classpath:/sftpfile.properties,classpath:/resthttp.properties" ignore-unresolvable="true"/> -->
<context:property-placeholder order="0"
location="classpath:/sftpfile.properties" ignore-unresolvable="true" />
<context:property-placeholder order="1"
location="classpath:/sftpuser.properties" ignore-unresolvable="true" />
<context:property-placeholder order="2"
location="classpath:/resthttp.properties" ignore-unresolvable="true" />
<context:property-placeholder order="3"
location="classpath:/mqtt.properties" ignore-unresolvable="true" />
<context:property-placeholder order="4"
location="classpath:/mail.properties" />
</beans>
mqtt-context.xml
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/integration/mqtt http://www.springframework.org/schema/integration/mqtt/spring-integration-mqtt-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:property-placeholder
location="classpath:/mqtt.properties" ignore-unresolvable="true" />
<!-- intercept and log every message -->
<int:logging-channel-adapter id="logger"
level="ERROR" />
<int:wire-tap channel="logger" />
<!-- Mark the auto-startup="true" for starting MqttPahoMessageDrivenChannelAdapter from configuration -->
<int-mqtt:message-driven-channel-adapter
id="startCaseAdapter" client-id="clientId" url="${mqtt.brokerurl}"
topics="topic" channel="startCase" auto-startup="true" />
<int:channel id="startCase" />
<int:service-activator id="startCaseService"
input-channel="startCase" ref="mqttCaseService" method="startCase" />
<bean id="mqttCaseService" class="com.iux.ieg.mqtt.MqttCaseService" />
MqttCaseService.java
import org.apache.log4j.Logger;
public class MqttCaseService {
private static Logger logger = Logger.getLogger(MqttCaseService.class);
public void startCase(String message){
logger.debug(message);
}
}
RunMqtt.java
public class RunMqtt {
private static Logger logger = Logger.getLogger(RunMqtt.class);
//#Test
public void test() throws MqttException{
ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext("/META-INF/spring/integration/mqtt/mqtt-context.xml");
logger.debug(context);
//MqttPahoMessageDrivenChannelAdapter startCaseAdapter = (MqttPahoMessageDrivenChannelAdapter)context.getBean("startCaseAdapter");
//Uncomment to stop the adapter manually from program
//startCaseAdapter.start();
//DefaultMqttPahoClientFactory mqttClient = (DefaultMqttPahoClientFactory)ac.getBean("clientFactory");
DefaultMqttPahoClientFactory mqttClient = new DefaultMqttPahoClientFactory();
MqttClient mclient = mqttClient.getClientInstance("tcp://*messagebrokerurl*:1883", "JavaSample");
String data = "This is what I am sending in 2nd attempt";
MqttMessage mm = new MqttMessage(data.getBytes());
mm.setQos(1);
mclient.connect();
mclient.publish("topic",mm);
mclient.disconnect();
//Uncomment to stop the adapter manually from program
//startCaseAdapter.stop();
}
public static void main(String[] args) {
try {
new RunMqtt().test();
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
the sample spring-integration mqtt project
Which sample?
Please show your configuration.
EDIT:
It looks like Spring is having trouble determining which constructor to use.
Try adding
<bean id="clientFactory" class="org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory" />
and add client-factory="clientFactory" to the message-driven adapter.

Cannot create inner bean 'org.szymon.email.classes.MyMapperClass

I have exception type: org.springframework.beans.factory.BeanCreationException
full stack:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.view.ContentNegotiatingViewResolver#0' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Cannot create inner bean 'org.szymon.email.classes.MyMapperClass#1e222db' of type [org.szymon.email.classes.MyMapperClass] while setting bean property 'defaultViews' with key [1]; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.szymon.email.classes.MyMapperClass] for bean with name 'org.szymon.email.classes.MyMapperClass#1e222db' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.szymon.email.classes.MyMapperClass
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:282)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:121)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1417)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1158)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
my dispatcher-servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<context:component-scan base-package="org.szymon.email.*" />
<tx:annotation-driven />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="favorPathExtension" value="true"/>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json"/>
<entry key="jsonp" value="application/javascript"/>
</map>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
<bean class="org.szymon.email.classes.MyMapperClass"/>
</list>
</property>
</bean>
</beans>
and my MyMapperClass:
package org.szymon.email.classes;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;
public class MyMapperClass extends MappingJacksonJsonView {
/**
* Default content type. Overridable as bean property.
*/
public static final String DEFAULT_CONTENT_TYPE = "application/javascript";
#Override
public String getContentType() {
return DEFAULT_CONTENT_TYPE;
}
/**
* Prepares the view given the specified model, merging it with static
* attributes and a RequestContext attribute, if necessary.
* Delegates to renderMergedOutputModel for the actual rendering.
* #see #renderMergedOutputModel
*/
#Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
if("GET".equals(request.getMethod().toUpperCase())) {
#SuppressWarnings("unchecked")
Map<String, String[]> params = request.getParameterMap();
if(params.containsKey("callback")) {
response.getOutputStream().write(new String(params.get("callback")[0] + "(").getBytes());
super.render(model, request, response);
response.getOutputStream().write(new String(");").getBytes());
response.setContentType("application/javascript");
}
else {
super.render(model, request, response);
}
}
else {
super.render(model, request, response);
}
}
}
This is continuation of solving problem from question:
Spring RESTful ajax gets error
There is one more interesting thing.
When I put comment on this bean like this:
<!-- <bean class="org.szymon.email.classes.MyMapperClass"/> -->
And create instance of this class in method on my controller and invoke render method of it, then everything is fine... but it is not proper solution.
Please help.
Cheers
The problem seems to be a build - IDE related. I was able to run the project both from IntellIJ IDEA and also by executing then Maven build and placing the produced war in webapps directory of Tomcat.
I suggest you do a Maven clean-compile-package and try again

Resources