mirror of
https://github.com/scm-manager/scm-manager.git
synced 2026-06-15 23:00:47 +02:00
added jaxb adapter for instant objects
This commit is contained in:
25
scm-core/src/main/java/sonia/scm/xml/XmlInstantAdapter.java
Normal file
25
scm-core/src/main/java/sonia/scm/xml/XmlInstantAdapter.java
Normal file
@@ -0,0 +1,25 @@
|
||||
package sonia.scm.xml;
|
||||
|
||||
import javax.xml.bind.annotation.adapters.XmlAdapter;
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.TemporalAccessor;
|
||||
|
||||
/**
|
||||
* JAXB adapter for {@link Instant} objects.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
public class XmlInstantAdapter extends XmlAdapter<String, Instant> {
|
||||
|
||||
@Override
|
||||
public String marshal(Instant instant) {
|
||||
return DateTimeFormatter.ISO_INSTANT.format(instant);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instant unmarshal(String text) {
|
||||
TemporalAccessor parsed = DateTimeFormatter.ISO_INSTANT.parse(text);
|
||||
return Instant.from(parsed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package sonia.scm.xml;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junitpioneer.jupiter.TempDirectory;
|
||||
|
||||
import javax.xml.bind.JAXB;
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@ExtendWith(TempDirectory.class)
|
||||
class XmlInstantAdapterTest {
|
||||
|
||||
@Test
|
||||
void shouldMarshalAndUnmarshalInstant(@TempDirectory.TempDir Path tempDirectory) {
|
||||
Path path = tempDirectory.resolve("instant.xml");
|
||||
|
||||
Instant instant = Instant.now();
|
||||
InstantObject object = new InstantObject(instant);
|
||||
JAXB.marshal(object, path.toFile());
|
||||
|
||||
InstantObject unmarshaled = JAXB.unmarshal(path.toFile(), InstantObject.class);
|
||||
assertEquals(instant, unmarshaled.instant);
|
||||
}
|
||||
|
||||
@XmlRootElement(name = "instant-object")
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
public static class InstantObject {
|
||||
|
||||
@XmlJavaTypeAdapter(XmlInstantAdapter.class)
|
||||
private Instant instant;
|
||||
|
||||
public InstantObject() {
|
||||
}
|
||||
|
||||
InstantObject(Instant instant) {
|
||||
this.instant = instant;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user