Camel Bindy not able to marshal POJO into CSV - java

I'm trying to marshal a POJO into a CSV using camel-bindy, using the following setup:
<bean id="bindyDataFormat" class="org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat">
<constructor-arg value="com.foo.kod.domain" />
<camel:route>
<camel:from uri="ref:kod.handler.list.in.csv" />
<camel:choice>
<camel:when>
<camel:xpath>$Accept = 'application/json' </camel:xpath>
<camel:to uri="bean:handlerListProcessor?method=process" />
<camel:marshal ref="myJSON" />
</camel:when>
<camel:when>
<camel:xpath>$Accept = 'text/csv' </camel:xpath>
<camel:to uri="bean:handlerListProcessor?method=process" />
<camel:marshal ref="bindyDataformat">
<camel:bindy type="Csv" packages="com.foo.kod.domain"/>
</camel:marshal>
</camel:when>
<camel:otherwise>
<camel:to uri="bean:handlerListProcessor?method=process" />
<camel:marshal ref="myJSON" />
</camel:otherwise>
</camel:choice>
</camel:route>
But this throws a ClassCastException each time:
java.lang.ClassCastException: com.foo.kod.domain.Handler cannot be cast to java.util.Map
at org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat.marshal(BindyCsvDataFormat.java:93)
at org.apache.camel.processor.MarshalProcessor.process(MarshalProcessor.java:58)
at org.apache.camel.impl.converter.AsyncProcessorTypeConverter$ProcessorToAsyncProcessorBridge.process(AsyncProcessorTypeConverter.java:50)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:78)
at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:98)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:89)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:69)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:78)
at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:98)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:89)
at org.apache.camel.processor.interceptor.TraceInterceptor.process(TraceInterceptor.java:99)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:78)
at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:98)
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:89)
at org.apache.camel.fabric.FabricTraceProcessor.process(FabricTraceProcessor.java:81)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:78)

Related

redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool

