Spring java.util.Date bean - spring

I wanna make java.util.Date bean. Date must be specified in human readable format (for example as string "02/25/1990").
How do it easiest (without using deprecated Date() constructors)?
<bean id="date" class="java.util.Date" >
<!-- Need 02/25/1990 -->
</bean>

I found easier solution:
<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="MM/dd/yyyy"/>
</bean>
<bean id="date" factory-bean="dateFormat" factory-method="parse">
<constructor-arg value="02/25/1990"/>
</bean>

Using the non-deprecated Date(long) constructor:
<bean id="date" class="java.util.Date">
<constructor-arg type="java.lang.Long" value="635904000000"/>
</bean>
If you want to use a String instead of the milliseconds you could do the following (uses SimpleDateFormat to produce a Date, while taking advantage of MethodInvokingFactoryBean to invoke it with the specified arguments):
<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="MM/dd/yyyy" />
</bean>
<bean id="date" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="dateFormat"/>
<property name="targetMethod" value="parse"/>
<property name="arguments">
<list>
<value type="java.lang.String">02/25/1990</value>
</list>
</property>
</bean>
Of course you need to use the correct pattern for SimpleDateFormat or could end up with unexpected results

Related

Call SOAP service asynchronously using Spring

I've to call a SOAP web service asynchronously. Currently, I'm calling it in a synchronous way using Spring webservicetemplate.
Current config is like:
<bean id="interceptedHttpClientBuilder" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="httpClientBuilder" />
<property name="targetMethod" value="addInterceptorFirst"> </property>
<property name="arguments">
<list>
<bean class="org.springframework.ws.transport.http.HttpComponentsMessageSender.RemoveSoapHeadersInterceptor"/>
</list>
</property>
</bean>
<bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig" factory-method="custom">
<property name="socketTimeout" value="120000" />
</bean>
<bean id="requestConfig" factory-bean="requestConfigBuilder" factory-method="build" />
<bean id="httpClient" factory-bean="httpClientBuilder" factory-method="build" />
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder" factory-method="create">
<property name="defaultRequestConfig" ref="requestConfig" />
</bean>
<bean id="messageSender" class="org.springframework.ws.transport.http.HttpComponentsMessageSender">
<constructor-arg ref="httpClient"></constructor-arg>
</bean>
<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="packagesToScan">
<list><value>...</value></list>
</property>
</bean>
<bean id="wsClientSecurityInterceptor"
class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="securementActions" value="UsernameToken" />
<property name="securementUsername"><value>${username}</value></property>
<property name="securementPassword"><value>${password}</value></property>
<property name="securementPasswordType" value="PasswordText" />
</bean>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<property name="marshaller" ref="jaxb2Marshaller"></property>
<property name="unmarshaller" ref="jaxb2Marshaller"></property>
<property name="defaultUri"><value>${ws.url}</value></property>
<property name="interceptors">
<list>
<ref local="wsClientSecurityInterceptor"/>
</list>
</property>
<property name="messageSender" ref="messageSender"></property>
</bean>
Java call looks like:
MyResponse response = (MyResponse) webServiceTemplate.marshalSendAndReceive(req, new WebServiceMessageCallback() {
public void doWithMessage(WebServiceMessage message) {
((SoapMessage) message).setSoapAction("test");
}
});
May I know how can I change it to call the service asynchronously? Or Do I need to use something else in spring to achieve this?
Not sure why you use spring-integration tag in your question, but if we are here, please, definitely take a look into the #MessagingGateway with the Future<> as a return type: https://docs.spring.io/spring-integration/docs/5.0.1.RELEASE/reference/html/messaging-endpoints-chapter.html#async-gateway
The SOAP WebService can be called via Spring Integration <int-ws:outbound-gateway>: https://docs.spring.io/spring-integration/docs/5.0.1.RELEASE/reference/html/ws.html
The samples are here: https://github.com/spring-projects/spring-integration-samples
To be more clear the code might looks like this:
<int:gateway id="mathService"
service-interface="org.springframework.integration.samples.async.gateway.MathServiceGateway"
default-request-channel="requestChannel"
async-executor="executor"/>
Where that MathServiceGateway is like this:
public interface MathServiceGateway {
Future<Integer> multiplyByTwo(int i);
}
The WS call is simple as well:
<int-ws:outbound-gateway request-channel="requestChannel" uri="http://www.w3schools.com/xml/tempconvert.asmx"/>

