Merge branch 'BAEL-3283-latest' into BAEL-3283

This commit is contained in:
sandip singh
2019-10-31 23:25:14 +05:30
parent db85c8f275
commit f6c3f9ebcb
20562 changed files with 1643286 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
## JAXB
This module contains articles about JAXB.
### Relevant Articles:
- [Guide to JAXB](https://www.baeldung.com/jaxb)
- [Unmarshalling Dates Using JAXB](https://www.baeldung.com/jaxb-unmarshalling-dates)
+138
View File
@@ -0,0 +1,138 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>jaxb</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jaxb</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>${jaxb.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-core</artifactId>
<version>${jaxb.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>com.sun.istack</groupId>
<artifactId>istack-commons-runtime</artifactId>
<version>${istack-commons-runtime.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>${javax.activation.version}</version>
</dependency>
</dependencies>
<build>
<finalName>jaxb</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>${lifecycle-mapping-plugin.version}</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<versionRange>[${jaxb2-maven-plugin.version},)</versionRange>
<goals>
<goal>schemagen</goal>
<goal>xjc</goal>
</goals>
</pluginExecutionFilter>
<action>
<execute />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<!-- xjc -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>${jaxb2-maven-plugin.version}</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<xjbSources>
<xjbSource>src/main/resources/global.xjb</xjbSource>
</xjbSources>
<sources>
<source>src/main/resources/user.xsd</source>
</sources>
<outputDirectory>${basedir}/src/main/java</outputDirectory>
<clearOutputDir>false</clearOutputDir>
<noGeneratedHeaderComments>true</noGeneratedHeaderComments>
<extension>true</extension>
<generateEpisode>false</generateEpisode>
</configuration>
</plugin>
<!-- schemagen -->
<!-- <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>jaxb2-maven-plugin</artifactId> <version>${jaxb2-maven-plugin.version}</version> <executions> <execution>
<id>schemagen</id> <goals> <goal>schemagen</goal> </goals> </execution> </executions> <configuration> <sources> <source>src/main/java/com/baeldung/jaxb/gen</source> </sources> <outputDirectory>src/main/resources</outputDirectory>
<clearOutputDir>false</clearOutputDir> <transformSchemas> <transformSchema> <uri>http://www.baeldung.com/jaxb/gen</uri> <toPrefix>user</toPrefix> <toFile>gen-schema.xsd</toFile> </transformSchema>
</transformSchemas> </configuration> </plugin> -->
</plugins>
</build>
<properties>
<!-- jaxb -->
<jaxb.version>2.2.11</jaxb.version>
<!-- maven plugins -->
<jaxb2-maven-plugin.version>2.3</jaxb2-maven-plugin.version>
<istack-commons-runtime.version>3.0.2</istack-commons-runtime.version>
<lifecycle-mapping-plugin.version>1.0.0</lifecycle-mapping-plugin.version>
<javax.activation.version>1.1</javax.activation.version>
</properties>
</project>
@@ -0,0 +1,73 @@
package com.baeldung.jaxb;
import java.util.Date;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
@XmlRootElement(name = "book")
@XmlType(propOrder = { "id", "name", "date" })
public class Book {
private Long id;
private String name;
private String author;
private Date date;
@XmlAttribute
public void setId(Long id) {
this.id = id;
}
@XmlElement(name = "title")
public void setName(String name) {
this.name = name;
}
@XmlTransient
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Long getId() {
return id;
}
public String getAuthor() {
return author;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
@@ -0,0 +1,28 @@
package com.baeldung.jaxb;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class DateAdapter extends XmlAdapter<String, Date> {
private static final ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
@Override
public Date unmarshal(String v) throws Exception {
return dateFormat.get().parse(v);
}
@Override
public String marshal(Date v) throws Exception {
return dateFormat.get().format(v);
}
}
@@ -0,0 +1,25 @@
package com.baeldung.jaxb.dateunmarshalling;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.datatype.XMLGregorianCalendar;
@XmlRootElement(name = "book")
public class Book {
@XmlElement(name = "title", required = true)
private String title;
@XmlElement(name = "published", required = true)
private XMLGregorianCalendar published;
public XMLGregorianCalendar getPublished() {
return published;
}
@Override
public String toString() {
return "[title: " + title + "; published: " + published.toString() + "]";
}
}
@@ -0,0 +1,27 @@
package com.baeldung.jaxb.dateunmarshalling;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.Date;
@XmlRootElement(name = "book")
public class BookDateAdapter {
@XmlElement(name = "title", required = true)
private String title;
@XmlElement(name = "published", required = true)
@XmlJavaTypeAdapter(DateAdapter.class)
private Date published;
public Date getPublished() {
return published;
}
@Override
public String toString() {
return "[title: " + title + "; published: " + published.toString() + "]";
}
}
@@ -0,0 +1,27 @@
package com.baeldung.jaxb.dateunmarshalling;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.time.LocalDateTime;
@XmlRootElement(name = "book")
public class BookLocalDateTimeAdapter {
@XmlElement(name = "title", required = true)
private String title;
@XmlElement(name = "published", required = true)
@XmlJavaTypeAdapter(LocalDateTimeAdapter.class)
private LocalDateTime published;
public LocalDateTime getPublished() {
return published;
}
@Override
public String toString() {
return "[title: " + title + "; published: " + published.toString() + "]";
}
}
@@ -0,0 +1,21 @@
package com.baeldung.jaxb.dateunmarshalling;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateAdapter extends XmlAdapter<String, Date> {
private static final String CUSTOM_FORMAT_STRING = "yyyy-MM-dd HH:mm:ss";
@Override
public String marshal(Date v) {
return new SimpleDateFormat(CUSTOM_FORMAT_STRING).format(v);
}
@Override
public Date unmarshal(String v) throws Exception {
return new SimpleDateFormat(CUSTOM_FORMAT_STRING).parse(v);
}
}
@@ -0,0 +1,45 @@
package com.baeldung.jaxb.dateunmarshalling;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.InputStream;
public class JaxbDateUnmarshalling {
public static final String DEFAULT_DATE_UNMARSHALLING_FILE = "default-date-unmarshalling.xml";
public static final String CUSTOM_DATE_UNMARSHALLING_FILE = "custom-date-unmarshalling.xml";
public static Book unmarshalDates(InputStream inputFile) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return (Book) jaxbUnmarshaller.unmarshal(inputFile);
}
public static BookDateAdapter unmarshalDatesUsingCustomXmlAdapter(InputStream inputFile) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(BookDateAdapter.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return (BookDateAdapter) jaxbUnmarshaller.unmarshal(inputFile);
}
public static BookLocalDateTimeAdapter unmarshalDatesUsingJava8(InputStream inputFile) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(BookLocalDateTimeAdapter.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return (BookLocalDateTimeAdapter) jaxbUnmarshaller.unmarshal(inputFile);
}
public static InputStream getInputStream(String file) {
ClassLoader classLoader = JaxbDateUnmarshalling.class.getClassLoader();
return classLoader.getResourceAsStream(file);
}
public static void main(String[] args) throws JAXBException {
Book book = unmarshalDates(getInputStream(DEFAULT_DATE_UNMARSHALLING_FILE));
BookDateAdapter bookDateAdapter = unmarshalDatesUsingCustomXmlAdapter(getInputStream(CUSTOM_DATE_UNMARSHALLING_FILE));
BookLocalDateTimeAdapter bookLocalDateTimeAdapter = unmarshalDatesUsingJava8(getInputStream(CUSTOM_DATE_UNMARSHALLING_FILE));
System.out.println(book);
System.out.println(bookDateAdapter);
System.out.println(bookLocalDateTimeAdapter);
}
}
@@ -0,0 +1,21 @@
package com.baeldung.jaxb.dateunmarshalling;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeAdapter extends XmlAdapter<String, LocalDateTime> {
private DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public String marshal(LocalDateTime dateTime) {
return dateTime.format(dateFormat);
}
@Override
public LocalDateTime unmarshal(String dateTime) {
return LocalDateTime.parse(dateTime, dateFormat);
}
}
@@ -0,0 +1,48 @@
package com.baeldung.jaxb.gen;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the com.baeldung.jaxb.gen package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.jaxb.gen
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link UserRequest }
*
*/
public UserRequest createUserRequest() {
return new UserRequest();
}
/**
* Create an instance of {@link UserResponse }
*
*/
public UserResponse createUserResponse() {
return new UserResponse();
}
}
@@ -0,0 +1,87 @@
package com.baeldung.jaxb.gen;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for UserRequest complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="UserRequest"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/&gt;
* &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/&gt;
* &lt;/sequence&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "UserRequest", propOrder = {
"id",
"name"
})
@XmlRootElement(name = "userRequest")
public class UserRequest
implements Serializable
{
private final static long serialVersionUID = -1L;
protected int id;
@XmlElement(required = true)
protected String name;
/**
* Gets the value of the id property.
*
*/
public int getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(int value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
}
@@ -0,0 +1,149 @@
package com.baeldung.jaxb.gen;
import java.io.Serializable;
import java.util.Calendar;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.w3._2001.xmlschema.Adapter1;
/**
* <p>Java class for UserResponse complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="UserResponse"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/&gt;
* &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/&gt;
* &lt;element name="gender" type="{http://www.w3.org/2001/XMLSchema}string"/&gt;
* &lt;element name="created" type="{http://www.w3.org/2001/XMLSchema}dateTime"/&gt;
* &lt;/sequence&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "UserResponse", propOrder = {
"id",
"name",
"gender",
"created"
})
@XmlRootElement(name = "userResponse")
public class UserResponse
implements Serializable
{
private final static long serialVersionUID = -1L;
protected int id;
@XmlElement(required = true)
protected String name;
@XmlElement(required = true)
protected String gender;
@XmlElement(required = true, type = String.class)
@XmlJavaTypeAdapter(Adapter1 .class)
@XmlSchemaType(name = "dateTime")
protected Calendar created;
/**
* Gets the value of the id property.
*
*/
public int getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(int value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the gender property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGender() {
return gender;
}
/**
* Sets the value of the gender property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGender(String value) {
this.gender = value;
}
/**
* Gets the value of the created property.
*
* @return
* possible object is
* {@link String }
*
*/
public Calendar getCreated() {
return created;
}
/**
* Sets the value of the created property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCreated(Calendar value) {
this.created = value;
}
}
@@ -0,0 +1,2 @@
@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/jaxb/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.baeldung.jaxb.gen;
@@ -0,0 +1,23 @@
package org.w3._2001.xmlschema;
import java.util.Calendar;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class Adapter1
extends XmlAdapter<String, Calendar>
{
public Calendar unmarshal(String value) {
return (javax.xml.bind.DatatypeConverter.parseDateTime(value));
}
public String marshal(Calendar value) {
if (value == null) {
return null;
}
return (javax.xml.bind.DatatypeConverter.printDateTime(value));
}
}
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<book>
<title>Book1</title>
<published>1979-11-28 02:31:32</published>
</book>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<book>
<title>Book1</title>
<published>1979-11-28T02:31:32</published>
</book>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxb:bindings version="2.0" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" xmlns:xs="http://www.w3.org/2001/XMLSchema"
jaxb:extensionBindingPrefixes="xjc">
<jaxb:globalBindings>
<xjc:simple />
<xjc:serializable uid="-1" />
<jaxb:javaType name="java.util.Calendar" xmlType="xs:dateTime"
parseMethod="javax.xml.bind.DatatypeConverter.parseDateTime"
printMethod="javax.xml.bind.DatatypeConverter.printDateTime" />
</jaxb:globalBindings>
</jaxb:bindings>
@@ -0,0 +1,9 @@
# Root logger
log4j.rootLogger=INFO, file, stdout
# Write to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
+19
View File
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
+23
View File
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.baeldung.com/jaxb/gen"
xmlns:userns="http://www.baeldung.com/jaxb/gen" elementFormDefault="qualified">
<element name="userRequest" type="userns:UserRequest"></element>
<element name="userResponse" type="userns:UserResponse"></element>
<complexType name="UserRequest">
<sequence>
<element name="id" type="int" />
<element name="name" type="string" />
</sequence>
</complexType>
<complexType name="UserResponse">
<sequence>
<element name="id" type="int" />
<element name="name" type="string" />
<element name="gender" type="string" />
<element name="created" type="dateTime" />
</sequence>
</complexType>
</schema>
@@ -0,0 +1,52 @@
package com.baeldung.jaxb.dateunmarshalling;
import org.junit.Test;
import javax.xml.bind.JAXBException;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import static org.junit.Assert.assertEquals;
public class JaxbDateUnmarshallingUnitTest {
@Test
public void whenUnmarshalDatesIsCalled_ThenCorrectDateIsReturned() throws JAXBException, DatatypeConfigurationException {
InputStream inputStream = JaxbDateUnmarshalling.getInputStream(JaxbDateUnmarshalling.DEFAULT_DATE_UNMARSHALLING_FILE);
XMLGregorianCalendar expected = DatatypeFactory.newInstance().newXMLGregorianCalendar("1979-11-28T02:31:32");
Book book = JaxbDateUnmarshalling.unmarshalDates(inputStream);
assertEquals(expected, book.getPublished());
}
@Test
public void whenUnmarshalDatesUsingCustomXmlAdapterIsCalled_ThenCorrectDateIsReturned() throws JAXBException, ParseException {
InputStream inputStream = JaxbDateUnmarshalling.getInputStream(JaxbDateUnmarshalling.CUSTOM_DATE_UNMARSHALLING_FILE);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date expected = format.parse("1979-11-28 02:31:32");
BookDateAdapter book = JaxbDateUnmarshalling.unmarshalDatesUsingCustomXmlAdapter(inputStream);
assertEquals(expected, book.getPublished());
}
@Test
public void whenUnmarshalDatesUsingJava8IsCalled_ThenCorrectDateIsReturned() throws JAXBException {
InputStream inputStream = JaxbDateUnmarshalling.getInputStream(JaxbDateUnmarshalling.CUSTOM_DATE_UNMARSHALLING_FILE);
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime expected = LocalDateTime.parse("1979-11-28 02:31:32", dateFormat);
BookLocalDateTimeAdapter book = JaxbDateUnmarshalling.unmarshalDatesUsingJava8(inputStream);
assertEquals(expected, book.getPublished());
}
}
@@ -0,0 +1,57 @@
package com.baeldung.jaxb.test;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import java.util.TimeZone;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import com.baeldung.jaxb.Book;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class JaxbIntegrationTest {
private Book book;
private JAXBContext context;
@Before
public void before() throws JAXBException {
book = new Book();
book.setId(1L);
book.setName("Book1");
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
book.setDate(new Date(1481909329718L));
context = JAXBContext.newInstance(Book.class);
}
@Test
public void marshal() throws JAXBException, IOException {
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(book, new File(this.getClass().getResource("/").getPath() + "/book.xml"));
File sampleBookFile = new File(this.getClass().getResource("/sample_book.xml").getFile());
File bookFile = new File(this.getClass().getResource("/book.xml").getFile());
String sampleBookXML = FileUtils.readFileToString(sampleBookFile, "UTF-8");
String marshallerBookXML = FileUtils.readFileToString(bookFile, "UTF-8");
Assert.assertEquals(sampleBookXML.replace("\r", "").replace("\n", ""), marshallerBookXML.replace("\r", "").replace("\n", ""));
}
@Test
public void unMashal() throws JAXBException, IOException {
Unmarshaller unmarshaller = context.createUnmarshaller();
String bookFile = this.getClass().getResource("/book.xml").getFile();
Book unMarshallerbook = (Book) unmarshaller.unmarshal(new FileReader(bookFile));
Assert.assertEquals(book, unMarshallerbook);
}
}
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book id="1">
<title>Book1</title>
<date>2016-12-16T17:28:49.718Z</date>
</book>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book id="1">
<title>Book1</title>
<date>2016-12-16T17:28:49.718Z</date>
</book>