java.net.SocketException: Invalid argument with RestTemplate - java

I'm using RestTemplate in order to send a post request. Something like this:
restTemplate.postForObject(url, fetchImageDataRequest, SimpleImageHolder[].class);
When I create restTemplate like that:
restTemplate = new RestTemplate();
MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
restTemplate.getMessageConverters().add(converter);
Everything works fine. But when I use RestTemplate that is created in spring.xml and defined like this:
<bean id="reHttpConnectionManager" class="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager">
<property name="params">
<bean class="org.apache.commons.httpclient.params.HttpConnectionManagerParams">
<property name="soTimeout" value="30000"/>
<property name="connectionTimeout" value="30000"/>
<property name="maxTotalConnections" value="300"/>
<property name="defaultMaxConnectionsPerHost" value="50"/>
</bean>
</property>
</bean>
<bean id="reRequestFactory" class="org.springframework.http.client.CommonsClientHttpRequestFactory">
<property name="readTimeout" value="3000" />
<constructor-arg>
<bean id="httpClient" class="org.apache.commons.httpclient.HttpClient">
<constructor-arg>
<bean class="org.apache.commons.httpclient.params.HttpClientParams" />
</constructor-arg>
<property name="httpConnectionManager" ref="reHttpConnectionManager" />
<property name="state">
<bean class="org.apache.commons.httpclient.HttpState" />
</property>
</bean>
</constructor-arg>
</bean>
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg ref="reRequestFactory" />
</bean>
I get an java.net.SocketException: Invalid argument exception. Trying to figure this issue.
The full stacke trace:
org.springframework.web.client.ResourceAccessException: I/O error: Invalid argument; nested exception is java.net.SocketException: Invalid argument
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:453)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:401)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:279)

I couldn't find what the problem was but I just removed the HttpParams bean from the constructor of the bean httpClient and removed completely the HttpState and now it works. The new XML looks like this:
<bean id="reHttpConnectionManager" class="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager">
<property name="params">
<bean class="org.apache.commons.httpclient.params.HttpConnectionManagerParams">
<property name="soTimeout" value="30000"/>
<property name="connectionTimeout" value="30000"/>
<property name="maxTotalConnections" value="300"/>
<property name="defaultMaxConnectionsPerHost" value="50"/>
</bean>
</property>
</bean>
<bean id="reRequestFactory" class="org.springframework.http.client.CommonsClientHttpRequestFactory">
<property name="readTimeout" value="3000" />
<constructor-arg>
<bean id="httpClient" class="org.apache.commons.httpclient.HttpClient">
<property name="httpConnectionManager" ref="reHttpConnectionManager" />
</bean>
</constructor-arg>
</bean>
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg ref="reRequestFactory" />
</bean>

Related

Spring and MappingJackson2HttpMessageConverter and registerModule

We are using the latest Spring 4.2.x and we recently went from Jackson Mapper 2.6.3 to 2.8.8, and now we are registering Modules.
Here is part of what or spring-servlet.xml looks like:
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd"></constructor-arg>
</bean>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
and here is what we us in code to map a json file:
  ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new ParameterNamesModule());
mapper.registerModule(new Jdk8Module());
mapper.registerModule(new JavaTimeModule());
So, what I'd like to do is configure the "spring-servlet" and "MappingJackson2HttpMessageConverter" so that I can add the modules to register.
Yes, we haven't gotten into using #Configuration yet, we are still using the XML which I don't mind at all.
Thanks for any help!
So, after some testing and trial and error, we came up with a springmvc-servlet.xml that looks like:
<context:annotation-config />
<context:component-scan base-package="com.tomholmes.mycode.core.server.controller" />
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="objectMapper"
class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="featuresToDisable">
<array>
<util:constant
static-field="com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS" />
</array>
</property>
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd"></constructor-arg>
</bean>
</property>
<property name="modulesToInstall"
value="
com.fasterxml.jackson.datatype.jdk8.Jdk8Module,
com.fasterxml.jackson.datatype.jsr310.JavaTimeModule,
com.fasterxml.jackson.module.paramnames.ParameterNamesModule" />
</bean>
<bean id="jsonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
<property name="objectMapper" ref="objectMapper" />
</bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonHttpMessageConverter" />
</list>
</property>
</bean>
This setup seemed to do the trick.