redis.properties
#jedisPoolConfig
redis.minIdle=100
redis.maxIdle=500
redis.maxTotal=50000
redis.maxWaitMillis=10000
redis.testOnBorrow=true
#jedisPool
redis.host=192.168.13.169
redis.port=6379
redis.timeout=3000
redis.port2=6380
#redis-sentinel
redis.sentinel=192.168.13.169:26379
redis.master=mymaster
spring-redis.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--properties配置-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:redis.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
<!-- 连接池配置信息 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxTotal" value="${redis.maxTotal}" />
<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<!--初级版:单实例-->
<bean id="jedisPool" class="redis.clients.jedis.JedisPool" scope="singleton">
<constructor-arg name="poolConfig" ref="jedisPoolConfig" />
<constructor-arg name="host" value="${redis.host}" />
<constructor-arg name="port" value="${redis.port}" type="int" />
</bean>
<!--主从-->
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg name="host" value="${redis.host}" />
<constructor-arg name="port" value="${redis.port}" />
<constructor-arg name="timeout" value="${redis.timeout}" />
<constructor-arg name="name" value="master" />
</bean>
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg name="host" value="${redis.host}" />
<constructor-arg name="port" value="${redis.port2}" />
<constructor-arg name="timeout" value="${redis.timeout}" />
<constructor-arg name="name" value="slave1" />
</bean>
</list>
</constructor-arg>
</bean>
<!--sentinel模式-->
<bean id="redisSentinelConfiguration" class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
<constructor-arg name="master" value="${redis.master}" />
<constructor-arg name="sentinelHostAndPorts">
<set>
<value>${redis.sentinel}</value>
</set>
</constructor-arg>
</bean>
<!--Jedis连接池-->
<bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:use-pool="true">
<property name="hostName" value="${redis.host}"/>
<constructor-arg ref="redisSentinelConfiguration" />
<constructor-arg ref="jedisPoolConfig" />
</bean>
<!-- redis template definition -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate" p:connection-factory-ref="jedisConnFactory"/>
<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
Code
Controller
#Controller
public class JedisController {
......
#Autowired
private RedisService redisService;
#RequestMapping(value = "test2")
#ResponseBody
public String test2(){
redisService.set("key2","v2");
return redisService.get("key1");
}
......
}
Service
#Service
public class RedisService extends BinaryRedisService {
public RedisService() {}
public String set(final String key, final String value) {
return (String)this.execute(new Function<ShardedJedis, String>() {
public String callBack(ShardedJedis shardedJedis) {
return shardedJedis.set(key, value);
}
});
}
......
}
public class BinaryRedisService {
#Autowired
protected ShardedJedisPool shardedJedisPool;
public BinaryRedisService() {
}
protected <T> T execute(Function<ShardedJedis, T> fun) {
ShardedJedis shardedJedis = null;
T t = null;
try {
shardedJedis = this.shardedJedisPool.getResource();
t = fun.callBack(shardedJedis);
} catch (Exception var8) {
var8.printStackTrace();
} finally {
if(null != shardedJedis) {
shardedJedis.close();
}
return t;
}
}
......
}
Problem
redis.clients.jedis.exceptions.JedisException: Could not get a
resource from the pool at
redis.clients.util.Pool.getResource(Pool.java:51) at
redis.clients.jedis.ShardedJedisPool.getResource(ShardedJedisPool.java:36)
at
org.henry.service.BinaryRedisService.execute(BinaryRedisService.java:29)
at org.henry.service.RedisService.set(RedisService.java:25) at
org.henry.service.RedisService$$FastClassBySpringCGLIB$$f57afd3.invoke()
at
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
at
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656)
at
org.henry.service.RedisService$$EnhancerBySpringCGLIB$$d4e52321.set()
at
org.henry.controller.JedisController.test2(JedisController.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) at
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at
org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:837)
at
org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:583)
at
org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at
org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
at
org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
at
org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)
at
org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
at
org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at
org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)
at
org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at
org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213)
at
org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:119)
at
org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
at org.eclipse.jetty.server.Server.handle(Server.java:524) at
org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:319) at
org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:253)
at
org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
at
org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
at
org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
at
org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
at
org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
at
org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
at
org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
at java.lang.Thread.run(Thread.java:745) Caused by:
java.util.NoSuchElementException: Unable to validate object at
org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:506)
at
org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363)
at redis.clients.util.Pool.getResource(Pool.java:49) ... 58 more
You need to make sure that a) Redis is running b) that it is able to accept connections from remote hosts and c) if you have enabled password protection, provide a password in your code.
To make sure that it can accept connections from remote hosts you have to look at the redis.conf file. Find the line with the binding addresses (it should look something like: bind 127.0.0.1) and either comment it out (so it can accept requests from all remote hosts - not recommended for production, but it's OK for testing), or add the remote IPs you want your Redis service to accept connections from.

Spring security with oauth2 adding additional parameters to authorization URL?

I have implemented Spring Security in my restful web service. In fact, I have to add an extra parameter with the request from client side and should fetch it from the service when request for authentication/accesstoken.
spring-security.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:oauth="http://www.springframework.org/schema/security/oauth2"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:sec="http://www.springframework.org/schema/security" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
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 ">
<!-- #author Nagesh.Chauhan(neel4soft#gmail.com) -->
<!-- This is default url to get a token from OAuth -->
<http pattern="/oauth/token" create-session="stateless"
authentication-manager-ref="clientAuthenticationManager"
xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
<anonymous enabled="false" />
<http-basic entry-point-ref="clientAuthenticationEntryPoint" />
<!-- include this only if you need to authenticate clients via request
parameters -->
<custom-filter ref="clientCredentialsTokenEndpointFilter"
after="BASIC_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>
<!-- This is where we tells spring security what URL should be protected
and what roles have access to them -->
<http pattern="/api/**" create-session="never"
entry-point-ref="oauthAuthenticationEntryPoint"
access-decision-manager-ref="accessDecisionManager"
xmlns="http://www.springframework.org/schema/security">
<anonymous enabled="false" />
<intercept-url pattern="/api/**" access="ROLE_APP" />
<custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>
<bean id="oauthAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="test" />
</bean>
<bean id="clientAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="test/client" />
<property name="typeName" value="Basic" />
</bean>
<bean id="oauthAccessDeniedHandler"
class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />
<bean id="clientCredentialsTokenEndpointFilter"
class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
<property name="authenticationManager" ref="clientAuthenticationManager" />
</bean>
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
xmlns="http://www.springframework.org/schema/beans">
<constructor-arg>
<list>
<bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
<bean class="org.springframework.security.access.vote.RoleVoter" />
<bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
</list>
</constructor-arg>
</bean>
<authentication-manager id="clientAuthenticationManager"
xmlns="http://www.springframework.org/schema/security">
<authentication-provider user-service-ref="clientDetailsUserService" />
</authentication-manager>
<!-- Custom User details service which is provide the user data -->
<bean id="customUserDetailsService"
class="com.weekenter.www.service.impl.CustomUserDetailsService" />
<authentication-manager alias="authenticationManager"
xmlns="http://www.springframework.org/schema/security">
<authentication-provider user-service-ref="customUserDetailsService">
<password-encoder hash="plaintext">
</password-encoder>
</authentication-provider>
</authentication-manager>
<bean id="clientDetailsUserService"
class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
<constructor-arg ref="clientDetails" />
</bean>
<!-- This defined token store, we have used inmemory tokenstore for now
but this can be changed to a user defined one -->
<bean id="tokenStore"
class="org.springframework.security.oauth2.provider.token.InMemoryTokenStore" />
<!-- This is where we defined token based configurations, token validity
and other things -->
<bean id="tokenServices"
class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
<property name="tokenStore" ref="tokenStore" />
<property name="supportRefreshToken" value="true" />
<property name="accessTokenValiditySeconds" value="120" />
<property name="clientDetailsService" ref="clientDetails" />
</bean>
<bean id="userApprovalHandler"
class="org.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandler">
<property name="tokenServices" ref="tokenServices" />
</bean>
<oauth:authorization-server
client-details-service-ref="clientDetails" token-services-ref="tokenServices"
user-approval-handler-ref="userApprovalHandler">
<oauth:authorization-code />
<oauth:implicit />
<oauth:refresh-token />
<oauth:client-credentials />
<oauth:password />
</oauth:authorization-server>
<oauth:resource-server id="resourceServerFilter"
resource-id="test" token-services-ref="tokenServices" />
<oauth:client-details-service id="clientDetails">
<!-- client -->
<oauth:client client-id="restapp"
authorized-grant-types="authorization_code,client_credentials"
authorities="ROLE_APP" scope="read,write,trust" secret="secret" />
<oauth:client client-id="restapp"
authorized-grant-types="password,authorization_code,refresh_token,implicit"
secret="restapp" authorities="ROLE_APP" />
</oauth:client-details-service>
<sec:global-method-security
pre-post-annotations="enabled" proxy-target-class="true">
<!--you could also wire in the expression handler up at the layer of the
http filters. See https://jira.springsource.org/browse/SEC-1452 -->
<sec:expression-handler ref="oauthExpressionHandler" />
</sec:global-method-security>
<oauth:expression-handler id="oauthExpressionHandler" />
<oauth:web-expression-handler id="oauthWebExpressionHandler" />
</beans>
CustomUserDetailsService
#Service
#Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private LoginDao loginDao;
public UserDetails loadUserByUsername(String login)
throws UsernameNotFoundException {
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
com.weekenter.www.entity.User user = null;
try {
user = loginDao.getUser(login);
if (user != null) {
if (user.getStatus().equals("1")) {
enabled = false;
}
} else {
throw new UsernameNotFoundException(login + " Not found !");
}
} catch (Exception ex) {
try {
throw new Exception(ex.getMessage());
} catch (Exception ex1) {
}
}
return new User(
user.getEmail(),
user.getPassword(),
enabled,
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
getAuthorities()
);
}
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles());
return authList;
}
public List<String> getRoles() {
List<String> roles = new ArrayList<String>();
roles.add("ROLE_APP");
return roles;
}
public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
}
Currently I am requesting with the URL:
http://localhost:8084/Domain/oauth/token?grant_type=password&client_id=restapp&client_secret=restapp&username=anoo#codelynks.com&password=mypass
And I will get the response
{
"access_token":"76e928b2-45e2-4283-88a4-6c01f41b51d3","token_type":"bearer","refresh_token":"8748e8ad-79c1-465d-94fe-13394eea370d","expires_in":119
}
I have to enhance it by adding additional parameter deviceToken.
And the URL would be:
http://localhost:8084/Domain/oauth/token?grant_type=password&client_id=restapp&client_secret=restapp&username=anoo#codelynks.com&password=mypass&deviceToken=something
I have treid by implementing UsernamePasswordAuthenticationFilter, but it didn't work. How can I get the deviceToken parameter from the web service without affecting the output?
http://localhost:8084/Domain/oauth/token?grant_type=password&client_id=restapp&client_secret=restapp&username=anoo#codelynks.com&password=mypass&additional_param=abc123
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
log.info("additional_param: " + request.getParameter("additional_param"));
log will show
additional_param: abc123
Although AOP is used when it comes to crosscutting concerns, this approach worked as expected and I think It is a valid approach.
#Aspect
public class Oauth2Aspect {
#AfterReturning("execution( * org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
public void executeAfterAuthentication() throws Exception {
System.out.println(":Authentication done");
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
System.out.println(":Authentication done " + request.getParameter("deviceInfo"));
}
}

