How to setup LocalDateTime in Spring XML configuration - java

My problem relates to the following class:
public class MyClass {
private LocalDateTime startDate;
}
I am trying to setup the startDate property of this bean using Spring XML configuration:
<property name="startDate">
<value>2000-01-01</value>
</property>
I get an error:
Cannot convert value of type [java.lang.String] to required type [java.time.LocalDateTime] for property 'startDate'
Is it possible to use Spring to do this conversion? I found examples on the net how to do that for Date object, however, LocalDateTime doesn't have a constructor taking a string (and the solution seems to need such constructor). LocalDateTime is constructed by using the static method LocalDateTime.parse.
Using the annotations #DateTimeFormat, like:
public class MyClass {
#DateTimeFormat(iso=ISO.LOCAL_DATE_TIME)
private LocalDateTime startDate;
}
is not a solution, since MyClass has to be available outside Spring.
Thanks in advance

you can register your conversion. like the following code, the following will convert a string to LocalDateTime
class CustomLocalDateTimeEditor extends PropertyEditorSupport {
private final boolean allowEmpty;
private final int exactDateLength;
public CustomLocalDateTimeEditor( boolean allowEmpty) {
this.allowEmpty = allowEmpty;
this.exactDateLength = -1;
}
public CustomLocalDateTimeEditor(boolean allowEmpty, int exactDateLength) {
this.allowEmpty = allowEmpty;
this.exactDateLength = exactDateLength;
}
#Override
public void setAsText(String text) throws IllegalArgumentException {
if (this.allowEmpty && !StringUtils.hasText(text)) {
setValue(null);
}
else if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) {
throw new IllegalArgumentException("Could not parse date: it is not exactly" + this.exactDateLength + "characters long");
}
else {
try {
setValue(LocalDateTime.parse(text));
}
catch (DateTimeParseException ex) {
throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
}
}
}
#Override
public String getAsText() {
LocalDateTime value = LocalDateTime.parse(String.valueOf(getValue()));
return (value != null ? value.toString() : "");
}
}

Here is what I ended up with based on Javy's comment:
import java.beans.PropertyEditorSupport;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class CustomLocalDateTimeEditor extends PropertyEditorSupport {
public CustomLocalDateTimeEditor() {
}
private LocalDateTime parseText(String text) {
LocalDateTime ldt;
try {
ldt = LocalDateTime.parse(text);
} catch(Exception ee) {
ldt = null;
}
if(ldt == null) {
try {
ldt = LocalDateTime.of(LocalDate.parse(text), LocalTime.of(0, 0));
} catch(Exception ee) {
ldt = null;
}
}
return ldt;
}
#Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(parseText(text));
}
#Override
public String getAsText() {
LocalDateTime value = parseText(String.valueOf(getValue()));
return (value != null ? value.toString() : "");
}
}
And in the XML I have the following:
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.time.LocalDateTime" value="com.mycompany.CustomLocalDateTimeEditor" />
</map>
</property>
</bean>
<bean id="myClass" class="MyClass">
<property name="startDate">
<value>2000-01-01</value>
</property>
</bean>

You can use #DateTimeFormat annotation and provide a pattern. For example
#DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDateTime startDate;
When Spring find the Joda localdatetime, it will convert date in appropriate format.
#DateTimeFormat in spring

Declare a dateFormat bean, in “MyClass” bean, reference “dateFormat” bean as a factory bean. The factory method will call SimpleDateFormat.parse() to convert String into Date object automatically.
reference:
http://www.mkyong.com/spring/spring-how-to-pass-a-date-into-bean-property-customdateeditor/

Related

How to validate that time format in Java is as expected