How to clear cache using CacheConfiguration in Apache ignite

Not able to destroy the cache after some duration time using Spring CacheConfiguration in Apache Ignite.After 40 seconds cache should be cleared.
Please see the below Code.
<bean id="ignite.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
<property name="cacheConfiguration">
<list>
<bean class="org.apache.ignite.configuration.CacheConfiguration">
<property name="name" value="myCache" />
<property name="atomicityMode" value="ATOMIC" />
<property name="backups" value="1" />
<property name="cacheMode" value="PARTITIONED"/>
<property name="expiryPolicyFactory"ref="createdExpiryPolicyForDay"/>
</bean>
<bean id="createdExpiryPolicyForDay" class="javax.cache.expiry.CreatedExpiryPolicy" factory-method="factoryOf" >
<constructor-arg type="javax.cache.expiry.Duration" ref="durationForDay"/>
<constructor-arg type="javax.cache.expiry.Duration" >
<util:constant static-field="javax.cache.expiry.Duration.FIVE_MINUTES"/>
</constructor-arg>
</bean>
<bean name="durationForDay" class="javax.cache.expiry.Duration" >
<constructor-arg name="timeUnit" value="SECONDS" />
<constructor-arg name="durationAmount" value="40"/>
</bean>
Please help us, we are stuck with this issue

ContentNegotiatingViewResolver MediaTypes Error after Upgrading to Spring 4.2

I have a dispatcher-servlet.xml file that has a Bean like this:
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver" p:defaultContentType="text/html">
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean id="localBasedViewResolver" class="com.company.web.i18n.LocaleBasedViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="${views.prefix}"
p:suffix="${views.suffix}"
p:cacheUnresolved="false"
p:exposedContextBeanNames="webProperties"
p:order="1"
/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="${views.prefix}"
p:suffix="${views.suffix}"
p:cacheUnresolved="false"
p:exposedContextBeanNames="webProperties"
p:order="2"
/>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
</list>
</property>
</bean>
After upgrading to Spring 4.2 I get the following error:
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'mediaTypes' of bean class [org.springframework.web.servlet.view.ContentNegotiatingViewResolver]: Bean property 'mediaTypes' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.BeanWrapperImpl.createNotWritablePropertyException(BeanWrapperImpl.java:230) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:423) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:280) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
This worked before the upgrade, so any help on how to fix would be greatly appreciated!
Spring 4.2 ContentNegotiatingViewResolver now delegates content negotiation to a ContentNegotiationManager. Define a ContentNegotiationManager bean in your application context and set it on your view resolver as follows
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="true" />
<property name="ignoreAcceptHeader" value="true"/>
<property name="useJaf" value="false"/>
<property name="defaultContentType" value="text/html" />
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
</map>
</property>
</bean>
Then update your view resolver as follows
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="contentNegotiationManager" ref="contentNegotiationManager"/>
<property name="viewResolvers">
<list>
<bean id="localBasedViewResolver" class="com.company.web.i18n.LocaleBasedViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="${views.prefix}"
p:suffix="${views.suffix}"
p:cacheUnresolved="false"
p:exposedContextBeanNames="webProperties"
p:order="1"
/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="${views.prefix}"
p:suffix="${views.suffix}"
p:cacheUnresolved="false"
p:exposedContextBeanNames="webProperties"
p:order="2"
/>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
</list>
</property>
</bean>

OpenSAML / Spring security setup so redeploy on Tomcat works

