Spring Integration Multipart form Uploads route with JSON response not working - spring

I have a spring integration route in xml which will make a web service call (multipart/formdata) and need to return the response in JSON format. The problem is I don't find any good sample SI route that do a multipart request with response. Any help is really appreciated.
<?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"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-http="http://www.springframework.org/schema/integration/http"
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
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/http http://www.springframework.org/schema/integration/http/spring-integration-http.xsd">
<bean id="byteArrayHttpMessageConverter"
class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
</bean>
<bean id="formHttpMessageConverter"
class="org.springframework.http.converter.FormHttpMessageConverter">
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<bean id="headerMapper"
class="org.springframework.integration.http.support.DefaultHttpHeaderMapper">
<property name="inboundHeaderNames" value="*" />
<property name="outboundHeaderNames" value="*" />
<property name="userDefinedHeaderPrefix" value="" />
</bean>
<int:channel id="http.request.submit.withfiles" />
<int:channel id="http.response.submit.withfiles" />
<int:channel id="http.router.route1.process.submit.withfiles" />
<int:channel id="http.router.route2.process.submit.withfiles" />
<int-http:inbound-gateway id="http.gateway.inbound.submit.withfiles"
supported-methods="POST" header-mapper="headerMapper"
request-channel="http.request.submit.withfiles"
reply-channel="http.response.submit.withfiles" path="/v1.0/file">
<int-http:request-mapping consumes="multipart/form-data"
produces="application/json" />
<int-http:header name="routingCode" expression="headers['routingCode']" />
</int-http:inbound-gateway>
<int:header-value-router input-channel="http.request.submit.withfiles"
header-name="routingCode" default-output-channel="http.router.route2.process.submit.withfiles">
<int:mapping value="AB"
channel="http.router.route1.process.submit.withfiles" />
<int:mapping value="AC"
channel="http.router.route2.process.submit.withfiles" />
<int:mapping value="AD"
channel="http.router.route2.process.submit.withfiles" />
<int:mapping value="AE"
channel="http.router.route2.process.submit.withfiles" />
<int:mapping value="AF"
channel="http.router.route2.process.submit.withfiles" />
</int:header-value-router>
<int-http:outbound-gateway
id="http.gateway.outbound.route1.submit.withfiles" header-mapper="headerMapper"
request-channel="http.router.route1.process.submit.withfiles"
reply-channel="http.response.submit.withfiles"
url="http://localhost:8080/myapplication1/file"
http-method-expression="headers.http_requestMethod"
expected-response-type="java.lang.String" charset="UTF-8"
reply-timeout="50000" />
<int-http:outbound-gateway
id="http.gateway.outbound.route2.submit.withfiles" header-mapper="headerMapper"
request-channel="http.router.route2.process.submit.withfiles"
reply-channel="http.response.submit.withfiles"
url="http://localhost:8081/myapplication2/file"
http-method="POST" charset="UTF-8" expected-response-type="java.lang.String"
reply-timeout="50000">
</int-http:outbound-gateway>
Error Message:
02-Sep-2015 13:36:07.300 SEVERE [http-nio-8080-exec-13] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [springServlet] in context with path [/my-switcher] threw exception [Request processing failed; nested exception is org.springframework.messaging.MessageHandlingException: HTTP request execution failed for URI [http://localhost:8081/myapplication2/file]; nested exception is org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: org.springframework.integration.http.multipart.UploadedMultipartFile["inputStream"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: org.springframework.integration.http.multipart.UploadedMultipartFile["inputStream"])] with root cause
com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: org.springframework.integration.http.multipart.UploadedMultipartFile["inputStream"])
at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:59)
at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:26)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:575)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:666)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:156)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:129)
at com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:2240)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:231)
at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
at org.springframework.http.converter.FormHttpMessageConverter.writePart(FormHttpMessageConverter.java:331)
at org.springframework.http.converter.FormHttpMessageConverter.writeParts(FormHttpMessageConverter.java:311)
at org.springframework.http.converter.FormHttpMessageConverter.writeMultipart(FormHttpMessageConverter.java:301)
at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:240)
at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:87)
at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:774)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:567)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:545)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:466)
at org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler.handleRequestMessage(HttpRequestExecutingMessageHandler.java:422)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:99)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:78)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:101)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:97)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:286)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:245)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:95)
at org.springframework.integration.router.AbstractMessageRouter.handleMessageInternal(AbstractMessageRouter.java:188)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:78)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:101)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:97)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:286)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
at org.springframework.messaging.core.GenericMessagingTemplate.doSendAndReceive(GenericMessagingTemplate.java:150)
at org.springframework.messaging.core.GenericMessagingTemplate.doSendAndReceive(GenericMessagingTemplate.java:45)
at org.springframework.messaging.core.AbstractMessagingTemplate.sendAndReceive(AbstractMessagingTemplate.java:42)
at org.springframework.integration.gateway.MessagingGatewaySupport.doSendAndReceive(MessagingGatewaySupport.java:331)
at org.springframework.integration.gateway.MessagingGatewaySupport.sendAndReceiveMessage(MessagingGatewaySupport.java:302)
at org.springframework.integration.http.inbound.HttpRequestHandlingEndpointSupport.actualDoHandleRequest(HttpRequestHandlingEndpointSupport.java:492)
at org.springframework.integration.http.inbound.HttpRequestHandlingEndpointSupport.doHandleRequest(HttpRequestHandlingEndpointSupport.java:389)
at org.springframework.integration.http.inbound.HttpRequestHandlingMessagingGateway.handleRequest(HttpRequestHandlingMessagingGateway.java:103)
at org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:51)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1517)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1474)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
More Details:
The actual webservice (http://localhost:8081/myapplication2/file) do a multipart form upload and returns a json message back to the calling application. So what I am expecting from this SI route is the http-outbound gateway will call the above webservice and do a postupload and returns a json response .
Also I am passing the request via postman like this.

Proxying a multipart/form-data request like this is not currently supported.
The problem is that Spring MVC has converted the raw form data to a MultipartHttpInputMessage; which is further converted by the inbound gateway to a MultiValueMap, where the file part(s) is(are) UploadedMultipartFile instances.
The outbound gateway does not know how to process this object; there's not a converter for it.
You could try adding a transformer, to convert the UploadedMultiPartFile element(s) in the payload to Resource(s), or write a custom MessageConverter and inject it into the outbound gateway.
We are seeing more and more of these HTTP "proxy" scenarios, so please open a 'new feature' JIRA issue.
Even better, consider contributing a solution!
EDIT:
Here is another work around - and it is more efficient. Effectively we want to disable multi-part decoding in the inbound gateway, and pass the multi-part request unchanged to the outbound.
Here's how to do it...
Remove the multipart resolver bean
Add a custom "pass-thru" multi-part converter to the inbound gateway...
public class PassThroughMultiPartConverter implements HttpMessageConverter<byte[]> {
#Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
if (!(byte[].class.isAssignableFrom(clazz))) {
return false;
}
if (mediaType != null) {
return MediaType.APPLICATION_FORM_URLENCODED.includes(mediaType)
|| MediaType.MULTIPART_FORM_DATA.includes(mediaType);
}
else {
return false;
}
}
#Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return false;
}
#Override
public List<MediaType> getSupportedMediaTypes() {
return Collections.singletonList(MediaType.MULTIPART_FORM_DATA);
}
#Override
public byte[] read(Class<? extends byte[]> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileCopyUtils.copy(inputMessage.getBody(), baos);
return baos.toByteArray();
}
#Override
public void write(byte[] t, MediaType contentType, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
throw new UnsupportedOperationException();
}
}
.
<int-http:inbound-gateway
...
request-payload-type="byte[]"
message-converters="converter"
merge-with-default-converters="false" />
<bean id="converter" class="foo.PassThroughMultiPartConverter" />