In my REST API Controller with #PathVariable("timestamp) I have to validate that timestamp format is complaint with ISO 8601 standard: eg. 2016-12-02T18:25:43.511Z.
#RequestMapping("/v3/testMe/{timestamp}")
public class TestController {
private static final String HARDCODED_TEST_VALUE = "{\n\t\"X\": \"01\",\n\t\"Y\": \"0.2\"\n}";
#ApiOperation(nickname = "getTestMe", value = "Return TestMe value", httpMethod = "GET",
authorizations = {#Authorization(value = OAUTH2,
scopes = {#AuthorizationScope(scope = DEFAULT_SCOPE, description = SCOPE_DESCRIPTION)})})
#RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public String getTestMe(#PathVariable("timestamp") String timestamp) {
if (timestamp != null) {
return HARDCODED_TEST_VALUE;
}
throw new ResourceNotFoundException("wrong timestamp format");
}
}
The way of how I would like to achieve it is similiar to above if-else statement that check whether timestamp is null or not - so analogically I would like to add similiar if-else to validate format of timestamp and return body if so or 404 error code if it's not.
Any idea what I could use to do that and please give me ready example ? I've tried simple validation with regex but is not convenient and unfortunately didn't work anyway ...
You can use Java 8's DateTimeFormatter and make sure it parses the string without throwing an exception. Here's a method that that returns true if the input string is a valid ISO date:
boolean isValidIsoDateTime(String date) {
try {
DateTimeFormatter.ISO_DATE_TIME.parse(date);
return true;
} catch (DateTimeParseException e) {
return false;
}
}
To return the hardcoded test value in response body, you should use the method like this:
public String getTestMe(#PathVariable("timestamp") String timestamp) {
if (timestamp != null && isValidIsoDateTime(timestamp)) {
return HARDCODED_TEST_VALUE;
}
throw new ResourceNotFoundException("wrong timestamp format");
}
public class MyClass {
public static void main(String args[]) {
System.out.println("-------------OK--------------");
String inputTimeString = "makara_kann";
if (!inputTimeString.matches("^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$")){
System.out.println("Invalid time string: " + inputTimeString);
} else {
System.out.println("valid time string: " + inputTimeString);
}
}
}
-------------OK--------------
Invalid time string: makara_kann

Can't convert from string to Joda LocalTime with DefaultFormattingConversionService

Am unable to convert string to Joda LocalTime with DefaultFormattingConversionService.
If I pass time as "12:00" it says time is too short, but if I pass it as "12:00:00", it says it is malformed.
import org.joda.time.LocalTime;
import org.springframework.format.support.DefaultFormattingConversionService;
public class SpringLocalTimeFormatterTry {
public static void main(String[] args) {
DefaultFormattingConversionService service = new DefaultFormattingConversionService();
try {
System.out.println(service.convert("12:00", LocalTime.class));
}
catch (Exception e) {
System.out.println(e.getMessage());
}
try {
System.out.println(service.convert("12:00:00", LocalTime.class));
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
How to use it correctly or fix?
The vanilla settings of DefaultFormattingConversionService use platform default locale, which, I assume from the error, are the same as mine, ie. English. That means, that for time you need to add the AM/PM indicator. This works for me:
System.out.println(service.convert("10:12 am", LocalTime.class));
>> 10:12:00.000
To handle your desired time format, you can add an extra converter:
service.addConverter(new Converter<String, LocalTime>() {
#Override
public LocalTime convert(String source) {
return LocalTime.parse(source);
}
});
Then, both examples pass:
System.out.println(service.convert("12:00", LocalTime.class));
>> 12:00:00.000
System.out.println(service.convert("12:00:00", LocalTime.class));
>> 12:00:00.000
You can skip registering the default converters by creating the service with
new DefaultFormattingConversionService(false);
Finally, I assume in the production code you are actually getting the ConversionService from the ConversionServiceFactoryBean, so you can configure that as follows:
#Bean
public ConversionServiceFactoryBean conversionService() {
ConversionServiceFactoryBean conversionServiceFactoryBean = new ConversionServiceFactoryBean();
Set<Converter<?, ?>> myConverters = new HashSet<>();
myConverters.add(new Converter<String, LocalTime>() {
#Override
public LocalTime convert(String source) {
return LocalTime.parse(source);
}
});
conversionServiceFactoryBean.setConverters(myConverters);
return conversionServiceFactoryBean;
}
Try this:
DateTimeFormatter dtf = DateTimeFormat.forPattern("HH:mm:ss");
LocalTime localTime = dtf.parseLocalTime("12:00:00");
System.out.println("Time"+localTime);

How to display java.time.LocalDate (Java 8) in Spring MVC 4 JSP [duplicate]

I haven't been able to figure out how to display a java.time.LocalDate value in a JSP.
In my JSP, I have this:
<fmt:formatDate value="${std.datum}" type="date" pattern="dd.MM.yyyy" var="stdDatum" />
The std.datum is of type java.time.LocalDate. When rendering the JSP I get this exception:
javax.el.ELException:
Cannot convert 2015-02-14 of type class
java.time.LocalDate to class java.util.Date
I'm assuming it's the conversion?
So is it possible to format an instance of LocalDate class with <fmr:formatDate> action?
I'm assuming it's the conversion?
Yes, it's a conversion related exception.
Solution
You could first use the <fmt:parseDate> action from the JSTL's "I18n capable formatting tag library" to do the conversion and then do the formatting with the <fmt:formatDate> action.
Here is an example:
<fmt:parseDate value="${std.datum}" type="date" pattern="yyyy-MM-dd" var="parsedDate" />
<fmt:formatDate value="${parsedDate}" type="date" pattern="dd.MM.yyyy" var="stdDatum" />
This solution is also presented right in the "JavaServer Pages™ Standard Tag Library (JSTL)" specification version 1.2 (see page 109).
This is an old question, but i find it is very best to do a custom tld in this case: without any double conversion to and from String.
Do your own tld file, then override the FormatDate class. Finally, declare your own custom prefix and use custom:formatDate instead of fmt:formatDate.
here is a simplified version
usage in JSP:
<%# taglib uri="/WEB-INF/custom" prefix="custom" %>
...
<custom:formatDate value="${std.datum}" pattern="dd/MM/yyyy" />
WEB-INF/custom.tld file
<?xml version="1.0" encoding="UTF-8"?>
<tag ib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">
<tag>
<description>
FormatDate with java8 type
</description>
<name>formatDate</name>
<tag-class>com.custom.tag.FormatDateTag</tag-class>
<body-content>empty</body-content>
<attribute>
<description>
Date and/or time to be formatted.
</description>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>
Custom formatting style for dates and times.
</description>
<name>pattern</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
Then the java class tag file
public class FormatDateTag extends TagSupport {
protected Temporal value;
protected String pattern;
private String var;
private int scope;
public FormatDateTag()
{
super ();
init ();
}
private void init()
{
this.pattern = this.var = null;
this.value = null;
this.scope = PageContext.PAGE_SCOPE;
}
public void setVar(final String var)
{
this.var = var;
}
public void setScope(final String scope)
{
this.scope = Util.getScope (scope);
}
public void setValue(final Temporal value)
{
this.value = value;
}
public void setPattern(final String pattern)
{
this.pattern = pattern;
}
#Override
public int doEndTag() throws JspException
{
String formatted = null;
if (this.value == null)
{
if (this.var != null)
{
this.pageContext.removeAttribute (this.var, this.scope);
}
return EVAL_PAGE;
}
// Create formatter
if (this.pattern != null)
{
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern (this.pattern);
formatted = formatter.format (this.value);
}
else
{
// no formatting locale available, use Date.toString()
formatted = this.value.toString ();
}
if (this.var != null)
{
this.pageContext.setAttribute (this.var, formatted, this.scope);
}
else
{
try
{
this.pageContext.getOut ().print (formatted);
}
catch (final IOException ioe)
{
throw new JspTagException (ioe.toString (), ioe);
}
}
return EVAL_PAGE;
}
#Override
public void release()
{
init ();
}
}
I wanted to avoid changing all the places where <fmt:formatDate/> where used, so I created the following two classes in stead:
First, a converter to convert (some of) the java.time classes. It checks that java.util.Date is the target type, if not, it does nothing. It supports source time as java.util.Date (including java.sql.Timestamp and java.sql.Date), LocalDate, LocalDateTime, ZonedDateTime, Instant or Long (time in millis).
package com.example.elresolvers;
import javax.el.ELContext;
import javax.el.TypeConverter;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
#SuppressWarnings("UseOfObsoleteDateTimeApi")
public class DateFromJavaTimeResolver extends TypeConverter {
#Override
public Object convertToType(ELContext context, Object obj, Class<?> type) {
Date date = null;
if (Date.class.isAssignableFrom(type)) {
if (obj instanceof Date) {
date = (Date) obj;
} else {
ZonedDateTime zdt = null;
if (obj instanceof LocalDate) {
zdt = ((LocalDate) obj).atStartOfDay(ZoneId.systemDefault());
} else if (obj instanceof LocalDateTime) {
zdt = ((LocalDateTime) obj).atZone(ZoneId.systemDefault());
} else if (obj instanceof ZonedDateTime) {
zdt = (ZonedDateTime) obj;
} else if (obj instanceof Instant) {
date = Date.from((Instant) obj);
} else if (obj instanceof Long) {
date = new Date((Long) obj);
}
if (zdt != null) {
date = Date.from(zdt.toInstant());
}
}
context.setPropertyResolved(date != null);
}
return date;
}
}
Next, a ServletContextListener class to register the converter for use with JSP:
package com.example.web;
import com.example.elresolvers.DateFromJavaTimeResolver;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.jsp.JspApplicationContext;
import javax.servlet.jsp.JspFactory;
public class JspElResolverInitListener implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext servletContext = sce.getServletContext();
JspApplicationContext context = JspFactory.getDefaultFactory().getJspApplicationContext(servletContext);
context.addELResolver(new DateFromJavaTimeResolver());
}
#Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
Finally, an entry in web.xml (if you are not using annotations or other means):
<listener>
<listener-class>com.example.web.JspElResolverInitListener</listener-class>
</listener>
Java:
public class DateTimeUtil {
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("dd.MM.yyyy");
public static String toString(LocalDateTime ldt) {
return ldt.format(DATE_FORMATTER);
}
JSP:
<%# page import="ru.javaops.topjava.util.DateTimeUtil" %>
...
<%=DateTimeUtil.toString(std.getDatum())%>

Using java.time.LocalDate with JSTL <fmt:formatDate> action

I haven't been able to figure out how to display a java.time.LocalDate value in a JSP.
In my JSP, I have this:
<fmt:formatDate value="${std.datum}" type="date" pattern="dd.MM.yyyy" var="stdDatum" />
The std.datum is of type java.time.LocalDate. When rendering the JSP I get this exception:
javax.el.ELException:
Cannot convert 2015-02-14 of type class
java.time.LocalDate to class java.util.Date
I'm assuming it's the conversion?
So is it possible to format an instance of LocalDate class with <fmr:formatDate> action?
I'm assuming it's the conversion?
Yes, it's a conversion related exception.
Solution
You could first use the <fmt:parseDate> action from the JSTL's "I18n capable formatting tag library" to do the conversion and then do the formatting with the <fmt:formatDate> action.
Here is an example:
<fmt:parseDate value="${std.datum}" type="date" pattern="yyyy-MM-dd" var="parsedDate" />
<fmt:formatDate value="${parsedDate}" type="date" pattern="dd.MM.yyyy" var="stdDatum" />
This solution is also presented right in the "JavaServer Pages™ Standard Tag Library (JSTL)" specification version 1.2 (see page 109).
This is an old question, but i find it is very best to do a custom tld in this case: without any double conversion to and from String.
Do your own tld file, then override the FormatDate class. Finally, declare your own custom prefix and use custom:formatDate instead of fmt:formatDate.
here is a simplified version
usage in JSP:
<%# taglib uri="/WEB-INF/custom" prefix="custom" %>
...
<custom:formatDate value="${std.datum}" pattern="dd/MM/yyyy" />
WEB-INF/custom.tld file
<?xml version="1.0" encoding="UTF-8"?>
<tag ib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">
<tag>
<description>
FormatDate with java8 type
</description>
<name>formatDate</name>
<tag-class>com.custom.tag.FormatDateTag</tag-class>
<body-content>empty</body-content>
<attribute>
<description>
Date and/or time to be formatted.
</description>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>
Custom formatting style for dates and times.
</description>
<name>pattern</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
Then the java class tag file
public class FormatDateTag extends TagSupport {
protected Temporal value;
protected String pattern;
private String var;
private int scope;
public FormatDateTag()
{
super ();
init ();
}
private void init()
{
this.pattern = this.var = null;
this.value = null;
this.scope = PageContext.PAGE_SCOPE;
}
public void setVar(final String var)
{
this.var = var;
}
public void setScope(final String scope)
{
this.scope = Util.getScope (scope);
}
public void setValue(final Temporal value)
{
this.value = value;
}
public void setPattern(final String pattern)
{
this.pattern = pattern;
}
#Override
public int doEndTag() throws JspException
{
String formatted = null;
if (this.value == null)
{
if (this.var != null)
{
this.pageContext.removeAttribute (this.var, this.scope);
}
return EVAL_PAGE;
}
// Create formatter
if (this.pattern != null)
{
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern (this.pattern);
formatted = formatter.format (this.value);
}
else
{
// no formatting locale available, use Date.toString()
formatted = this.value.toString ();
}
if (this.var != null)
{
this.pageContext.setAttribute (this.var, formatted, this.scope);
}
else
{
try
{
this.pageContext.getOut ().print (formatted);
}
catch (final IOException ioe)
{
throw new JspTagException (ioe.toString (), ioe);
}
}
return EVAL_PAGE;
}
#Override
public void release()
{
init ();
}
}
I wanted to avoid changing all the places where <fmt:formatDate/> where used, so I created the following two classes in stead:
First, a converter to convert (some of) the java.time classes. It checks that java.util.Date is the target type, if not, it does nothing. It supports source time as java.util.Date (including java.sql.Timestamp and java.sql.Date), LocalDate, LocalDateTime, ZonedDateTime, Instant or Long (time in millis).
package com.example.elresolvers;
import javax.el.ELContext;
import javax.el.TypeConverter;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
#SuppressWarnings("UseOfObsoleteDateTimeApi")
public class DateFromJavaTimeResolver extends TypeConverter {
#Override
public Object convertToType(ELContext context, Object obj, Class<?> type) {
Date date = null;
if (Date.class.isAssignableFrom(type)) {
if (obj instanceof Date) {
date = (Date) obj;
} else {
ZonedDateTime zdt = null;
if (obj instanceof LocalDate) {
zdt = ((LocalDate) obj).atStartOfDay(ZoneId.systemDefault());
} else if (obj instanceof LocalDateTime) {
zdt = ((LocalDateTime) obj).atZone(ZoneId.systemDefault());
} else if (obj instanceof ZonedDateTime) {
zdt = (ZonedDateTime) obj;
} else if (obj instanceof Instant) {
date = Date.from((Instant) obj);
} else if (obj instanceof Long) {
date = new Date((Long) obj);
}
if (zdt != null) {
date = Date.from(zdt.toInstant());
}
}
context.setPropertyResolved(date != null);
}
return date;
}
}
Next, a ServletContextListener class to register the converter for use with JSP:
package com.example.web;
import com.example.elresolvers.DateFromJavaTimeResolver;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.jsp.JspApplicationContext;
import javax.servlet.jsp.JspFactory;
public class JspElResolverInitListener implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext servletContext = sce.getServletContext();
JspApplicationContext context = JspFactory.getDefaultFactory().getJspApplicationContext(servletContext);
context.addELResolver(new DateFromJavaTimeResolver());
}
#Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
Finally, an entry in web.xml (if you are not using annotations or other means):
<listener>
<listener-class>com.example.web.JspElResolverInitListener</listener-class>
</listener>
Java:
public class DateTimeUtil {
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("dd.MM.yyyy");
public static String toString(LocalDateTime ldt) {
return ldt.format(DATE_FORMATTER);
}
JSP:
<%# page import="ru.javaops.topjava.util.DateTimeUtil" %>
...
<%=DateTimeUtil.toString(std.getDatum())%>

How to tell Apache CXF to use java.util.Date in Spring Configuration

I am Using CXF to host web services in a Spring context, which makes JAX-WS the default binding. And I'm using Java-First, which means annotated endpoint interfaces and classes.
Since default binding for JAX-WS uses XMLGregorianCalendar class for dates, when I call my web service passing a java.util.Date it is converted to XMLGregorianCalendar on the server.
There are many posts and documentation on how to change this to bind date values to java.util.Date, but all are related to wsdl2java tool, such as:
<jaxws:bindings wsdlLocation="YOUR_WSDL_LOCATION"
xmlns:jaxws="http://java.sun.com/xml/ns/jaxws"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
<jaxws:bindings node="wsdl:definitions/wsdl:types/xs:schema[#targetNamespace='THE_NAMESPACE_OF_YOUR_SCHEMA']">
<jxb:globalBindings xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<jxb:javaType name="java.util.Date" xmlType="xs:dateTime"
parseMethod="org.apache.cxf.tools.common.DataTypeAdapter.parseDateTime"
printMethod="org.apache.cxf.tools.common.DataTypeAdapter.printDateTime"/>
</jxb:globalBindings>
</jaxws:bindings>
</jaxws:bindings>
Since I'm using Spring, I'm looking for a way to do this in Spring context configuration files (or CXF configuration files). A snippet of my file:
<jaxws:endpoint id="jaxwsDocumentGroupWsEndpoint" implementor="#documentGroupWsEndpoint" address="/documentGroup">
<!-- SOMETHING TO WRITE HERE TO TELL CXF TO USE java.util.Date ??? -->
</jaxws:endpoint>
The solution for your problem is hidden into class generation.
You should generate your classes with the following binding:
<jaxb:globalBindings generateMixedExtensions="true">
<jaxb:javaType
name="java.util.Calendar"
xmlType="xs:dateTime"
parseMethod="com.test.DataTypeBinder.unmarshalDateTime"
printMethod="com.test.DataTypeBinder.marshalDateTime" />
</jaxb:globalBindings>
And include in your class path the following class:
public class DataTypeBinder {
private static DateFormat dateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private static DateFormat date = new SimpleDateFormat("yyyy-MM-dd");
public static Calendar unmarshalDate(String value) {
if (value == null || value.length() == 0) {
return null;
}
Date d = null;
try {
d = date.parse(value);
} catch (Exception e) {
e.printStackTrace();
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(d);
return c;
}
public static String marshalDate(Calendar value) {
if (value == null) {
return null;
}
return date.format(value.getTime());
}
public static Calendar unmarshalDateTime(String value) {
if (value == null || value.length() == 0) {
return null;
}
Date d = null;
try {
d = dateTime.parse(value);
} catch (Exception e) {
e.printStackTrace();
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(d);
return c;
}
}
Then JAXB is going to include in your generated classes the following type declaration:
#XmlElement(type = String.class)
#XmlJavaTypeAdapter(Adapter1 .class)
#XmlSchemaType(name = "dateTime")
protected Calendar transactionDate;

Categories