We're running a webapp on OpenJDK IcedTea6 1.13.6 using Tomcat 6.0.35. For SSO we're using the Spring security SAML extension, which bases on OpenSAML 2.6.1.
When re-deploying our application (without restarting Tomcat), I get a
NoClassDefFoundError: org/bouncycastle/crypto/paddings/ISO10126d2Padding
which is very nicely described here. From an Eclipse MAT analysis, I gather that either BouncyCastleProvider or JCERSAPublicKey are preventing the WebappClassLoaderfrom being gc'ed.
How do I configure SAML so that all (bouncy castle) instances are properly destroyed? I have a hard time believing that SAML is designed such that a deployment mandates a Tomcat restart.
My current configuration:
...
<bean id="samlLogger" class="org.springframework.security.saml.log.SAMLDefaultLogger">
<property name="logErrors" value="true"/>
<property name="logMessages" value="true"/>
</bean>
<bean id="keyManager" class="org.springframework.security.saml.key.JKSKeyManager">
<constructor-arg value="classpath:security/samlKeystore.jks"/>
<constructor-arg type="java.lang.String" value="mypassword"/>
<constructor-arg>
<map>
<entry key="tenzingfaces" value="keyphrase"/>
</map>
</constructor-arg>
<constructor-arg type="java.lang.String" value="tenzingfaces"/>
</bean>
<bean id="samlEntryPoint" class="org.springframework.security.saml.SAMLEntryPoint">
<property name="defaultProfileOptions">
<bean class="org.springframework.security.saml.websso.WebSSOProfileOptions">
<property name="binding" value="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"/>
<property name="includeScoping" value="false"/>
</bean>
</property>
</bean>
<bean id="metadataDisplayFilter" class="org.springframework.security.saml.metadata.MetadataDisplayFilter"/>
<bean id="samlAuthenticationProvider" class="org.springframework.security.saml.SAMLAuthenticationProvider">
<property name="userDetails" ref="samlUserDetailService" />
<property name="forcePrincipalAsString" value="false" />
</bean>
<bean id="samlUserDetailService" class="ch.umbrella.springframework.security.SamlUserDetailsServiceImpl" />
<bean id="contextProvider" class="org.springframework.security.saml.context.SAMLContextProviderImpl"/>
<bean id="samlSuccessRedirectHandler" class="ch.umbrella.springframework.security.SsoAuthenticationSuccessHandler" >
<property name="defaultTargetUrl" value="/main.html" />
<property name="alwaysUseDefaultTargetUrl" value="false" />
<property name="credentialsExpiredUrl" value="/credentialsexpired.html" />
</bean>
<bean id="samlWebSSOProcessingFilter" class="org.springframework.security.saml.SAMLProcessingFilter">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="authenticationSuccessHandler" ref="samlSuccessRedirectHandler"/>
</bean>
<bean id="processor" class="org.springframework.security.saml.processor.SAMLProcessorImpl">
<constructor-arg>
<list>
<ref bean="redirectBinding"/>
<ref bean="postBinding"/>
</list>
</constructor-arg>
</bean>
<bean id="webSSOprofileConsumer" class="org.springframework.security.saml.websso.WebSSOProfileConsumerImpl"/>
<bean id="hokWebSSOprofileConsumer" class="org.springframework.security.saml.websso.WebSSOProfileConsumerHoKImpl"/>
<bean id="webSSOprofile" class="org.springframework.security.saml.websso.WebSSOProfileImpl"/>
<bean id="hokWebSSOProfile" class="org.springframework.security.saml.websso.WebSSOProfileConsumerHoKImpl"/>
<bean id="postBinding" class="org.springframework.security.saml.processor.HTTPPostBinding">
<constructor-arg ref="parserPool"/>
<constructor-arg ref="velocityEngine"/>
</bean>
<bean id="velocityEngine" class="org.springframework.security.saml.util.VelocityFactory" factory-method="getEngine"/>
<bean id="redirectBinding" class="org.springframework.security.saml.processor.HTTPRedirectDeflateBinding">
<constructor-arg ref="parserPool"/>
</bean>
<bean class="org.springframework.security.saml.SAMLBootstrap"/>
<bean id="parserPool" class="org.opensaml.xml.parse.StaticBasicParserPool" scope="singleton" init-method="initialize"/>
<bean id="parserPoolHolder" class="org.springframework.security.saml.parser.ParserPoolHolder" scope="singleton"/>
...
And, in a staging-specific file:
<bean id="metadata" class="org.springframework.security.saml.metadata.CachingMetadataManager">
<constructor-arg>
<list>
<bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate" destroy-method="destroy">
<constructor-arg>
<bean class="org.opensaml.saml2.metadata.provider.ResourceBackedMetadataProvider" destroy-method="destroy">
<constructor-arg ref="timer1" />
<constructor-arg>
<bean class="org.opensaml.util.resource.ClasspathResource">
<constructor-arg value="/security/idp.xml"/>
</bean>
</constructor-arg>
<property name="parserPool" ref="parserPool"/>
</bean>
</constructor-arg>
<constructor-arg>
<bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
</bean>
</constructor-arg>
</bean>
<bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate" destroy-method="destroy">
<constructor-arg>
<bean class="org.opensaml.saml2.metadata.provider.ResourceBackedMetadataProvider" destroy-method="destroy">
<constructor-arg ref="timer2" />
<constructor-arg>
<bean class="org.opensaml.util.resource.ClasspathResource">
<constructor-arg value="/security/localhost_sp.xml"/>
</bean>
</constructor-arg>
<property name="parserPool" ref="parserPool"/>
</bean>
</constructor-arg>
<constructor-arg>
<bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
<property name="local" value="true"/>
<property name="securityProfile" value="metaiop"/>
<property name="sslSecurityProfile" value="pkix"/>
<property name="signMetadata" value="true"/>
<property name="signingKey" value="tenzingfaces"/>
<property name="encryptionKey" value="tenzingfaces"/>
<property name="requireArtifactResolveSigned" value="false" />
<property name="requireLogoutRequestSigned" value="false" />
<property name="requireLogoutResponseSigned" value="false" />
<property name="idpDiscoveryEnabled" value="false" />
</bean>
</constructor-arg>
</bean>
</list>
</constructor-arg>
<property name="hostedSPName" value="https://hurricane.umbrellanet.ch/uf-test/saml/metadata" />
</bean>
Thanks
Simon
If you are bundling the bouncycastle jars in your war, then don't do that. Instead put those jars in tomcat/lib . Hopefully, that would fix it.