Thanks Gary.
As of now I resolved this issue by replacing the 'http outbound gate way' with 'service activator' and invoke the webservice via REST Template inside the class which is referred in the service activator.
<int:service-activator id="serviceactivator"
input-channel="http.router.process.submit.withfiles"
output-channel="http.response.submit.withfiles"
ref="multipartReceiver" method="receive"
requires-reply="true" >
</int:service-activator>

Related

Spring integration and AMQP on RabbitMQ throws exception Method handleToken(byte[]) cannot be found

This is my context config:
<?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:int-amqp="http://www.springframework.org/schema/integration/amqp"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xmlns:int="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/integration/amqp http://www.springframework.org/schema/integration/amqp/spring-integration-amqp.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd">
<rabbit:connection-factory id="connectionFactory" host="localhost"/>
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory"/>
<rabbit:queue name="upload-queue"/>
<rabbit:admin connection-factory="connectionFactory"/>
<rabbit:topic-exchange name="infrastructure-exchange">
<rabbit:bindings>
<rabbit:binding queue="upload-queue" pattern="ru.interosite.*"/>
</rabbit:bindings>
</rabbit:topic-exchange>
<int-amqp:outbound-channel-adapter
channel="toRabbit"
routing-key="ru.interosite.1"
amqp-template="amqpTemplate"
exchange-name="infrastructure-exchange"/>
<int-amqp:inbound-channel-adapter
channel="fromRabbit"
queue-names="upload-queue"
connection-factory="connectionFactory"
/>
<int:gateway id="infrastructureGateway" service-interface="com.dropbyke.web.api.service.InfrastructureGateway"/>
<int:channel id="toRabbit"/>
<int:channel id="fromRabbit"/>
<bean id="testInfrastructureServiceImpl" class="com.dropbyke.web.api.service.TestInfrastructureServiceImpl"/>
<int:service-activator input-channel="fromRabbit" ref="testInfrastructureServiceImpl" method="handleToken" />
<!-- A Spring Integration adapter that routes messages sent to the helloWorldChannel to the bean named "helloServiceImpl"'s hello() method -->
<!--<int:outbound-channel-adapter channel="fromRabbit" ref="testInfrastructureServiceImpl" method="handleToken"/>-->
</beans>
This is gateway interface:
public interface InfrastructureGateway {
#Gateway(requestChannel = "toRabbit")
void doUpload(UserTokenDTO tokenDTO);
}
Message endpoint that supposed to handle calls:
#MessageEndpoint
public class TestInfrastructureServiceImpl implements TestInfrastructureService {
public void handleToken( UserTokenDTO tokenDTO) {
System.out.println("Handle user token " + tokenDTO.getToken());
}
}
So when I invoke gateway's doUpload method I'm getting this error message:
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1004E:(pos 8): Method call: Method handleToken(byte[]) cannot be found on com.dropbyke.web.api.service.TestInfrastructureServiceImpl type
If I exclude Rabbit part then all works fine. What should I do to make it work with Rabbit? Should I implement some converter from byte[] to my domain object UserTokenDTO?
As nicolas-labrot suggested I had to make my UserTokenDTO to be a Serializable. After that all works fine.

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.