Spring MVC: ModelAndViewContainer: View is [null]; default model{Some-Object}

I am using Spring-mvc with ContentNegotiatingViewResolver for handle my response objects and parse into a specific format. When i return the object from controller, in response it add my response object but also add the object which i used to map the request parameter. My controller is act as rest controller. Because i want to create rest-services using spring with ContentNegotiatingViewResolver. After debugging, i found InvocableHandlerMethdod class in which invokeForRequest method contain following argument:
public final Object invokeForRequest(NativeWebRequest request, ModelAndViewContainer mavContainer,
Object... providedArgs) throws Exception {
...............................................
In ModelAndViewContainer argument contain following detail:
ModelAndViewContainer: View is [null]; default model {oauthClientDetail=com.netsol.entities.OauthClientDetail#9ac35e, org.springframework.validation.BindingResult.oauthClientDetail=org.springframework.validation.BeanPropertyBindingResult: 0 errors}
I am not able to figure, why OauthClientDetail object set in ModelAndViewContainer and how i prevent this.
Follwing is my controller code:
#RequestMapping(value = "/changePassword", method = RequestMethod.POST)
public ApiResponse<UserDetail> changePassword(#Valid OauthClientDetail clientDetail,
BindingResult bindingResult,
#RequestParam(value = "password", required = true) String password) {
logger.info("In changePassword Service...... ");
if(bindingResult.hasErrors()){
throw new InvalidRequestException("Error", bindingResult);
}
UserDetail detail = userService.changeUserPassword(password, clientDetail, encoder);
ApiResponse<UserDetail> response = new ApiResponse<UserDetail>();
if(detail != null){
response.setErrorCode(CommonUtility.API_RESPONSE_STATUS.SUCCESS.getValue());
response.setErrorMessage(CommonUtility.API_RESPONSE_STATUS.SUCCESS.getMessage());
response.setResponse(detail);
}else{
response.setErrorCode(CommonUtility.API_RESPONSE_STATUS.FAIL.getValue());
response.setErrorMessage(CommonUtility.API_RESPONSE_STATUS.FAIL.getMessage());
response.setResponse(null);
}
return response;
}
rest-servlet.xml configuration:
bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false" />
<property name="favorParameter" value="true" />
<property name="parameterName" value="mediaType" />
<property name="ignoreAcceptHeader" value="true" />
<property name="useJaf" value="false" />
<property name="defaultContentType" value="application/json" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="contentNegotiationManager" ref="contentNegotiationManager" />
<property name="order" value="1" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
<entry key="html" value="text/html" />
</map>
</property>
<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="autodetectAnnotations" value="true" />
<property name="aliases">
<map>
<entry key="list" value="java.util.List" />
<entry key="string" value="java.lang.String" />
<entry key="hsahmap" value="java.util.HashMap" />
<entry key="object" value="java.lang.Object" />
<entry key="hashSet" value="java.util.HashSet" />
</map>
</property>
<property name="supportedClasses">
<list>
<value>java.util.List</value>
<value>java.lang.String</value>
<value>java.util.Map</value>
<value>java.lang.Object</value>
<value>java.util.Set</value>
<value>java.lang.Long</value>
<value>java.util.Date</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>
</list>
</property>
<property name="defaultContentType" ref="htmlMediaType" />
<property name="ignoreAcceptHeader" value="true" />
</bean>
<bean id="htmlMediaType" class="org.springframework.http.MediaType">
<constructor-arg value="text" />
<constructor-arg value="html" />
</bean>
My request from chrome postman client:
POST /empirecl-api/api/changePassword HTTP/1.1
Host: localhost:8080
Authorization: Bearer b3f46274-b019-4d7b-a3bd-5c19e9660c2f
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
clientId=my-client-with-secret&clientSecret=12345678&clientSecretConfirm=12345678&password=12345678
My Response is:
{
"oauthClientDetail": {
"userId": null,
"clientId": "my-client-with-secret",
"additionalInformation": null,
"authorities": null,
"authorizedGrantTypes": null,
"autoapprove": null,
"clientSecret": "12345678",
"clientSecretConfirm": "12345678",
"resourceIds": null,
"scope": null,
"webServerRedirectUri": null,
"createdOn": null,
"updatedOn": null,
"active": null,
"lastLogin": null
},
"apiResponse": {
"errorCode": 0,
"errorMessage": "Success",
"response": {
"userName": "my-client-with-secret",
"dateCreated": null,
"dateUpdated": null,
"active": "true"
}
}
}
In response the oauthClientDetail object contain values that, i send with request and map into the object. From this, i assume that, my map object is set in the response. How i prevent this object to set in the response.
I found the Solution from this MappingJacksonJsonView return top-level json object link. Need to add #ResponseBody annotation in controller and set produces={"application/json"}. Follwoing is my new code:
#RequestMapping(value = "/changePassword", method = RequestMethod.POST, produces={"application/json"})
public #ResponseBody ApiResponse<UserDetail> changePassword(#Valid OauthClientDetail clientDetail,
BindingResult bindingResult,
#RequestParam(value = "password", required = true) String password) {
logger.info("In changePassword Service...... ");
if(bindingResult.hasErrors()){
throw new InvalidRequestException("Error", bindingResult);
}
UserDetail detail = userService.changeUserPassword(password, clientDetail, encoder);
ApiResponse<UserDetail> response = new ApiResponse<UserDetail>();
if(detail != null){
response.setSuccess(CommonUtility.API_RESPONSE_STATUS.SUCCESS.getValue());
response.setMessage(CommonUtility.API_RESPONSE_STATUS.SUCCESS.getMessage());
response.setResponse(detail);
}else{
response.setSuccess(CommonUtility.API_RESPONSE_STATUS.FAIL.getValue());
response.setMessage(CommonUtility.API_RESPONSE_STATUS.FAIL.getMessage());
response.setResponse(null);
}
return response;
}

Spring batch integration

I am looking for a guidance/solution with Spring batch integration. I have a directory to which external application will send xml files. My application should read the file content and move the file to another directory.
The application should be able to process the files in parallel.
Thanks in advance.
You can use Spring Integration ftp / sftp combined with Spring Batch:
1.Spring Integration Ftp Configuration :
<bean id="ftpClientFactory"
class="org.springframework.integration.ftp.session.DefaultFtpSessionFactory">
<property name="host" value="${host.name}" />
<property name="port" value="${host.port}" />
<property name="username" value="${host.username}" />
<property name="password" value="${host.password}" />
<property name="bufferSize" value="100000"/>
</bean>
<int:channel id="ftpChannel" />
<int-ftp:outbound-channel-adapter id="ftpOutbound"
channel="ftpChannel" remote-directory="/yourremotedirectory/" session-factory="ftpClientFactory" use-temporary-file-name="false" />
2.Create your reader and autowire a service to provide your items if needed :
#Scope("step")
public class MajorItemReader implements InitializingBean{
private List<YourItem> yourItems= null;
#Autowired
private MyService provider;
public YourItem read() {
if ((yourItems!= null) && (yourItems.size() != 0)) {
return yourItems.remove(0);
}
return null;
}
//Reading Items from Service
private void reloadItems() {
this.yourItems= new ArrayList<YourItem>();
// use the service to provide your Items
if (yourItems.isEmpty()) {
yourItems= null;
}
}
public MyService getProvider() {
return provider;
}
public void setProvider(MyService provider) {
this.provider = provider;
}
#Override
public void afterPropertiesSet() throws Exception {
reloadItems();
}
}
3. Create Your Own Item Processor
public class MyProcessor implements
ItemProcessor<YourItem, YourItem> {
#Override
public YourItem process(YourItem arg0) throws Exception {
// Apply any logic to your Item before transferring it to the writer
return arg0;
}
}
4. Create Your Own Writer :
public class MyWriter{
#Autowired
#Qualifier("ftpChannel")
private MessageChannel messageChannel;
public void write(YourItem pack) throws IOException {
//create your file and from your Item
File file = new File("the_created_file");
// Sending the file via Spring Integration Ftp Channel
Message<File> message = MessageBuilder.withPayload(file).build();
messageChannel.send(message);
}
5.Batch Configuration :
<bean id="dataSourcee"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="" />
<property name="url" value="" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
<property name="dataSource" ref="dataSourcee" />
<property name="transactionManager" ref="transactionManagerrr" />
<property name="databaseType" value="" />
</bean>
<bean id="transactionManagerrr"
class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>
6.Another ApplicationContext file to Configure Your Job :
<context:annotation-config />
<bean id="provider" class="mypackage.MyService" />
<context:component-scan base-package="mypackage" />
<bean id="myReader" class="mypackage.MyReader"
<property name="provider" ref="provider" />
</bean>
<bean id="myWriter" class="mypackage.MyWriter" />
<bean id="myProcessor" class="mypackage.MyProcessor" />
<bean id="mReader"
class="org.springframework.batch.item.adapter.ItemReaderAdapter">
<property name="targetObject" ref="myReader" />
<property name="targetMethod" value="read" />
</bean>
<bean id="mProcessor"
class="org.springframework.batch.item.adapter.ItemProcessorAdapter">
<property name="targetObject" ref="myProcessor" />
<property name="targetMethod" value="process" />
</bean>
<bean id="mWriter"
class="org.springframework.batch.item.adapter.ItemWriterAdapter">
<property name="targetObject" ref="myWriter" />
<property name="targetMethod" value="write" />
</bean>
<batch:job id="myJob">
<batch:step id="step01">
<batch:tasklet>
<batch:chunk reader="mReader" writer="mWriter"
processor="mProcessor" commit-interval="1">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="myRunScheduler" class="mypackage.MyJobLauncher" />
<task:scheduled-tasks>
<task:scheduled ref="myJobLauncher" method="run"
cron="0 0/5 * * * ?" />
<!-- this will maker the job runs every 5 minutes -->
</task:scheduled-tasks>
7.Finally Configure A launcher to launch your job :
public class MyJobLauncher {
#Autowired
private JobLauncher jobLauncher;
#Autowired
#Qualifier("myJob")
private Job job;
public void run() {
try {
String dateParam = new Date().toString();
JobParameters param = new JobParametersBuilder().addString("date",
dateParam).toJobParameters();
JobExecution execution = jobLauncher.run(job, param);
execution.stop();
} catch (Exception e) {
e.printStackTrace();
}
}

Spring Batch: not able to access jobexecutionConext in flatfileitemwriter

hey i am trying to use the jobexecutioncontxt in my flatfileitemwriter and it shows me errors...
My xml is:-
<batch:job id="subrogationJob" incrementer="incrementer">
<batch:step id="subrogation" next="readFromDataBase">
<batch:tasklet ref="filetransferTasklet">
<batch:listeners>
<batch:listener ref="setCurrentFile" />
</batch:listeners>
</batch:tasklet>
</batch:step>
<batch:step id="readFromDataBase" next="hasMoreFilesStep">
<batch:tasklet>
<batch:chunk reader="databaseReader" processor="subrogationProcessor" writer="dbToFileItemWriter"
commit-interval="1" />
</batch:tasklet>
</batch:step>
<batch:decision id="hasMoreFilesStep" decider="hasMoreFilesDecider">
<batch:fail on="FAILED" />
<batch:next on="CONTINUE" to="subrogation" />
<batch:end on="COMPLETED"/>
</batch:decision>
</batch:job>
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"
value="file:${UNIQUE_DIR}/${APP_NAME}/batch/nonadj_batch.properties" />
</bean>
<bean id="incrementer"
class="org.springframework.batch.core.launch.support.RunIdIncrementer" />
<bean id="setCurrentFile"
class="com.hcsc.ccsp.nonadj.subrogation.batch.SubrogationInputFolderScanner"
scope="step">
<property name="collectionParameter" value="inputFiles" />
<property name="outputFolder" value="${subrogationOutputFolder}" />
<property name="inputFolder" value="${subrogationInputFolder}" />
<property name="archiveFolder" value="${subrogationArchiveFolder}" />
</bean>
<bean id="filetransferTasklet"
class="com.hcsc.ccsp.nonadj.subrogation.integration.SubrogationFileTransferTasklet"
scope="step">
<property name="inputfile" value="file:#{jobExecutionContext['inputFile']}" />
<property name="outputfile" value="file:#{jobExecutionContext['outputFile']}" />
</bean>
<bean id="subrogationProcessor" class="com.hcsc.ccsp.nonadj.subrogation.processor.SubrogationProcessor" scope="step">
</bean>
<bean id="dbToFileItemWriter" class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
<property name="resource" value="file:#{jobExecutionContext['outputFile']}" />
<property name="lineAggregator">
<bean class="com.hcsc.ccsp.nonadj.subrogation.writer.SubrogationLineAggregator"/>
</property>
<property name="footerCallback" ref="subroHeaderFooterWriter" />
<property name="headerCallback" ref="subroHeaderFooterWriter" />
<property name="transactional" value="true" />
<property name="appendAllowed" value="true" />
<property name="saveState" value="true" />
</bean>
<bean id="subroHeaderFooterWriter" class="com.hcsc.ccsp.nonadj.subrogation.writer.SubrogationHeaderFooterWriter" scope="step">
<property name="delegate" ref="dbToFileItemWriter" />
</bean>
<bean id="hasMoreFilesDecider"
class="com.hcsc.ccsp.nonadj.subrogation.batch.CollectionEmptyDecider" scope="step">
<property name="collectionParameter" value="inputFiles" />
<property name="outputfile" value="file:#{jobExecutionContext['outputFile']}" />
<property name="archiveFolder" value="file:${subrogationArchiveFolder}" />
</bean>
<context:component-scan base-package="com.hcsc.ccsp.nonadj.subrogation.batch"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Component" />
</context:component-scan>
<context:annotation-config />
<bean id="databaseReader"
class="org.springframework.batch.item.database.JdbcCursorItemReader"
scope="step">
<property name="dataSource" ref="subrogrationDataSource" />
<property name="sql"
value="SELECT QUERY" />
<property name="rowMapper">
<bean
class="com.hcsc.ccsp.nonadj.subrogation.integration.SubrogationFieldSetMapper" />
</property>
</bean>
in my listner in beforestep i put parameter in jobcontextn as
ExecutionContext jobContext = stepExecution.getJobExecution().getExecutionContext();
jobContext.put("outputFile", filePath);
and in xml when i m trying to use this in xml in my writer is shows me error.....
but it works fine filetransferTasklet.
error is :-
O inside reader
[5/1/14 10:41:02:303 CDT] 0000001a SystemOut O inside processor........
[5/1/14 10:41:02:303 CDT] 0000001a SystemOut O inside aggregator
[5/1/14 10:41:02:320 CDT] 0000001a AbstractStep E org.springframework.batch.core.step.AbstractStep execute Exception while closing step execution resources
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.subroHeaderFooterWriter' defined in class path resource [subrogation.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type '$Proxy46 implementing org.springframework.batch.item.file.ResourceAwareItemWriterItemStream,org.springframework.beans.factory.InitializingBean,java.io.Serializable,org.springframework.aop.scope.ScopedObject,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised' to required type 'org.springframework.batch.item.file.FlatFileItemWriter' for property 'delegate'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [$Proxy46 implementing org.springframework.batch.item.file.ResourceAwareItemWriterItemStream,org.springframework.beans.factory.InitializingBean,java.io.Serializable,org.springframework.aop.scope.ScopedObject,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [org.springframework.batch.item.file.FlatFileItemWriter] for property 'delegate': no matching editors or conversion strategy found
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:329)
at org.springframework.batch.core.scope.StepScope.get(StepScope.java:150)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:325)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:33)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:182)
at $Proxy47.writeFooter(Unknown Source)
at org.springframework.batch.item.file.FlatFileItemWriter.close(FlatFileItemWriter.java:282)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:600)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy46.close(Unknown Source)
at org.springframework.batch.item.support.CompositeItemStream.close(CompositeItemStream.java:83)
at org.springframework.batch.core.step.tasklet.TaskletStep.close(TaskletStep.java:297)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:264)
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:135)
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:61)
at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:60)
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:144)
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:124)
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:135)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:293)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:120)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:48)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:114)
at com.hcsc.ccsp.nonadj.batch.web.JobLauncherController.launch(JobLauncherController.java:64)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:600)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:718)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1661)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:937)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:500)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3826)
at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:931)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1583)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:186)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:455)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:384)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:272)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1550)
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type '$Proxy46 implementing org.springframework.batch.item.file.ResourceAwareItemWriterItemStream,org.springframework.beans.factory.InitializingBean,java.io.Serializable,org.springframework.aop.scope.ScopedObject,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised' to required type 'org.springframework.batch.item.file.FlatFileItemWriter' for property 'delegate'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [$Proxy46 implementing org.springframework.batch.item.file.ResourceAwareItemWriterItemStream,org.springframework.beans.factory.InitializingBean,java.io.Serializable,org.springframework.aop.scope.ScopedObject,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [org.springframework.batch.item.file.FlatFileItemWriter] for property 'delegate': no matching editors or conversion strategy found
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:462)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:499)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:493)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1371)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1330)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
... 70 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [$Proxy46 implementing org.springframework.batch.item.file.ResourceAwareItemWriterItemStream,org.springframework.beans.factory.InitializingBean,java.io.Serializable,org.springframework.aop.scope.ScopedObject,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [org.springframework.batch.item.file.FlatFileItemWriter] for property 'delegate': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:231)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:447)
... 76 more
[5/1/14 10:41:02:386 CDT] 0000001a AbstractJob E org.springframework.batch.core.job.AbstractJob execute Encountered fatal error executing job
org.springframework.batch.core.JobExecutionException: Flow execution ended unexpectedly
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:141)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:293)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:120)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:48)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:114)
at com.hcsc.ccsp.nonadj.batch.web.JobLauncherController.launch(JobLauncherController.java:64)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:600)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:718)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1661)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:937)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:500)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3826)
at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:931)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1583)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:186)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:455)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:384)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:272)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1550)
Caused by: org.springframework.batch.core.job.flow.FlowExecutionException: Ended flow=subrogationJob at state=subrogationJob.hasMoreFilesStep with exception
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:152)
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:124)
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:135)
... 40 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.hasMoreFilesDecider': Scope 'step' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No context holder available for step scope
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:339)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:33)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:182)
at $Proxy45.decide(Unknown Source)
at org.springframework.batch.core.job.flow.support.state.DecisionState.handle(DecisionState.java:43)
at org.springframework.batch.core.configuration.xml.SimpleFlowFactoryBean$DelegateState.handle(SimpleFlowFactoryBean.java:141)
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:144)
... 42 more
Caused by: java.lang.IllegalStateException: No context holder available for step scope
at org.springframework.batch.core.scope.StepScope.getContext(StepScope.java:197)
at org.springframework.batch.core.scope.StepScope.get(StepScope.java:139)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:325)
... 49 more
[5/1/14 10:41:02:392 CDT] 0000001a SimpleJobLaun I org.springframework.batch.core.launch.support.SimpleJobLauncher$1 run Job: [FlowJob: [name=subrogationJob]] completed with the following parameters: [{param47=47}] and the following status: [FAILED]
SubrogationHeaderFooterWriter is
package com.hcsc.ccsp.nonadj.subrogation.writer;
import java.io.IOException;
import java.io.Writer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.batch.item.file.FlatFileFooterCallback;
import org.springframework.batch.item.file.FlatFileHeaderCallback;
import org.springframework.batch.item.file.FlatFileItemWriter;
import com.hcsc.ccsp.nonadj.subrogation.batch.Subrogation;
import com.hcsc.ccsp.nonadj.subrogation.integration.SubrogationFileTransferTasklet;
import com.hcsc.ccsp.nonadj.subrogation.processor.SubrogationProcessor;
public class SubrogationHeaderFooterWriter implements
FlatFileFooterCallback, FlatFileHeaderCallback{
SubrogationFileTransferTasklet fileTransferTasklet = new SubrogationFileTransferTasklet();
private FlatFileItemWriter<Subrogation> delegate;
public void setDelegate(FlatFileItemWriter<Subrogation> delegate) {
this.delegate = delegate;
}
public FlatFileItemWriter<Subrogation> getDelegate() {
return delegate;
}
/*#Override
public void open(ExecutionContext executionContext)
throws ItemStreamException {
this.delegate.open(executionContext);
}
#Override
public void update(ExecutionContext executionContext)
throws ItemStreamException {
this.delegate.update(executionContext);
}
#Override
public void close() throws ItemStreamException {
this.delegate.close();
}*/
#Override
public void writeHeader(Writer writer) throws IOException {
// TODO Auto-generated method stub
System.out.println("inside header");
writer.write(SubrogationFileTransferTasklet.header);
}
#Override
public void writeFooter(Writer writer) throws IOException {
// TODO Auto-generated method stub
System.out.println("inside header");
String trailer = SubrogationFileTransferTasklet.trailer;
String s1 = StringUtils.substring(trailer, 0, 23);
System.out.println("trailer without contwer is" + s1);
System.out.println("whole traileer is" + s1
+ SubrogationProcessor.totalRecords);
System.out
.println("duplicate data is" + SubrogationProcessor.duplicate);
writer.write(s1 + SubrogationProcessor.totalRecords);
System.out.println("inside Footer");
writer.write("Total Number of Records :: \n\n");
}
/*public void write(List<? extends Subrogation> subrogation) throws Exception {
System.out.println("inside writer");
delegate.write(subrogation);
}*/
}
pls help....
You have two exceptions here. The first one is due to the fact that the type for com.hcsc.ccsp.nonadj.subrogation.writer.SubrogationHeaderFooterWriter.delegate does not match the FlatFileItemWriter. What type is that defined as (if you can update your post with the code for this class, it would be helpful)?
The second one is because you are attempting to use a decider that is step scoped. In a regular Spring Batch job (not a JSR-352 based job), a decider is not a step. Because of that, it doesn't get a StepExecution, and therefore step scope is not supported.
Update
Change your setter for the delegate to take ItemWriter (the interface) instead of FlatFileItemWriter (the implementation) to address the first issue.

Categories