UnMarshalling content-type=application/x-www-form-urlencoded using Jaxb2Marshaller throws error "Content is not allowed in prolog"

I am trying to setup a rest service which handles request of content-type=application/x-www-form-urlencoded. I am currently using Jaxb2Marshaller for unmarshalling the request. However while unmarshalling, it is throwing error "[org.xml.sax.SAXParseException: Content is not allowed in prolog.]".
I checked the xml request as string. It is in url-encoded form as: %3C%3Fxml+version=%221.0%22+encoding%3D%22UTF-8%22+standalone%3D%22yes%22%3F%3E%3Cxrsi%.
It seems this encoded xml string request is causing the error. Is there any way to decode the request first than unmarshall?
Below is my context setting:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000000" />
</bean>
<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="autodetectAnnotations" value="true" />
<!-- Set some properties to make the outputted xml look nicer -->
</bean>
<mvc:annotation-driven>
<mvc:message-converters>
<!-- Configure the XStream message converter -->
<bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="jaxbMarshaller2" />
<property name="unmarshaller" ref="jaxbMarshaller2" />
<property name="supportedMediaTypes">
<list>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="application" />
<constructor-arg index="1" value="xml" />
</bean>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="application" />
<constructor-arg index="1" value="x-www-form-urlencoded" />
</bean>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="jaxbMarshaller2" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.auto.server.schema.ReceiveRequest</value>
<value>com.auto.server.schema.ReceiveReply</value>
</list>
</property>
</bean>
<bean name="viewResolver" class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="ignoreAcceptHeader" value="true" />
<property name="favorParameter" value="true" />
<property name="favorPathExtension" value="true" />
<!-- if no content type is specified, return json. -->
<property name="defaultContentType" value="application/x-www-form-urlencoded" />
<property name="mediaTypes">
<map>
<entry key="xml" value="application/x-www-form-urlencoded" />
</map>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg ref="jaxbMarshaller" />
<property name="modelKey" value="responseObject" />
</bean>
</list>
</property>
</bean>
<!-- REST API controllers -->
<context:component-scan base-package="com.auto.server.schema" />
Here is the controller part
#ResponseBody
#RequestMapping(value = "/heartbeat", method = RequestMethod.POST, headers = { "content-type=application/x-www-form-urlencoded" }, consumes = "application/x-www-form-urlencoded;charset=UTF-8")
public Object heartBeat(#RequestBody ReceiveRequest request) {
ReceiveReply reply = new ReceiveReply();
return reply;
}
If you are always going to get data in URL-encoded style i.e content-type="application/x-www-form-urlencoded"
Then you can simply decode that in your bean when you receive it through following code :
String decodedString = java.net.URLDecoder( inputString, "UTF-8" );

Categories

Resources