Spring: Can't move #Transactioanl annotation from DAO to Service layer

It the Transactional annotation is in the DAO layer it works, if I move it to the service layer, I get exception:
Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.adam.czibere.RestAPIController]: Illegal arguments for constructor; nested exception is java.lang.IllegalArgumentException: argument type mismatch
Here is my code:
CatalogDAOInterface:
public interface CatalogDAOInterface {
public List<Product> getAllProduct();
public List<Category> getAllCategories() ;
public List<Media> getAllMedias();
}
CatalogDAO:
#Repository
#SuppressWarnings({"unchecked", "rawtypes"})
public class CatalogDAO implements CatalogDAOInterface {
#Autowired private SessionFactory sessionFactory;
#Override
public List<Product> getAllProduct() {
Session session = sessionFactory.getCurrentSession();
List products = session.createQuery("from Product").list();
return products;
}
#Override
public List<Category> getAllCategories() {
Session session = sessionFactory.getCurrentSession();
List products = session.createQuery("from Category").list();
return products;
}
#Override
public List<Media> getAllMedias() {
Session session = sessionFactory.getCurrentSession();
List medias = session.createQuery("from Media").list();
return medias;
}
}
CatalogServiceInterface:
public interface CatalogServiceInterface {
public List<Category> getAllCategories();
public List<Product> getAllProducts();
public List<Media> getAllMedias();
}
CatalogService:
#Service
public class CatalogService implements CatalogServiceInterface{
#Autowired
private CatalogDAO catalogDAO;
#Transactinal
#Override
public List<Product> getAllProducts() {
return catalogDAO.getAllProduct();
}
#Transactinal
#Override
public List<Category> getAllCategories() {
return catalogDAO.getAllCategories();
}
#Transactinal
#Override
public List<Media> getAllMedias() {
return catalogDAO.getAllMedias();
}
}
servlet-context.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- Enable #Controller annotation support -->
<mvc:annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<context:component-scan base-package="com.adam.czibere" />
<!-- <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" -->
<!-- destroy-method="close"> -->
<!-- <property name="driverClassName" value="com.mysql.jdbc.Driver" /> -->
<!-- <property name="url" value="jdbc:mysql://localhost:3306/pizzashop" /> -->
<!-- <property name="username" value="root" /> -->
<!-- <property name="password" value="czadam" /> -->
<!-- <property name="validationQuery" value="SELECT 1" /> -->
<!-- </bean> -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver" />
<property name="url" value="jdbc:jtds:sqlserver://something" />
<property name="username" value="something" />
<property name="password" value="something" />
<property name="validationQuery" value="SELECT 1" />
</bean>
<!-- Hibernate Session Factory -->
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan">
<array>
<value>com.adam.czibere</value>
</array>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean>
<!-- Hibernate Transaction Manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
<!-- Activates annotation based transaction management -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
The stack trace:
exception
javax.servlet.ServletException: Servlet.init() for servlet appServlet threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:724)
root cause
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'catalogAPIController' defined in file [C:\Users\czadam\Documents\workspace 2.0\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\SalesWizard\WEB-INF\classes\com\adam\czibere\CatalogAPIController.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.adam.czibere.CatalogAPIController]: Illegal arguments for constructor; nested exception is java.lang.IllegalArgumentException: argument type mismatch
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:288)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1035)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:939)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:724)
root cause
org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.adam.czibere.CatalogAPIController]: Illegal arguments for constructor; nested exception is java.lang.IllegalArgumentException: argument type mismatch
org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:158)
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:110)
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:280)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1035)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:939)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:724)
root cause
java.lang.IllegalArgumentException: argument type mismatch
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:526)
org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:110)
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:280)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1035)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:939)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:724)
Part of My Controller:
#Controller
#RequestMapping(value = "api", produces = "application/json")
public class CatalogAPIController {
CatalogService catalogService;
private static final int BUFFER_SIZE = 4096;
#Autowired
public CatalogAPIController(CatalogService catalogService) {
this.catalogService = catalogService;
}
// get all categories
#RequestMapping(value = "category/all", produces = "application/json;charset=UTF-8")
#ResponseBody
public String getAllCategories() {
JSONArray categoryArray = new JSONArray();
for (Category cat : catalogService.getAllCategories()) {
JSONObject categoryJSON = new JSONObject();
try {
categoryJSON.put("id", cat.getId());
categoryJSON.put("name", cat.getName());
categoryJSON.put("imageMediaID", cat.getImageMediaID());
categoryJSON.put("parentID", cat.getParent().getId());
// Media
JSONArray mediaArray = new JSONArray();
for (Media item : cat.getMedias()) {
if (item != null) {
mediaArray.put(item.getId());
}
}
categoryJSON.put("mediaIDs", mediaArray);
categoryJSON.put("modifiedDate", cat.getModifiedDate());
categoryArray.put(categoryJSON);
} catch (JSONException e) {
e.printStackTrace();
return "Error: " + e.getMessage();
}
}
return categoryArray.toString();
}
}
When Spring is applying the #Transactional annotation internally, it creates a proxy class which wraps your service class.
So when your service bean is created in your application context, you are getting an object that is not of type CatalogService but some Proxy$1 class.
This Proxy$1 class will not extend CatalogService but it will implement CatalogServiceInterface. Therefore, when your CatalogAPIController bean gets created, it attempts to call its constructor with your Proxy$1 object which is the wrong type as your constructor expects a class.
So if you were to change your controller to use the interface instead of the implementation, then I believe your problems will disappear. This is because Proxy$1 DOES implement CatalogServiceInterface.
The moral of the story: ALWAYS use the interface if you reference your implementation (for if you ever decide to provide a different implementation (e.g. CatalogService2 which also implements CatalogServiceInterface, you can only plug that into your CatalogAPIController if its constructor is using the interface rather than the class (and essentially this is what's happening when you specify #Transactional.
Hope that makes sense.
two thing caught my attention
1.
#Transactinal
is it a typo or are you importing another annotation, it should be #Transactional
2.
why aren't you using the interfaces if you're already defining them?
instead of
#Autowired
public CatalogAPIController(CatalogService catalogService) {
this.catalogService = catalogService;
}
change it to
#Autowired
public CatalogAPIController(CatalogServiceInterface catalogService) {
this.catalogService = catalogService;
}
same applies to dao interface.
I don't understand the relation between moving transactional from one place to the other. See if that helps
This is what I can think of with the details you've provided. I believe you don't have the CGLIB libraries on your classpath. As such, for Spring to apply #Transactional behavior, it proxies your annotated class with JDK proxies. JDK proxies use interfaces, they cannot proxy base classes. As such, the direct superclass of a proxy is java.lang.reflect.Proxy.
In this case, your CatalogService bean will be wrapped in a proxy whose class is something like Proxy$1. When Spring tries to instantiate your #Controller class, CatalogAPIController, through reflection using the constructor
#Autowired
public CatalogAPIController(CatalogService catalogService) {
this.catalogService = catalogService;
}
it will fail because the argument passed to the Constructor#newInstance(Object...) method will not match the parameter type CatalogService since Proxy$1 is not a sub type of CatalogService.
The reason this didn't happen when you were annotating the DAO, I believe is that your DAO class is not on the component-scan package that applied #Transactional behavior. So it might have appeared as though the #Transactional was working but it wasn't. Because #Transactional wasn't working, no proxy was created and therefore Spring didn't complain about injecting this field
#Autowired
private CatalogDAO catalogDAO;
in your service class.
One possible solution is to do what Luis recommended and change your parameter types to the interface as JDK proxies to implement the interfaces, ie. the interfaces are supertypes of the Proxy$1 class instance generated to wrap your bean.
Another solution is to provide the CGLIB jars on your classpath. Spring will detect them and use them. It will then be able to proxy your class by base class instead of interface. You can find the libraries here.
Don't forget to tell Spring to proxy the target class with
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />

Spring mvc test - testing controllers with Autowired annotations

I am trying to create some tests for my controllers using spring test framework.
Following this article: http://blog.springsource.org/2012/11/12/spring-framework-3-2-rc1-spring-mvc-test-framework/ I created this test class
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration("classpath:testContext.xml")
public class ServiceRequestControllerTest {
#Autowired
private WebApplicationContext wac;
#Autowired
private ServiceRequestController productController;
#Autowired
private WSServiceRequestIO wsServiceRequestIO;
#Autowired
private Open311ResponseMarshaller open311ResponseMarshaller;
#Autowired
private Open311GETQueryStringParser open311GETQueryStringParser;
#Autowired
private Open311POSTQueryStringParser open311POSTRequestParser;
#Autowired
private Open311ResponseFactory responseFactory;
private MockMvc mockMvc;
#Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
#Test
public void testTest() throws Exception {
this.mockMvc.perform(get("/requests"));
}
}
and my testContext.xml is
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<bean class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="utils.webservice.WSServiceRequestIO" />
</bean>
<bean class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="open311.model.Open311ResponseMarshaller" />
</bean>
<bean class="org.mockito.Mockito" factory-method="mock">
<constructor-arg
value="open311.utils.Open311POSTQueryStringParser" />
</bean>
<bean class="org.mockito.Mockito" factory-method="mock">
<constructor-arg
value="open311.utils.Open311GETQueryStringParser" />
</bean>
<bean class="org.mockito.Mockito" factory-method="mock">
<constructor-arg
value="open311.model.Open311ResponseFactory" />
</bean>
<context:component-scan base-package="open311.controller" />
<mvc:annotation-driven />
<mvc:resources mapping="/services*" location="/resources/" />
</beans>
now, when I run my tests I get a lot of messages like:
2013-04-19 14:33:34 INFO GenericTypeResolver:216 - Could not determine the target type for type argument [T] for method [public static <T> T org.mockito.Mockito.mock(java.lang.Class<T>)].
so there is some problem with inferring types by mockito, but still when I enter the debug mode and inspect my controller I can see that objects were injected correctly. (I am using #Autowire annotation in my controller).
Anyway, when I try to run this test I am getting test failure because of
org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoSuchMethodError: javax/servlet/http/HttpServletResponse.getContentType()Ljava/lang/String;
at org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1259)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:816)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:66)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:168)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:136)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:134)
at open311.controller.ServiceRequestControllerTest.testTest(ServiceRequestControllerTest.java:58)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
what could be the source of my problem? I think that I followed every step from this tutorial.
The NoSuchMethodError indicates that you likely have an incompatible version of the Servlet API on your test classpath.
Also, you'll need to include your Spring MVC configuration as well as the bean definition for your ServiceRequestController within your test XML config, either directly, via an import, or by declaring a separate XML config file via #ContextConfiguration.