Prevent ResourcePropertySource from throwing FileNotFoundException

Is there a way to prevent ResourcePropertySource from throwing java.io.FileNotFoundException
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="ignoreResourceNotFound" value="true" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="propertySources">
<list>
<bean class="org.springframework.core.io.support.ResourcePropertySource">
<constructor-arg value="file:#{systemProperties['user.home']}/user.properties"/>
</bean>
<bean class="org.springframework.core.io.support.ResourcePropertySource">
<constructor-arg value="classpath:project.properties"/>
</bean>
</list>
</property>
</bean>
I'd like t to fallback to the project.properties if the user.properties file if not found
Why so complex.
<context:property-placeholder location="${user.home}/user.properties,classpath:project.properties" ignore-resource-not-found="true" />
That should be all you need. No need for EL or directly use a ResourcePropertySource.

Spring Batch: Reading a File : if field is empty setting the default value

I am very new to spring batch. I have requirement in which i have to read a file having a header(Field Names) record and data records
i have to validate 1st record (check the field names matching against set of predefined names)- note that this record need to be skipped- i mean should not be part of items in processor)
read and store rest of the field values to a POJO
if the field 'date' is empty , i need to set the default value as 'xxxx-yy-zz'
i am unable to 1st and 3rd requirement with batch
here is the sample reader XML. please help
<bean id="reader" class="org.springframework.batch.item.file.FlatFileItemReader">
<property name="resource" value="classpath:input/import" />
<property name="encoding" value="UTF-8" />
<property name="linesToSkip" value="1" />
<property name="lineMapper" ref="line.mapper"/>
</bean>
<bean id="line.mapper" class="org.springframework.batch.item.file.mapping .DefaultLineMapper">
<property name="lineTokenizer" ref="line.tokenizer"/>
<property name="fieldSetMapper" ref="fieldSet.enity.mapper"/>
</bean>
<bean id="line.tokenizer" class="org.springframework.batch.item.file.transfo rm.DelimitedLineTokenizer">
<property name="delimiter">
<util:constant static-field="org.springframework.batch.item.file.transfo rm.DelimitedLineTokenizer.DELIMITER_TAB"/>
</property>
<property name="names" value="id,date,age " />
<property name="strict" value="false"/>
</bean>
<bean id="fieldSet.enity.mapper" class="org.springframework.batch.item.file.mapping .BeanWrapperFieldSetMapper">
<property name="targetType" value="a.b.myPOJO"/>
<property name="customEditors">
<map>
<entry key="java.util.Date">
<bean class="org.springframework.beans.propertyeditors.C ustomDateEditor">
<constructor-arg>
<bean class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-mm-dd" />
</bean>
</constructor-arg>
<constructor-arg value="true" />
</bean>
</entry>
</map>
</property>
Create your own custom FieldSetMapper like below
CustomeFieldSetMapper implements FieldSetMapper<a.b.myPOJO> {
#Override
public a.b.myPOJO mapFieldSet(FieldSet fs) {
a.b.myPOJO myPOJO = new a.b.myPOJO();
if(fs.readString("date").isEmpty()){
myPOJO.setDate("xxxx-yy-zz");
}
return a.b.myPOJO;
}
}
You think you should do date set in ItemProcessor.
Also, if <property name="linesToSkip" value="1" /> not fill your requirements - extend FlatFileItemReader and validate first line manually in it.

How do I add a jackson objectmapper dateformat config into spring mvc config?

I have a problem about jackson 2.1.
My pojo have some date properties, I want turn it to string, I setted it in spring-servlet.xml but it's not usefull.
I don't like use #JsonSerialize(using = JsonDateSerializer.class) on the setter.
this is my configuration:
<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>
Assuming you are using Spring 3.1, you should customize your mvc-annotation driven tag properties,
as is shown in
Configuring ObjectMapper in Spring
Assuming that your bean declaration is correct I think it should be something 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>
My setup is:
<!-- Date Format -->
<bean id="dateFormatter" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd"/>
</bean>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="dateFormatter" />
<property name="targetMethod" value="setTimeZone" />
<property name="arguments">
<list>
<ref bean="timeZone"/>
</list>
</property>
</bean>
<!-- End Date Format -->
<!-- Jackson Object Mapper -->
<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper"/>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="jacksonObjectMapper" />
<property name="targetMethod" value="configure" />
<property name="arguments">
<list>
<value type="org.codehaus.jackson.map.DeserializationConfig.Feature">FAIL_ON_UNKNOWN_PROPERTIES</value>
<value>false</value>
</list>
</property>
</bean>
<bean id="jacksonDeserializationConfig" class="org.codehaus.jackson.map.DeserializationConfig" factory-bean="jacksonObjectMapper" factory-method="getDeserializationConfig" />
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="jacksonDeserializationConfig" />
<property name="targetMethod" value="setDateFormat" />
<property name="arguments">
<list>
<ref bean="dateFormatter"/>
</list>
</property>
</bean>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="jacksonObjectMapper" />
<property name="targetMethod" value="setDeserializationConfig" />
<property name="arguments">
<list>
<ref bean="jacksonDeserializationConfig"/>
</list>
</property>
</bean>
<!-- End Jackson Object Mapper -->
<!-- JSON provider -->
<bean id="jsonRestProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider">
<property name="mapper" ref="jacksonObjectMapper"/>
</bean>

Jackson+Spring3.0.5 custom object mapper

I am having a hard time configuring Jackson on my Spring application. I can get it to work, but it does not seem to accept any kind of configurations. Basically what i'm trying to achieve is have an ObjectMapper that scans for Spring format annotations.
What i am trying is this:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</list>
</property>
</bean>
<bean id="jacksonObjectMapper" class="ro.softwin.cnfp.ConversionServiceAwareObjectMapper" />
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="html" value="text/html" />
</map>
</property>
<property name="viewResolvers">
<list>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="prefixJson" value="false" />
<property name="objectMapper" value="jacksonObjectMapper" />
</bean>
</list>
</property>
</bean>
The code for the mapper is :
public class ConversionServiceAwareObjectMapper extends ObjectMapper {
#Autowired
public ConversionServiceAwareObjectMapper(
ConversionService conversionService) {
AnnotationIntrospector introspector = AnnotationIntrospector.pair(
new FormatAnnotationIntrospector(conversionService),
DEFAULT_ANNOTATION_INTROSPECTOR);
this.setDeserializationConfig(this.getDeserializationConfig()
.withAnnotationIntrospector(introspector));
this.setSerializationConfig(this.getSerializationConfig()
.withAnnotationIntrospector(introspector).withSerializationInclusion(JsonSerialize.Inclusion.NON_NULL));
}
}
When initializing the server the following error occurs:
java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.codehaus.jackson.map.ObjectMapper] for property 'objectMapper': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:241)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:470)
... 55 more
I tried switching to a normal view resolver and just having the object mapper in the AnnotationMethodHandler, and that works regarding server start-up, but it just completely ignores any configuration.
I am completely at a loss as to what to do next.
Thanks for any help.
Update :
<property name="objectMapper" value="jacksonObjectMapper" />
with:
<property name="objectMapper" ref="jacksonObjectMapper" />
ref not value.

Resources