HTTP Status 500 - Request processing failed; nested exception is org.hibernate.HibernateException: /hibernate.cfg.xml not found

I am a newbie to Hibernate and Spring and I am getting the above exception while executing the application.
I am trying to fetch the values of a record from the database.
Following is the exception that I am getting :-
message Request processing failed; nested exception is org.hibernate.HibernateException: /hibernate.cfg.xml not found
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: /hibernate.cfg.xml not found
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
org.hibernate.HibernateException: /hibernate.cfg.xml not found
org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:170)
org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1497)
org.hibernate.cfg.Configuration.configure(Configuration.java:1519)
org.hibernate.cfg.Configuration.configure(Configuration.java:1506)
com.me.app.HomeController.handleRequestInternal(HomeController.java:56)
org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.34 logs.
Following are my file :-
POJO
public class Usertable {
int id;
String userName;
String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Controller
//#Controller
public class HomeController extends AbstractController{
//private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
// #RequestMapping(value = "/", method = RequestMethod.GET)
// public String home(Locale locale, Model model) {
// logger.info("Welcome home! The client locale is {}.", locale);
//
// Date date = new Date();
// DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
//
// String formattedDate = dateFormat.format(date);
//
// model.addAttribute("serverTime", formattedDate );
//
// return "home";
// }
#Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
Usertable user;
Configuration cfg = new Configuration();
SessionFactory sf = cfg.configure().buildSessionFactory();
Session hibsession = sf.openSession();
Transaction tx = hibsession.beginTransaction();
user = (Usertable)hibsession.get(Usertable.class, userName);
System.out.println("UserName is "+ user.getUserName());
System.out.println("Password is "+ user.getPassword());
tx.commit();
hibsession.close();
return new ModelAndView("first","abc","abc");
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">tiger</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/contacts</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="Usertable.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Usertable.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 20 Mar, 2013 4:26:30 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.me.app.Usertable" table="USERTABLE">
<id name="id" type="java.lang.Integer">
<column name="UserID" />
<generator class="native" />
</id>
<property name="userName" type="java.lang.String">
<column name="UserName" />
</property>
<property name="password" type="java.lang.String">
<column name="UserPassword" />
</property>
</class>
</hibernate-mapping>
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<!-- <resources mapping="/resources/**" location="/resources/" /> -->
<beans:bean id="urlMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<beans:bean name="/books.htm" class="com.me.app.HomeController" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.me.app" />
</beans:beans>
Kindly help me with this issue.Thanks in advance.!
The thing is you shouldn't instantiate your hibernate configuration in your handle of a request but rather let spring instantiate your session factory and inject it into your controller and retrieve the session from there. Doing this, then you won't have to implement a session factory for each request made to your application.
You can check this question or the official documentation to have details on how to instantiate your session factory via spring.
This will (indirectly) solve your problem.
benzonico and KHY thanks for your inputs. The first mistake that I was doing was I placed the hibernate.cfg.xml inside src/main/java/com/me/app/ which should have been src/main/java/. This worked for me. The next part about TypedMismatch was
user = (Usertable)hibsession.get(Usertable.class, userName);
I was trying to get the String reference from the database which was actually Integer. So that solved the typedMismatchException.
I will definitely try injecting the session factory into my code through spring. Since I am new to this frameworks I learnt a loads while discussing with you and trying the new codes.
Thanks again for your valuable feedback.

Resources