Package list libxstream-java / e1a339d
New upstream version 1.4.10 Emmanuel Bourg 4 years ago
121 changed file(s) with 7028 addition(s) and 2313 deletion(s). Raw diff Collapse all Expand all
00 language: java
1 sudo: false
12 jdk:
23 - oraclejdk8
34 - oraclejdk7
45 - openjdk6
56 install: true
6 script: "mvn -V -B -e clean package"
7 script:
8 if ( `javac -version 2>&1 | grep '1\.8\.0' > /dev/null` ); then
9 mkdir -p xstream/profiles/coveralls;
10 mkdir -p xstream-hibernate/profiles/coveralls;
11 mvn -V -B -e clean package cobertura:cobertura coveralls:report;
12 else
13 mvn -V -B -e clean package;
14 fi
715 cache:
816 directories:
917 - $HOME/.m2
0 For Java 6 or higher build with Maven 3.2.5 or higher
0 For Java 7, 8, or 9 build with Maven 3.3.9 or higher
1 For Java 6 or higher build with Maven 3.2.5
12 For Java 5 build with Maven 3.0.5
23 For Java 1.4 build with Maven 2.0.11
3
4 Before building:
54
65 To build:
76
0 [![Build Status](https://travis-ci.org/x-stream/xstream.svg?branch=v-1.4.x)](https://travis-ci.org/x-stream/xstream)
1 ----
0 master: [![Build Status](https://travis-ci.org/x-stream/xstream.svg?branch=master)](https://travis-ci.org/x-stream/xstream) [![Coverage Status](https://coveralls.io/repos/github/x-stream/xstream/badge.svg?branch=master)](https://coveralls.io/github/x-stream/xstream?branch=master)
1 v-1.4.x: [![Build Status](https://travis-ci.org/x-stream/xstream.svg?branch=v-1.4.x)](https://travis-ci.org/x-stream/xstream) [![Coverage Status](https://coveralls.io/repos/github/x-stream/xstream/badge.svg?branch=v-1.4.x)](https://coveralls.io/github/x-stream/xstream?branch=v-1.4.x)
2
3 - - - -
24 # XStream
35 _Java to XML Serialization, and back again_
46
00 <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/maven-v4_0_0.xsd">
11 <!--
22 Copyright (C) 2006 Joe Walnes.
3 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2015, 2016 XStream committers.
3 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2015, 2016, 2017 XStream committers.
44 All rights reserved.
55
66 The software in this package is published under the terms of the BSD
1313 <groupId>com.thoughtworks.xstream</groupId>
1414 <artifactId>xstream-parent</artifactId>
1515 <packaging>pom</packaging>
16 <version>1.4.9</version>
16 <version>1.4.10</version>
1717 <name>XStream Parent</name>
1818 <url>http://x-stream.github.io</url>
1919 <description>
3838 <profile>
3939 <id>jdk19</id>
4040 <activation>
41 <jdk>1.9</jdk>
41 <jdk>9</jdk>
4242 </activation>
4343 <properties>
4444 <version.java.source>1.6</version.java.source>
5252 </activation>
5353 <properties>
5454 <javadoc.xdoclint>-Xdoclint:-missing</javadoc.xdoclint>
55 <version.plugin.felix.bundle>2.5.4</version.plugin.felix.bundle>
56 </properties>
57 </profile>
58 <profile>
59 <id>jdk16</id>
60 <activation>
61 <jdk>1.6</jdk>
62 </activation>
63 <properties>
64 <version.org.openjdk.jmh>1.16</version.org.openjdk.jmh>
5565 </properties>
5666 </profile>
5767 <profile>
204214 </plugins>
205215 </build>
206216 </profile>
217 <profile>
218 <id>coveralls</id>
219 <activation>
220 <file>
221 <exists>profiles/coveralls</exists>
222 </file>
223 </activation>
224 <build>
225 <plugins>
226 <plugin>
227 <groupId>org.codehaus.mojo</groupId>
228 <artifactId>cobertura-maven-plugin</artifactId>
229 <configuration>
230 <formats>
231 <format>xml</format>
232 </formats>
233 <aggregate>true</aggregate>
234 </configuration>
235 </plugin>
236 <plugin>
237 <groupId>org.eluder.coveralls</groupId>
238 <artifactId>coveralls-maven-plugin</artifactId>
239 </plugin>
240 </plugins>
241 </build>
242 </profile>
207243 </profiles>
208244
209245 <modules>
268304 <dependency>
269305 <groupId>com.thoughtworks.xstream</groupId>
270306 <artifactId>xstream</artifactId>
271 <version>1.4.9</version>
307 <version>1.4.10</version>
272308 </dependency>
273309 <dependency>
274310 <groupId>com.thoughtworks.xstream</groupId>
275311 <artifactId>xstream</artifactId>
276 <version>1.4.9</version>
312 <version>1.4.10</version>
277313 <classifier>tests</classifier>
278314 <type>test-jar</type>
279315 <scope>test</scope>
281317 <dependency>
282318 <groupId>com.thoughtworks.xstream</groupId>
283319 <artifactId>xstream</artifactId>
284 <version>1.4.9</version>
320 <version>1.4.10</version>
285321 <classifier>javadoc</classifier>
286322 <scope>provided</scope>
287323 </dependency>
288324 <dependency>
289325 <groupId>com.thoughtworks.xstream</groupId>
290326 <artifactId>xstream-hibernate</artifactId>
291 <version>1.4.9</version>
327 <version>1.4.10</version>
292328 </dependency>
293329 <dependency>
294330 <groupId>com.thoughtworks.xstream</groupId>
295331 <artifactId>xstream-hibernate</artifactId>
296 <version>1.4.9</version>
332 <version>1.4.10</version>
297333 <classifier>javadoc</classifier>
298334 <scope>provided</scope>
299335 </dependency>
300336 <dependency>
301337 <groupId>com.thoughtworks.xstream</groupId>
302338 <artifactId>xstream-jmh</artifactId>
303 <version>1.4.9</version>
339 <version>1.4.10</version>
304340 </dependency>
305341 <dependency>
306342 <groupId>com.thoughtworks.xstream</groupId>
307343 <artifactId>xstream-jmh</artifactId>
308 <version>1.4.9</version>
344 <version>1.4.10</version>
309345 <classifier>javadoc</classifier>
310346 <scope>provided</scope>
311347 </dependency>
312348 <dependency>
313349 <groupId>com.thoughtworks.xstream</groupId>
314350 <artifactId>xstream-benchmark</artifactId>
315 <version>1.4.9</version>
351 <version>1.4.10</version>
316352 </dependency>
317353 <dependency>
318354 <groupId>com.thoughtworks.xstream</groupId>
319355 <artifactId>xstream-benchmark</artifactId>
320 <version>1.4.9</version>
356 <version>1.4.10</version>
321357 <classifier>javadoc</classifier>
322358 <scope>provided</scope>
323359 </dependency>
749785 <artifactId>maven-surefire-plugin</artifactId>
750786 <version>${version.plugin.maven.surefire}</version>
751787 <configuration>
788 <argLine>${surefire.argline}</argLine>
752789 <forkMode>once</forkMode>
753790 <printSummary>true</printSummary>
754791 <useFile>false</useFile>
817854 </manifest>
818855 </archive>
819856 </configuration>
857 </plugin>
858 <plugin>
859 <groupId>org.eluder.coveralls</groupId>
860 <artifactId>coveralls-maven-plugin</artifactId>
861 <version>${version.plugin.eluder.coveralls}</version>
820862 </plugin>
821863 </plugins>
822864 </pluginManagement>
903945 <version.plugin.maven.source>2.1.2</version.plugin.maven.source>
904946 <version.plugin.maven.surefire>2.4.3</version.plugin.maven.surefire>
905947 <version.plugin.mojo.build-helper>1.5</version.plugin.mojo.build-helper>
906 <version.plugin.mojo.cobertura>2.0</version.plugin.mojo.cobertura>
948 <version.plugin.mojo.cobertura>2.7</version.plugin.mojo.cobertura>
907949 <version.plugin.mojo.jxr>2.0-beta-1</version.plugin.mojo.jxr>
950 <version.plugin.eluder.coveralls>4.2.0</version.plugin.eluder.coveralls>
908951
909952 <version.org.apache.maven.wagon.webdev>1.0-beta-2</version.org.apache.maven.wagon.webdev>
910953
928971 <version.org.jdom>1.1.3</version.org.jdom>
929972 <version.org.jdom2>2.0.5</version.org.jdom2>
930973 <version.org.json>20080701</version.org.json>
931 <version.org.openjdk.jmh>1.11.1</version.org.openjdk.jmh>
974 <version.org.openjdk.jmh>1.19</version.org.openjdk.jmh>
932975 <version.org.slf4j>1.6.1</version.org.slf4j>
933976 <version.oro>2.0.8</version.oro>
934977 <version.stax>1.2.0</version.stax>
942985 <link.javadoc.javase>http://docs.oracle.com/javase/8/docs/api/</link.javadoc.javase>
943986
944987 <javadoc.xdoclint />
988 <surefire.argline />
945989 </properties>
946990 </project>
00 <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/maven-v4_0_0.xsd">
11 <!--
22 Copyright (C) 2006 Joe Walnes.
3 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 XStream committers.
3 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 XStream committers.
44 All rights reserved.
55
66 The software in this package is published under the terms of the BSD
1313 <parent>
1414 <groupId>com.thoughtworks.xstream</groupId>
1515 <artifactId>xstream-parent</artifactId>
16 <version>1.4.9</version>
16 <version>1.4.10</version>
1717 </parent>
1818 <artifactId>xstream</artifactId>
1919 <packaging>jar</packaging>
205205
206206 <profiles>
207207 <profile>
208 <id>jdk18ge</id>
208 <id>jdk19-ge</id>
209 <activation>
210 <jdk>[9,)</jdk>
211 </activation>
212 <properties>
213 <surefire.argline>--add-modules java.activation --permit-illegal-access</surefire.argline>
214 </properties>
215 </profile>
216 <profile>
217 <id>jdk18-ge</id>
209218 <activation>
210219 <jdk>[1.8,)</jdk>
211220 </activation>
220229 </compilerArgs>
221230 <excludes>
222231 <exclude>**/Lambda**</exclude>
232 <exclude>**/time/**</exclude>
233 <exclude>**/ISO8601JavaTimeConverter.java</exclude>
223234 </excludes>
224235 <testExcludes>
225236 <exclude>**/Lambda**</exclude>
237 <exclude>**/*18TypesTest.java</exclude>
226238 </testExcludes>
227239 </configuration>
228240 <executions>
233245 <target>1.8</target>
234246 <excludes>
235247 <exclude>foo</exclude>
248 <exclude>foo</exclude>
249 <exclude>foo</exclude>
236250 </excludes>
237251 <testExcludes>
252 <exclude>foo</exclude>
238253 <exclude>foo</exclude>
239254 </testExcludes>
240255 </configuration>
245260 </execution>
246261 </executions>
247262 </plugin>
263 </plugins>
264 </build>
265 </profile>
266 <profile>
267 <id>jdk18</id>
268 <activation>
269 <jdk>1.8</jdk>
270 </activation>
271 <build>
272 <plugins>
248273 <plugin>
249274 <groupId>org.apache.maven.plugins</groupId>
250275 <artifactId>maven-javadoc-plugin</artifactId>
251276 <configuration>
277 <source>1.8</source>
252278 <excludePackageNames>com.thoughtworks.xstream.core.util</excludePackageNames>
253279 </configuration>
254280 </plugin>
264290 <excludePackageNames>com.thoughtworks.xstream.core.util</excludePackageNames>
265291 <additionalparam>${javadoc.xdoclint}</additionalparam>
266292 <detectJavaApiLink>false</detectJavaApiLink>
267 <source>${version.java.source}</source>
293 <source>1.8</source>
268294 <links>
269295 <link>${link.javadoc.javase}</link>
270296 </links>
289315 </compilerArgs>
290316 <excludes>
291317 <exclude>**/Lambda**</exclude>
318 <exclude>**/time/**</exclude>
319 <exclude>**/ISO8601JavaTimeConverter.java</exclude>
292320 </excludes>
293321 <testExcludes>
294322 <exclude>**/Lambda**</exclude>
323 <exclude>**/*18TypesTest.java</exclude>
295324 </testExcludes>
296325 </configuration>
297326 </plugin>
315344 <excludes>
316345 <exclude>**/Lambda**</exclude>
317346 <exclude>**/extended/PathConverter*</exclude>
347 <exclude>**/time/**</exclude>
348 <exclude>**/ISO8601JavaTimeConverter.java</exclude>
318349 </excludes>
319350 <testExcludes>
320351 <exclude>**/Lambda**</exclude>
352 <exclude>**/extended/*17Test*</exclude>
321353 <exclude>**/acceptance/Extended17TypesTest*</exclude>
322 <exclude>**/extended/*17Test*</exclude>
354 <exclude>**/acceptance/*18TypesTest.java</exclude>
323355 </testExcludes>
324356 </configuration>
325357 </plugin>
383415 <exclude>**/AnnotationMapper*</exclude>
384416 <exclude>**/EnumMapper*</exclude>
385417 <exclude>**/enums/*</exclude>
418 <exclude>**/time/**</exclude>
419 <exclude>**/ISO8601JavaTimeConverter.java</exclude>
386420 <exclude>**/basic/StringBuilder*</exclude>
387421 <exclude>**/basic/UUID*</exclude>
388422 <exclude>**/core/util/Types*</exclude>
401435 <exclude>**/acceptance/Basic15TypesTest*</exclude>
402436 <exclude>**/acceptance/Concurrent15TypesTest*</exclude>
403437 <exclude>**/acceptance/Extended17TypesTest*</exclude>
438 <exclude>**/acceptance/*18TypesTest.java</exclude>
404439 </testExcludes>
405440 </configuration>
406441 </plugin>
00 /*
11 * Copyright (C) 2003, 2004, 2005, 2006 Joe Walnes.
2 * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 XStream Committers.
2 * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 XStream Committers.
33 * All rights reserved.
44 *
55 * The software in this package is published under the terms of the BSD
2525 import java.io.Writer;
2626 import java.lang.reflect.Constructor;
2727 import java.lang.reflect.Field;
28 import java.lang.reflect.InvocationTargetException;
29 import java.lang.reflect.Member;
2830 import java.lang.reflect.Method;
2931 import java.math.BigDecimal;
3032 import java.math.BigInteger;
3133 import java.net.URI;
3234 import java.net.URL;
35 import java.nio.charset.Charset;
36 import java.text.DecimalFormatSymbols;
3337 import java.util.ArrayList;
3438 import java.util.BitSet;
3539 import java.util.Calendar;
40 import java.util.Collection;
3641 import java.util.Collections;
42 import java.util.Currency;
3743 import java.util.Date;
3844 import java.util.GregorianCalendar;
3945 import java.util.HashMap;
4046 import java.util.HashSet;
4147 import java.util.Hashtable;
48 import java.util.Iterator;
4249 import java.util.LinkedList;
4350 import java.util.List;
4451 import java.util.Locale;
4653 import java.util.Properties;
4754 import java.util.Set;
4855 import java.util.SortedSet;
56 import java.util.TimeZone;
4957 import java.util.TreeMap;
5058 import java.util.TreeSet;
5159 import java.util.Vector;
5664 import com.thoughtworks.xstream.converters.ConverterLookup;
5765 import com.thoughtworks.xstream.converters.ConverterRegistry;
5866 import com.thoughtworks.xstream.converters.DataHolder;
67 import com.thoughtworks.xstream.converters.MarshallingContext;
5968 import com.thoughtworks.xstream.converters.SingleValueConverter;
6069 import com.thoughtworks.xstream.converters.SingleValueConverterWrapper;
70 import com.thoughtworks.xstream.converters.UnmarshallingContext;
6171 import com.thoughtworks.xstream.converters.basic.BigDecimalConverter;
6272 import com.thoughtworks.xstream.converters.basic.BigIntegerConverter;
6373 import com.thoughtworks.xstream.converters.basic.BooleanConverter;
128138 import com.thoughtworks.xstream.mapper.DefaultImplementationsMapper;
129139 import com.thoughtworks.xstream.mapper.DefaultMapper;
130140 import com.thoughtworks.xstream.mapper.DynamicProxyMapper;
141 import com.thoughtworks.xstream.mapper.ElementIgnoringMapper;
131142 import com.thoughtworks.xstream.mapper.FieldAliasingMapper;
132143 import com.thoughtworks.xstream.mapper.ImmutableTypesMapper;
133144 import com.thoughtworks.xstream.mapper.ImplicitCollectionMapper;
140151 import com.thoughtworks.xstream.mapper.SystemAttributeAliasingMapper;
141152 import com.thoughtworks.xstream.mapper.XStream11XmlFriendlyMapper;
142153 import com.thoughtworks.xstream.security.AnyTypePermission;
154 import com.thoughtworks.xstream.security.ArrayTypePermission;
143155 import com.thoughtworks.xstream.security.ExplicitTypePermission;
156 import com.thoughtworks.xstream.security.InterfaceTypePermission;
144157 import com.thoughtworks.xstream.security.NoPermission;
145158 import com.thoughtworks.xstream.security.NoTypePermission;
159 import com.thoughtworks.xstream.security.NullPermission;
160 import com.thoughtworks.xstream.security.PrimitiveTypePermission;
146161 import com.thoughtworks.xstream.security.RegExpTypePermission;
147162 import com.thoughtworks.xstream.security.TypeHierarchyPermission;
148163 import com.thoughtworks.xstream.security.TypePermission;
311326 private PackageAliasingMapper packageAliasingMapper;
312327 private ClassAliasingMapper classAliasingMapper;
313328 private FieldAliasingMapper fieldAliasingMapper;
329 private ElementIgnoringMapper elementIgnoringMapper;
314330 private AttributeAliasingMapper attributeAliasingMapper;
315331 private SystemAttributeAliasingMapper systemAttributeAliasingMapper;
316332 private AttributeMapper attributeMapper;
320336 private LocalConversionMapper localConversionMapper;
321337 private SecurityMapper securityMapper;
322338 private AnnotationConfiguration annotationConfiguration;
339
340 private transient boolean insecureWarning;
323341
324342 public static final int NO_REFERENCES = 1001;
325343 public static final int ID_REFERENCES = 1002;
583601 mapper = new DynamicProxyMapper(mapper);
584602 mapper = new PackageAliasingMapper(mapper);
585603 mapper = new ClassAliasingMapper(mapper);
604 mapper = new ElementIgnoringMapper(mapper);
586605 mapper = new FieldAliasingMapper(mapper);
587606 mapper = new AttributeAliasingMapper(mapper);
588607 mapper = new SystemAttributeAliasingMapper(mapper);
589 mapper = new ImplicitCollectionMapper(mapper);
608 mapper = new ImplicitCollectionMapper(mapper, reflectionProvider);
590609 mapper = new OuterClassMapper(mapper);
591610 mapper = new ArrayMapper(mapper);
592611 mapper = new DefaultImplementationsMapper(mapper);
599618 mapper = new LocalConversionMapper(mapper);
600619 mapper = new ImmutableTypesMapper(mapper);
601620 if (JVM.is18()) {
602 mapper =
603 buildMapperDynamically("com.thoughtworks.xstream.mapper.LambdaMapper", new Class[]{Mapper.class},
604 new Object[]{mapper});
621 mapper = buildMapperDynamically("com.thoughtworks.xstream.mapper.LambdaMapper", new Class[]{Mapper.class},
622 new Object[]{mapper});
605623 }
606624 mapper = new SecurityMapper(mapper);
607625 if (JVM.is15()) {
647665 .lookupMapperOfType(PackageAliasingMapper.class);
648666 classAliasingMapper = (ClassAliasingMapper)this.mapper
649667 .lookupMapperOfType(ClassAliasingMapper.class);
668 elementIgnoringMapper = (ElementIgnoringMapper)this.mapper
669 .lookupMapperOfType(ElementIgnoringMapper.class);
650670 fieldAliasingMapper = (FieldAliasingMapper)this.mapper
651671 .lookupMapperOfType(FieldAliasingMapper.class);
652672 attributeMapper = (AttributeMapper)this.mapper
675695 }
676696
677697 addPermission(AnyTypePermission.ANY);
698 insecureWarning = true;
699 }
700
701 /**
702 * Setup the security framework of a XStream instance.
703 * <p>
704 * This method is a pure helper method for XStream 1.4.x. It initializes an XStream instance with a white list of
705 * well-known and simply types of the Java runtime as it is done in XStream 1.5.x by default. This method will do
706 * therefore nothing in XStream 1.5.
707 * </p>
708 *
709 * @param xstream
710 * @since 1.4.10
711 */
712 public static void setupDefaultSecurity(final XStream xstream) {
713 if (xstream.insecureWarning) {
714 xstream.addPermission(NoTypePermission.NONE);
715 xstream.addPermission(NullPermission.NULL);
716 xstream.addPermission(PrimitiveTypePermission.PRIMITIVES);
717 xstream.addPermission(ArrayTypePermission.ARRAYS);
718 xstream.addPermission(InterfaceTypePermission.INTERFACES);
719 xstream.allowTypeHierarchy(Calendar.class);
720 xstream.allowTypeHierarchy(Collection.class);
721 xstream.allowTypeHierarchy(Map.class);
722 xstream.allowTypeHierarchy(Map.Entry.class);
723 xstream.allowTypeHierarchy(Member.class);
724 xstream.allowTypeHierarchy(Number.class);
725 xstream.allowTypeHierarchy(Throwable.class);
726 xstream.allowTypeHierarchy(TimeZone.class);
727
728 Class type = JVM.loadClassForName("java.lang.Enum");
729 if (type != null) {
730 xstream.allowTypeHierarchy(type);
731 }
732 type = JVM.loadClassForName("java.nio.file.Path");
733 if (type != null) {
734 xstream.allowTypeHierarchy(type);
735 }
736
737 final Set types = new HashSet();
738 types.add(BitSet.class);
739 types.add(Charset.class);
740 types.add(Class.class);
741 types.add(Currency.class);
742 types.add(Date.class);
743 types.add(DecimalFormatSymbols.class);
744 types.add(File.class);
745 types.add(Locale.class);
746 types.add(Object.class);
747 types.add(Pattern.class);
748 types.add(StackTraceElement.class);
749 types.add(String.class);
750 types.add(StringBuffer.class);
751 types.add(JVM.loadClassForName("java.lang.StringBuilder"));
752 types.add(URL.class);
753 types.add(URI.class);
754 types.add(JVM.loadClassForName("java.util.UUID"));
755 if (JVM.isSQLAvailable()) {
756 types.add(JVM.loadClassForName("java.sql.Timestamp"));
757 types.add(JVM.loadClassForName("java.sql.Time"));
758 types.add(JVM.loadClassForName("java.sql.Date"));
759 }
760 if (JVM.is18()) {
761 xstream.allowTypeHierarchy(JVM.loadClassForName("java.time.Clock"));
762 types.add(JVM.loadClassForName("java.time.Duration"));
763 types.add(JVM.loadClassForName("java.time.Instant"));
764 types.add(JVM.loadClassForName("java.time.LocalDate"));
765 types.add(JVM.loadClassForName("java.time.LocalDateTime"));
766 types.add(JVM.loadClassForName("java.time.LocalTime"));
767 types.add(JVM.loadClassForName("java.time.MonthDay"));
768 types.add(JVM.loadClassForName("java.time.OffsetDateTime"));
769 types.add(JVM.loadClassForName("java.time.OffsetTime"));
770 types.add(JVM.loadClassForName("java.time.Period"));
771 types.add(JVM.loadClassForName("java.time.Ser"));
772 types.add(JVM.loadClassForName("java.time.Year"));
773 types.add(JVM.loadClassForName("java.time.YearMonth"));
774 types.add(JVM.loadClassForName("java.time.ZonedDateTime"));
775 xstream.allowTypeHierarchy(JVM.loadClassForName("java.time.ZoneId"));
776 types.add(JVM.loadClassForName("java.time.chrono.HijrahDate"));
777 types.add(JVM.loadClassForName("java.time.chrono.JapaneseDate"));
778 types.add(JVM.loadClassForName("java.time.chrono.JapaneseEra"));
779 types.add(JVM.loadClassForName("java.time.chrono.MinguoDate"));
780 types.add(JVM.loadClassForName("java.time.chrono.ThaiBuddhistDate"));
781 types.add(JVM.loadClassForName("java.time.chrono.Ser"));
782 xstream.allowTypeHierarchy(JVM.loadClassForName("java.time.chrono.Chronology"));
783 types.add(JVM.loadClassForName("java.time.temporal.ValueRange"));
784 types.add(JVM.loadClassForName("java.time.temporal.WeekFields"));
785 }
786 types.remove(null);
787
788 final Iterator iter = types.iterator();
789 final Class[] classes = new Class[types.size()];
790 for (int i = 0; i < classes.length; ++i) {
791 classes[i] = (Class)iter.next();
792 }
793 xstream.allowTypes(classes);
794 } else {
795 throw new IllegalArgumentException("Security framework of XStream instance already initialized");
796 }
678797 }
679798
680799 protected void setupAliases() {
734853 alias("awt-color", JVM.loadClassForName("java.awt.Color", false));
735854 alias("awt-font", JVM.loadClassForName("java.awt.Font", false));
736855 alias("awt-text-attribute", JVM.loadClassForName("java.awt.font.TextAttribute"));
737
738 // only available in Java 5 when javax.activation:activation is available on CP
739 Class type = JVM.loadClassForName("javax.activation.ActivationDataFlavor");
740 if (type != null) {
741 alias("activation-data-flavor", type);
742 }
856 }
857
858 Class type = JVM.loadClassForName("javax.activation.ActivationDataFlavor");
859 if (type != null) {
860 alias("activation-data-flavor", type);
743861 }
744862
745863 if (JVM.isSQLAvailable()) {
762880 }
763881
764882 if (JVM.is15()) {
765 aliasDynamically("duration", "javax.xml.datatype.Duration");
883 aliasDynamically("xml-duration", "javax.xml.datatype.Duration");
766884 alias("concurrent-hash-map", JVM.loadClassForName("java.util.concurrent.ConcurrentHashMap"));
767885 alias("enum-set", JVM.loadClassForName("java.util.EnumSet"));
768886 alias("enum-map", JVM.loadClassForName("java.util.EnumMap"));
773891 if (JVM.is17()) {
774892 aliasType("path", JVM.loadClassForName("java.nio.file.Path"));
775893 }
776
894
895 if (JVM.is18()) {
896 alias("fixed-clock", JVM.loadClassForName("java.time.Clock$FixedClock"));
897 alias("offset-clock", JVM.loadClassForName("java.time.Clock$OffsetClock"));
898 alias("system-clock", JVM.loadClassForName("java.time.Clock$SystemClock"));
899 alias("tick-clock", JVM.loadClassForName("java.time.Clock$TickClock"));
900 alias("day-of-week", JVM.loadClassForName("java.time.DayOfWeek"));
901 alias("duration", JVM.loadClassForName("java.time.Duration"));
902 alias("instant", JVM.loadClassForName("java.time.Instant"));
903 alias("local-date", JVM.loadClassForName("java.time.LocalDate"));
904 alias("local-date-time", JVM.loadClassForName("java.time.LocalDateTime"));
905 alias("local-time", JVM.loadClassForName("java.time.LocalTime"));
906 alias("month", JVM.loadClassForName("java.time.Month"));
907 alias("month-day", JVM.loadClassForName("java.time.MonthDay"));
908 alias("offset-date-time", JVM.loadClassForName("java.time.OffsetDateTime"));
909 alias("offset-time", JVM.loadClassForName("java.time.OffsetTime"));
910 alias("period", JVM.loadClassForName("java.time.Period"));
911 alias("year", JVM.loadClassForName("java.time.Year"));
912 alias("year-month", JVM.loadClassForName("java.time.YearMonth"));
913 alias("zoned-date-time", JVM.loadClassForName("java.time.ZonedDateTime"));
914 aliasType("zone-id", JVM.loadClassForName("java.time.ZoneId"));
915 aliasType("chronology", JVM.loadClassForName("java.time.chrono.Chronology"));
916 alias("hijrah-date", JVM.loadClassForName("java.time.chrono.HijrahDate"));
917 alias("hijrah-era", JVM.loadClassForName("java.time.chrono.HijrahEra"));
918 alias("japanese-date", JVM.loadClassForName("java.time.chrono.JapaneseDate"));
919 alias("japanese-era", JVM.loadClassForName("java.time.chrono.JapaneseEra"));
920 alias("minguo-date", JVM.loadClassForName("java.time.chrono.MinguoDate"));
921 alias("minguo-era", JVM.loadClassForName("java.time.chrono.MinguoEra"));
922 alias("thai-buddhist-date", JVM.loadClassForName("java.time.chrono.ThaiBuddhistDate"));
923 alias("thai-buddhist-era", JVM.loadClassForName("java.time.chrono.ThaiBuddhistEra"));
924 alias("chrono-field", JVM.loadClassForName("java.time.temporal.ChronoField"));
925 alias("chrono-unit", JVM.loadClassForName("java.time.temporal.ChronoUnit"));
926 alias("iso-field", JVM.loadClassForName("java.time.temporal.IsoFields$Field"));
927 alias("iso-unit", JVM.loadClassForName("java.time.temporal.IsoFields$Unit"));
928 alias("julian-field", JVM.loadClassForName("java.time.temporal.JulianFields$Field"));
929 alias("temporal-value-range", JVM.loadClassForName("java.time.temporal.ValueRange"));
930 alias("week-fields", JVM.loadClassForName("java.time.temporal.WeekFields"));
931 }
932
777933 if (JVM.loadClassForName("java.lang.invoke.SerializedLambda") != null) {
778934 aliasDynamically("serialized-lambda", "java.lang.invoke.SerializedLambda");
779935 }
804960 registerConverter(
805961 new SerializableConverter(mapper, reflectionProvider, classLoaderReference), PRIORITY_LOW);
806962 registerConverter(new ExternalizableConverter(mapper, classLoaderReference), PRIORITY_LOW);
963 registerConverter(new InternalBlackList(), PRIORITY_LOW);
807964
808965 registerConverter(new NullConverter(), PRIORITY_VERY_HIGH);
809966 registerConverter(new IntConverter(), PRIORITY_NORMAL);
841998 registerConverter(new SqlTimeConverter(), PRIORITY_NORMAL);
842999 registerConverter(new SqlDateConverter(), PRIORITY_NORMAL);
8431000 }
844 registerConverter(
845 new DynamicProxyConverter(mapper, classLoaderReference), PRIORITY_NORMAL);
1001 registerConverter(new DynamicProxyConverter(mapper, classLoaderReference), PRIORITY_NORMAL);
8461002 registerConverter(new JavaClassConverter(classLoaderReference), PRIORITY_NORMAL);
8471003 registerConverter(new JavaMethodConverter(classLoaderReference), PRIORITY_NORMAL);
8481004 registerConverter(new JavaFieldConverter(classLoaderReference), PRIORITY_NORMAL);
1005
8491006 if (JVM.isAWTAvailable()) {
8501007 registerConverter(new FontConverter(mapper), PRIORITY_NORMAL);
8511008 registerConverter(new ColorConverter(), PRIORITY_NORMAL);
9131070 PRIORITY_NORMAL, null, null);
9141071 }
9151072 if (JVM.is18()) {
1073 registerConverterDynamically("com.thoughtworks.xstream.converters.time.ChronologyConverter",
1074 PRIORITY_NORMAL, null, null);
1075 registerConverterDynamically("com.thoughtworks.xstream.converters.time.DurationConverter", PRIORITY_NORMAL,
1076 null, null);
1077 registerConverterDynamically("com.thoughtworks.xstream.converters.time.HijrahDateConverter",
1078 PRIORITY_NORMAL, null, null);
1079 registerConverterDynamically("com.thoughtworks.xstream.converters.time.JapaneseDateConverter",
1080 PRIORITY_NORMAL, null, null);
1081 registerConverterDynamically("com.thoughtworks.xstream.converters.time.JapaneseEraConverter",
1082 PRIORITY_NORMAL, null, null);
1083 registerConverterDynamically("com.thoughtworks.xstream.converters.time.InstantConverter", PRIORITY_NORMAL,
1084 null, null);
1085 registerConverterDynamically("com.thoughtworks.xstream.converters.time.LocalDateConverter", PRIORITY_NORMAL,
1086 null, null);
1087 registerConverterDynamically("com.thoughtworks.xstream.converters.time.LocalDateTimeConverter",
1088 PRIORITY_NORMAL, null, null);
1089 registerConverterDynamically("com.thoughtworks.xstream.converters.time.LocalTimeConverter", PRIORITY_NORMAL,
1090 null, null);
1091 registerConverterDynamically("com.thoughtworks.xstream.converters.time.MinguoDateConverter",
1092 PRIORITY_NORMAL, null, null);
1093 registerConverterDynamically("com.thoughtworks.xstream.converters.time.MonthDayConverter", PRIORITY_NORMAL,
1094 null, null);
1095 registerConverterDynamically("com.thoughtworks.xstream.converters.time.OffsetDateTimeConverter",
1096 PRIORITY_NORMAL, null, null);
1097 registerConverterDynamically("com.thoughtworks.xstream.converters.time.OffsetTimeConverter",
1098 PRIORITY_NORMAL, null, null);
1099 registerConverterDynamically("com.thoughtworks.xstream.converters.time.PeriodConverter", PRIORITY_NORMAL,
1100 null, null);
1101 registerConverterDynamically("com.thoughtworks.xstream.converters.time.SystemClockConverter",
1102 PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper});
1103 registerConverterDynamically("com.thoughtworks.xstream.converters.time.ThaiBuddhistDateConverter",
1104 PRIORITY_NORMAL, null, null);
1105 registerConverterDynamically("com.thoughtworks.xstream.converters.time.ValueRangeConverter",
1106 PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper});
1107 registerConverterDynamically("com.thoughtworks.xstream.converters.time.WeekFieldsConverter",
1108 PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper});
1109 registerConverterDynamically("com.thoughtworks.xstream.converters.time.YearConverter", PRIORITY_NORMAL,
1110 null, null);
1111 registerConverterDynamically("com.thoughtworks.xstream.converters.time.YearMonthConverter", PRIORITY_NORMAL,
1112 null, null);
1113 registerConverterDynamically("com.thoughtworks.xstream.converters.time.ZonedDateTimeConverter",
1114 PRIORITY_NORMAL, null, null);
1115 registerConverterDynamically("com.thoughtworks.xstream.converters.time.ZoneIdConverter", PRIORITY_NORMAL,
1116 null, null);
9161117 registerConverterDynamically("com.thoughtworks.xstream.converters.reflection.LambdaConverter",
9171118 PRIORITY_NORMAL, new Class[]{Mapper.class, ReflectionProvider.class, ClassLoaderReference.class},
9181119 new Object[]{mapper, reflectionProvider, classLoaderReference});
9741175 addImmutableType(File.class, false);
9751176 addImmutableType(Class.class, false);
9761177
1178 if (JVM.is17()) {
1179 Class type = JVM.loadClassForName("java.nio.file.Paths");
1180 if (type != null) {
1181 Method methodGet;
1182 try {
1183 methodGet = type.getDeclaredMethod("get", new Class[] {String.class, String[].class});
1184 if (methodGet != null) {
1185 Object path = methodGet.invoke(null, new Object[]{".", new String[0]});
1186 if (path != null) {
1187 addImmutableType(path.getClass(), false);
1188 }
1189 }
1190 } catch (NoSuchMethodException e) {
1191 } catch (SecurityException e) {
1192 } catch (IllegalAccessException e) {
1193 } catch (InvocationTargetException e) {
1194 }
1195 }
1196 }
1197
9771198 if (JVM.isAWTAvailable()) {
9781199 addImmutableTypeDynamically("java.awt.font.TextAttribute", false);
9791200 }
9921213 addImmutableType(Collections.EMPTY_LIST.getClass(), true);
9931214 addImmutableType(Collections.EMPTY_SET.getClass(), true);
9941215 addImmutableType(Collections.EMPTY_MAP.getClass(), true);
1216
1217 if (JVM.is18()) {
1218 addImmutableTypeDynamically("java.time.Duration", false);
1219 addImmutableTypeDynamically("java.time.Instant", false);
1220 addImmutableTypeDynamically("java.time.LocalDate", false);
1221 addImmutableTypeDynamically("java.time.LocalDateTime", false);
1222 addImmutableTypeDynamically("java.time.LocalTime", false);
1223 addImmutableTypeDynamically("java.time.MonthDay", false);
1224 addImmutableTypeDynamically("java.time.OffsetDateTime", false);
1225 addImmutableTypeDynamically("java.time.OffsetTime", false);
1226 addImmutableTypeDynamically("java.time.Period", false);
1227 addImmutableTypeDynamically("java.time.Year", false);
1228 addImmutableTypeDynamically("java.time.YearMonth", false);
1229 addImmutableTypeDynamically("java.time.ZonedDateTime", false);
1230 addImmutableTypeDynamically("java.time.ZoneId", false);
1231 addImmutableTypeDynamically("java.time.ZoneOffset", false);
1232 addImmutableTypeDynamically("java.time.ZoneRegion", false);
1233 addImmutableTypeDynamically("java.time.chrono.HijrahChronology", false);
1234 addImmutableTypeDynamically("java.time.chrono.HijrahDate", false);
1235 addImmutableTypeDynamically("java.time.chrono.IsoChronology", false);
1236 addImmutableTypeDynamically("java.time.chrono.JapaneseChronology", false);
1237 addImmutableTypeDynamically("java.time.chrono.JapaneseDate", false);
1238 addImmutableTypeDynamically("java.time.chrono.JapaneseEra", false);
1239 addImmutableTypeDynamically("java.time.chrono.MinguoChronology", false);
1240 addImmutableTypeDynamically("java.time.chrono.MinguoDate", false);
1241 addImmutableTypeDynamically("java.time.chrono.ThaiBuddhistChronology", false);
1242 addImmutableTypeDynamically("java.time.chrono.ThaiBuddhistDate", false);
1243 addImmutableTypeDynamically("java.time.temporal.IsoFields$Field", false);
1244 addImmutableTypeDynamically("java.time.temporal.IsoFields$Unit", false);
1245 addImmutableTypeDynamically("java.time.temporal.JulianFields$Field", false);
1246 }
9951247 }
9961248
9971249 private void addImmutableTypeDynamically(String className, boolean isReferenceable) {
12261478 */
12271479 public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) {
12281480 try {
1481 if (insecureWarning) {
1482 insecureWarning = false;
1483 System.err.println("Security framework of XStream not initialized, XStream is probably vulnerable.");
1484 }
12291485 return marshallingStrategy.unmarshal(
12301486 root, reader, dataHolder, converterLookup, mapper);
12311487
17131969 }
17141970
17151971 /**
1716 * Create a DataHolder that can be used to pass data to the converters. The DataHolder is
1717 * provided with a call to {@link #marshal(Object, HierarchicalStreamWriter, DataHolder)} or
1718 * {@link #unmarshal(HierarchicalStreamReader, Object, DataHolder)}.
1972 * Create a DataHolder that can be used to pass data to the converters. The DataHolder is provided with a call to
1973 * {@link #marshal(Object, HierarchicalStreamWriter, DataHolder)},
1974 * {@link #unmarshal(HierarchicalStreamReader, Object, DataHolder)},
1975 * {@link #createObjectInputStream(HierarchicalStreamReader, DataHolder)} or
1976 * {@link #createObjectOutputStream(HierarchicalStreamWriter, String, DataHolder)}.
17191977 *
17201978 * @return a new {@link DataHolder}
17211979 */
18332091 * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
18342092 * @since 1.0.3
18352093 */
1836 public ObjectOutputStream createObjectOutputStream(final HierarchicalStreamWriter writer,
1837 String rootNodeName) throws IOException {
2094 public ObjectOutputStream createObjectOutputStream(final HierarchicalStreamWriter writer, final String rootNodeName)
2095 throws IOException {
2096 return createObjectOutputStream(writer, rootNodeName, null);
2097 }
2098
2099 /**
2100 * Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream.
2101 *
2102 * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
2103 * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
2104 * @since 1.4.10
2105 */
2106 public ObjectOutputStream createObjectOutputStream(final HierarchicalStreamWriter writer, final String rootNodeName,
2107 final DataHolder dataHolder) throws IOException {
18382108 final StatefulWriter statefulWriter = new StatefulWriter(writer);
18392109 statefulWriter.startNode(rootNodeName, null);
18402110 return new CustomObjectOutputStream(new CustomObjectOutputStream.StreamCallback() {
1841 public void writeToStream(Object object) {
1842 marshal(object, statefulWriter);
2111 public void writeToStream(final Object object) {
2112 marshal(object, statefulWriter, dataHolder);
18432113 }
18442114
18452115 public void writeFieldsToStream(Map fields) throws NotActiveException {
18902160 }
18912161
18922162 /**
1893 * Creates an ObjectInputStream that deserializes a stream of objects from a reader using
1894 * XStream. <h3>Example</h3>
1895 *
2163 * Creates an ObjectInputStream that deserializes a stream of objects from a reader using XStream.
2164 * <p>
2165 * It is necessary to call ObjectInputStream.close() when done, otherwise the stream might keep system resources.
2166 * </p>
2167 * <h3>Example</h3>
2168 *
18962169 * <pre>
18972170 * ObjectInputStream in = xstream.createObjectOutputStream(aReader);
18982171 * int a = out.readInt();
19042177 * String)
19052178 * @since 1.0.3
19062179 */
1907 public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader)
1908 throws IOException {
2180 public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader) throws IOException {
2181 return createObjectInputStream(reader, null);
2182 }
2183
2184 /**
2185 * Creates an ObjectInputStream that deserializes a stream of objects from a reader using XStream.
2186 *
2187 * @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
2188 * @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
2189 * @since 1.4.10
2190 */
2191 public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader, final DataHolder dataHolder)
2192 throws IOException {
19092193 return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() {
19102194 public Object readFromStream() throws EOFException {
19112195 if (!reader.hasMoreChildren()) {
19122196 throw new EOFException();
19132197 }
19142198 reader.moveDown();
1915 Object result = unmarshal(reader);
2199 final Object result = unmarshal(reader, dataHolder);
19162200 reader.moveUp();
19172201 return result;
19182202 }
19752259 * declaring type and not necessarily the type that is converted.
19762260 *
19772261 * @since 1.1.3
1978 * @throws InitializationException if no {@link FieldAliasingMapper} is available
2262 * @throws InitializationException if no {@link ElementIgnoringMapper} is available
19792263 */
19802264 public void omitField(Class definedIn, String fieldName) {
1981 if (fieldAliasingMapper == null) {
2265 if (elementIgnoringMapper == null) {
19822266 throw new com.thoughtworks.xstream.InitializationException("No "
1983 + FieldAliasingMapper.class.getName()
2267 + ElementIgnoringMapper.class.getName()
19842268 + " available");
19852269 }
1986 fieldAliasingMapper.omitField(definedIn, fieldName);
2270 elementIgnoringMapper.omitField(definedIn, fieldName);
19872271 }
19882272
19892273 /**
20122296 * @since 1.4.5
20132297 */
20142298 public void ignoreUnknownElements(final Pattern pattern) {
2015 if (fieldAliasingMapper == null) {
2299 if (elementIgnoringMapper == null) {
20162300 throw new com.thoughtworks.xstream.InitializationException("No "
2017 + FieldAliasingMapper.class.getName()
2301 + ElementIgnoringMapper.class.getName()
20182302 + " available");
20192303 }
2020 fieldAliasingMapper.addFieldsToIgnore(pattern);
2304 elementIgnoringMapper.addElementsToIgnore(pattern);
20212305 }
20222306
20232307 /**
20742358 */
20752359 public void addPermission(TypePermission permission) {
20762360 if (securityMapper != null) {
2361 insecureWarning &= permission != NoTypePermission.NONE;
20772362 securityMapper.addPermission(permission);
20782363 }
20792364 }
22472532 super(message);
22482533 }
22492534 }
2535
2536 private class InternalBlackList implements Converter {
2537
2538 public boolean canConvert(final Class type) {
2539 return (type == void.class || type == Void.class)
2540 || (insecureWarning
2541 && type != null
2542 && (type.getName().equals("java.beans.EventHandler")
2543 || type.getName().endsWith("$LazyIterator")
2544 || type.getName().startsWith("javax.crypto.")));
2545 }
2546
2547 public void marshal(final Object source, final HierarchicalStreamWriter writer,
2548 final MarshallingContext context) {
2549 throw new ConversionException("Security alert. Marshalling rejected.");
2550 }
2551
2552 public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
2553 throw new ConversionException("Security alert. Unmarshalling rejected.");
2554 }
2555 }
22502556 }
00 /*
1 * Copyright (C) 2006, 2007, 2014, 2016 XStream Committers.
1 * Copyright (C) 2006, 2007, 2014, 2016, 2017 XStream Committers.
22 * All rights reserved.
33 *
44 * The software in this package is published under the terms of the BSD
107107 public void toXML(final XStream xstream, final Object obj, final Writer out)
108108 throws IOException {
109109 final XStream outer = new XStream();
110 XStream.setupDefaultSecurity(outer);
110111 final ObjectOutputStream oos = outer.createObjectOutputStream(out);
111112 try {
112113 oos.writeObject(xstream);
267268 public Object fromXML(final HierarchicalStreamDriver driver, final Reader xml, final TypePermission[] permissions)
268269 throws IOException, ClassNotFoundException {
269270 final XStream outer = new XStream(driver);
271 XStream.setupDefaultSecurity(outer);
270272 for(int i = 0; i < permissions.length; ++i) {
271273 outer.addPermission(permissions[i]);
272274 }
00 /*
11 * Copyright (C) 2004, 2005 Joe Walnes.
2 * Copyright (C) 2006, 2007 XStream Committers.
2 * Copyright (C) 2006, 2007, 2017 XStream Committers.
33 * All rights reserved.
44 *
55 * The software in this package is published under the terms of the BSD
1212
1313 import java.util.Calendar;
1414 import java.util.Date;
15 import java.util.GregorianCalendar;
16
17 import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
1518
1619
1720 /**
2124 * @author Mauro Talevi
2225 * @author J&ouml;rg Schaible
2326 */
24 public class ISO8601DateConverter extends ISO8601GregorianCalendarConverter {
27 public class ISO8601DateConverter extends AbstractSingleValueConverter {
28 private final ISO8601GregorianCalendarConverter converter = new ISO8601GregorianCalendarConverter();
2529
2630 public boolean canConvert(Class type) {
27 return type.equals(Date.class);
31 return type.equals(Date.class) && converter.canConvert(GregorianCalendar.class);
2832 }
2933
3034 public Object fromString(String str) {
31 return ((Calendar)super.fromString(str)).getTime();
35 return ((Calendar)converter.fromString(str)).getTime();
3236 }
3337
3438 public String toString(Object obj) {
35 Calendar calendar = Calendar.getInstance();
39 final Calendar calendar = Calendar.getInstance();
3640 calendar.setTime((Date)obj);
37 return super.toString(calendar);
41 return converter.toString(calendar);
3842 }
3943 }
00 /*
11 * Copyright (C) 2005 Joe Walnes.
2 * Copyright (C) 2006, 2007, 2011, 2013, 2014, 2015, 2016 XStream Committers.
2 * Copyright (C) 2006, 2007, 2011, 2013, 2014, 2015, 2016, 2017 XStream Committers.
33 * All rights reserved.
44 *
55 * The software in this package is published under the terms of the BSD
1010 */
1111 package com.thoughtworks.xstream.converters.extended;
1212
13 import com.thoughtworks.xstream.converters.ConversionException;
13 import java.lang.reflect.InvocationTargetException;
14 import java.util.GregorianCalendar;
15
16 import com.thoughtworks.xstream.converters.SingleValueConverter;
1417 import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
15
16 import org.joda.time.DateTime;
17 import org.joda.time.DateTimeZone;
18 import org.joda.time.format.DateTimeFormatter;
19 import org.joda.time.format.ISODateTimeFormat;
20
21 import java.util.Calendar;
22 import java.util.GregorianCalendar;
23 import java.util.TimeZone;
18 import com.thoughtworks.xstream.core.JVM;
2419
2520
2621 /**
27 * A GregorianCalendarConverter conforming to the ISO8601 standard. The converter will always
28 * serialize the calendar value in UTC and deserialize it to a value in the current default time
29 * zone.
22 * A GregorianCalendarConverter conforming to the ISO8601 standard. The converter will always serialize the calendar
23 * value in UTC and deserialize it to a value in the current default time zone.
3024 *
3125 * @author Mauro Talevi
3226 * @author J&ouml;rg Schaible
3428 * @since 1.1.3
3529 */
3630 public class ISO8601GregorianCalendarConverter extends AbstractSingleValueConverter {
37 private static final DateTimeFormatter[] formattersUTC = new DateTimeFormatter[]{
38 ISODateTimeFormat.dateTime(),
39 ISODateTimeFormat.dateTimeNoMillis(),
40 ISODateTimeFormat.basicDateTime(),
41 ISODateTimeFormat.basicOrdinalDateTime(),
42 ISODateTimeFormat.basicOrdinalDateTimeNoMillis(),
43 ISODateTimeFormat.basicTime(),
44 ISODateTimeFormat.basicTimeNoMillis(),
45 ISODateTimeFormat.basicTTime(),
46 ISODateTimeFormat.basicTTimeNoMillis(),
47 ISODateTimeFormat.basicWeekDateTime(),
48 ISODateTimeFormat.basicWeekDateTimeNoMillis(),
49 ISODateTimeFormat.ordinalDateTime(),
50 ISODateTimeFormat.ordinalDateTimeNoMillis(),
51 ISODateTimeFormat.time(),
52 ISODateTimeFormat.timeNoMillis(),
53 ISODateTimeFormat.tTime(),
54 ISODateTimeFormat.tTimeNoMillis(),
55 ISODateTimeFormat.weekDateTime(),
56 ISODateTimeFormat.weekDateTimeNoMillis()
57 };
58 private static final DateTimeFormatter[] formattersNoUTC = new DateTimeFormatter[]{
59 ISODateTimeFormat.basicDate(),
60 ISODateTimeFormat.basicOrdinalDate(),
61 ISODateTimeFormat.basicWeekDate(),
62 ISODateTimeFormat.date(),
63 ISODateTimeFormat.dateHour(),
64 ISODateTimeFormat.dateHourMinute(),
65 ISODateTimeFormat.dateHourMinuteSecond(),
66 ISODateTimeFormat.dateHourMinuteSecondFraction(),
67 ISODateTimeFormat.dateHourMinuteSecondMillis(),
68 ISODateTimeFormat.hour(),
69 ISODateTimeFormat.hourMinute(),
70 ISODateTimeFormat.hourMinuteSecond(),
71 ISODateTimeFormat.hourMinuteSecondFraction(),
72 ISODateTimeFormat.hourMinuteSecondMillis(),
73 ISODateTimeFormat.ordinalDate(),
74 ISODateTimeFormat.weekDate(),
75 ISODateTimeFormat.year(),
76 ISODateTimeFormat.yearMonth(),
77 ISODateTimeFormat.yearMonthDay(),
78 ISODateTimeFormat.weekyear(),
79 ISODateTimeFormat.weekyearWeek(),
80 ISODateTimeFormat.weekyearWeekDay()
81 };
82
83 public boolean canConvert(Class type) {
84 return type.equals(GregorianCalendar.class);
31 private final static Class[] EMPTY_CLASS_ARRAY = new Class[0];
32 private final static Object[] EMPTY_OBJECT_ARRAY = new Object[0];
33 private final SingleValueConverter converter;
34
35 public ISO8601GregorianCalendarConverter() {
36 SingleValueConverter svConverter = null;
37 final Class type = JVM.loadClassForName(JVM.is18()
38 ? "com.thoughtworks.xstream.core.util.ISO8601JavaTimeConverter"
39 : "com.thoughtworks.xstream.core.util.ISO8601JodaTimeConverter");
40 try {
41 svConverter = (SingleValueConverter)type.getDeclaredConstructor(EMPTY_CLASS_ARRAY).newInstance(
42 EMPTY_OBJECT_ARRAY);
43 } catch (final InstantiationException e) {
44 // ignore
45 } catch (final IllegalAccessException e) {
46 // ignore
47 } catch (final InvocationTargetException e) {
48 // ignore
49 } catch (final NoSuchMethodException e) {
50 // ignore
51 }
52 converter = svConverter;
8553 }
8654
87 public Object fromString(String str) {
88 for (int i = 0; i < formattersUTC.length; i++ ) {
89 DateTimeFormatter formatter = formattersUTC[i];
90 try {
91 DateTime dt = formatter.parseDateTime(str);
92 Calendar calendar = dt.toGregorianCalendar();
93 calendar.setTimeZone(TimeZone.getDefault());
94 return calendar;
95 } catch (IllegalArgumentException e) {
96 // try with next formatter
97 }
98 }
99 final DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(TimeZone.getDefault());
100 for (int i = 0; i < formattersNoUTC.length; i++ ) {
101 try {
102 final DateTimeFormatter formatter = formattersNoUTC[i].withZone(dateTimeZone);
103 final DateTime dt = formatter.parseDateTime(str);
104 final Calendar calendar = dt.toGregorianCalendar();
105 calendar.setTimeZone(TimeZone.getDefault());
106 return calendar;
107 } catch (IllegalArgumentException e) {
108 // try with next formatter
109 }
110 }
111 ConversionException exception = new ConversionException("Cannot parse date");
112 exception.add("date", str);
113 throw exception;
55 public boolean canConvert(final Class type) {
56 return converter != null && type.equals(GregorianCalendar.class);
11457 }
11558
116 public String toString(Object obj) {
117 DateTime dt = new DateTime(obj);
118 return dt.toString(formattersUTC[0]);
59 public Object fromString(final String str) {
60 return converter.fromString(str);
61 }
62
63 public String toString(final Object obj) {
64 return converter.toString(obj);
11965 }
12066 }
00 /*
11 * Copyright (C) 2005 Joe Walnes.
2 * Copyright (C) 2006, 2007 XStream Committers.
2 * Copyright (C) 2006, 2007, 2017 XStream Committers.
33 * All rights reserved.
44 *
55 * The software in this package is published under the terms of the BSD
2626 private final static String PADDING = "000000000";
2727
2828 public boolean canConvert(Class type) {
29 return type.equals(Timestamp.class);
29 return type.equals(Timestamp.class) && super.canConvert(Date.class);
3030 }
3131
3232 public Object fromString(String str) {
99 */
1010 package com.thoughtworks.xstream.converters.extended;
1111
12 import java.io.File;
1213 import java.net.URI;
1314 import java.net.URISyntaxException;
1415 import java.nio.file.FileSystems;
1516 import java.nio.file.Path;
1617 import java.nio.file.Paths;
1718
18 import com.thoughtworks.xstream.converters.ConversionException;
1919 import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
2020
2121
2828 public class PathConverter extends AbstractSingleValueConverter {
2929
3030 @Override
31 public boolean canConvert(final Class type) {
31 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
3232 return Path.class.isAssignableFrom(type);
3333 }
3434
3535 @Override
36 public Object fromString(final String str) {
36 public Path fromString(final String str) {
3737 try {
3838 final URI uri = new URI(str);
3939 if (uri.getScheme() == null) {
4242 return Paths.get(uri);
4343 }
4444 } catch (final URISyntaxException e) {
45 throw new ConversionException(e);
45 return Paths.get(str);
4646 }
4747 }
4848
5050 public String toString(final Object obj) {
5151 final Path path = (Path)obj;
5252 if (path.getFileSystem() == FileSystems.getDefault()) {
53 return path.toString();
53 final String localPath = path.toString();
54 if (File.separatorChar != '/') {
55 return localPath.replace(File.separatorChar, '/');
56 } else {
57 return localPath;
58 }
5459 } else {
5560 return path.toUri().toString();
5661 }
00 /*
11 * Copyright (C) 2003, 2004 Joe Walnes.
2 * Copyright (C) 2006, 2007, 2012, 2014 XStream Committers.
2 * Copyright (C) 2006, 2007, 2012, 2014, 2016, 2017 XStream Committers.
33 * All rights reserved.
44 *
55 * The software in this package is published under the terms of the BSD
66 * style license a copy of which has been included with this distribution in
77 * the LICENSE.txt file.
8 *
8 *
99 * Created on 01. October 2004 by Joe Walnes
1010 */
1111 package com.thoughtworks.xstream.converters.extended;
2020
2121
2222 /**
23 * Converts a java.sql.Timestamp to text.
24 *
23 * Converts a {@link Timestamp} to a string.
24 *
2525 * @author Joe Walnes
2626 * @author J&ouml;rg Schaible
2727 */
2828 public class SqlTimestampConverter extends AbstractSingleValueConverter {
2929
30 private final ThreadSafeSimpleDateFormat format = new ThreadSafeSimpleDateFormat(
31 "yyyy-MM-dd HH:mm:ss", TimeZone.getTimeZone("UTC"), 0, 5, false);
30 private final ThreadSafeSimpleDateFormat format;
31
32 /**
33 * Constructs a SqlTimestampConverter using UTC format.
34 */
35 public SqlTimestampConverter() {
36 this(TimeZone.getTimeZone("UTC"));
37 }
38
39 /**
40 * Constructs a SqlTimestampConverter.
41 * <p>
42 * XStream uses by default UTC as time zone. However, if the resulting XML is used as feed for a data base (like MS
43 * SQL) the server might expect the timestamp to be in local time and does the conversion to UTC on its own. In such
44 * a case you can register an own instance of the SqlTimestamp converter using e.g. {@link TimeZone#getDefault()}.
45 * </p>
46 *
47 * @param timeZone the time zone used for the format
48 * @since 1.4.10
49 */
50 public SqlTimestampConverter(final TimeZone timeZone) {
51 format = new ThreadSafeSimpleDateFormat("yyyy-MM-dd HH:mm:ss", timeZone, 0, 5, false);
52 }
3253
3354 public boolean canConvert(Class type) {
3455 return type.equals(Timestamp.class);
3556 }
3657
37 public String toString(Object obj) {
38 Timestamp timestamp = (Timestamp)obj;
39 StringBuffer buffer = new StringBuffer(format.format(timestamp)).append('.');
40 if (timestamp.getNanos() == 0) {
41 buffer.append('0');
42 } else {
43 String nanos = String.valueOf(timestamp.getNanos() + 1000000000);
58 public String toString(final Object obj) {
59 final Timestamp timestamp = (Timestamp)obj;
60 final StringBuffer buffer = new StringBuffer(format.format(timestamp));
61 if (timestamp.getNanos() != 0) {
62 buffer.append('.');
63 final String nanos = String.valueOf(timestamp.getNanos() + 1000000000);
4464 int last = 10;
4565 while (last > 2 && nanos.charAt(last-1) == '0')
4666 --last;
4969 return buffer.toString();
5070 }
5171
52 public Object fromString(String str) {
53 int idx = str.lastIndexOf('.');
54 if (idx < 0 || str.length() - idx < 2 || str.length() - idx > 10) {
55 throw new ConversionException(
56 "Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]");
72 public Object fromString(final String str) {
73 final int idx = str.lastIndexOf('.');
74 if (idx > 0 && (str.length() - idx < 2 || str.length() - idx > 10)) {
75 throw new ConversionException("Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]");
5776 }
5877 try {
59 Timestamp timestamp = new Timestamp(format.parse(str.substring(0, idx)).getTime());
60 StringBuffer buffer = new StringBuffer(str.substring(idx + 1));
61 while(buffer.length() != 9) {
62 buffer.append('0');
78 final Timestamp timestamp = new Timestamp(format.parse(idx < 0 ? str : str.substring(0, idx)).getTime());
79 if (idx > 0) {
80 final StringBuffer buffer = new StringBuffer(str.substring(idx + 1));
81 while (buffer.length() != 9) {
82 buffer.append('0');
83 }
84 timestamp.setNanos(Integer.parseInt(buffer.toString()));
6385 }
64 timestamp.setNanos(Integer.parseInt(buffer.toString()));
6586 return timestamp;
6687 } catch (NumberFormatException e) {
6788 throw new ConversionException(
127127 }
128128
129129 public boolean propertyDefinedInClass(String name, Class type) {
130 return getProperty(name, type) != null;
130 return propertyDictionary.propertyDescriptorOrNull(type, name) != null;
131131 }
132132
133133 /**
135135 */
136136 public boolean canInstantiate(Class type) {
137137 try {
138 return newInstance(type) != null;
139 } catch (ObjectAccessException e) {
138 return type != null && newInstance(type) != null;
139 } catch (final ErrorWritingException e) {
140140 return false;
141141 }
142142 }
00 /*
11 * Copyright (C) 2005 Joe Walnes.
2 * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 XStream Committers.
2 * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 XStream Committers.
33 * All rights reserved.
44 *
55 * The software in this package is published under the terms of the BSD
143143 Object value = context.convertAnother(result, type);
144144 beanProvider.writeProperty(result, propertyName, value);
145145 seenProperties.add(new FastField(resultType, propertyName));
146 } else {
146 } else if (!mapper.isIgnoredElement(propertyName)) {
147147 throw new MissingFieldException(resultType.getName(), propertyName);
148148 }
149149 }
00 /*
11 * Copyright (C) 2005 Joe Walnes.
2 * Copyright (C) 2006, 2007, 2008, 2009, 2011, 2016 XStream Committers.
2 * Copyright (C) 2006, 2007, 2008, 2009, 2011, 2016, 2017 XStream Committers.
33 * All rights reserved.
44 *
55 * The software in this package is published under the terms of the BSD
7070 */
7171 public BeanProperty property(Class cls, String name) {
7272 BeanProperty beanProperty = null;
73 PropertyDescriptor descriptor = (PropertyDescriptor)buildMap(cls).get(name);
73 PropertyDescriptor descriptor = propertyDescriptorOrNull(cls, name);
7474 if (descriptor == null) {
7575 throw new MissingFieldException(cls.getName(), name);
7676 }
9090 *
9191 * @param type
9292 * @param name
93 * @throws MissingFieldException if property does not exist
9394 */
9495 public PropertyDescriptor propertyDescriptor(Class type, String name) {
95 PropertyDescriptor descriptor = (PropertyDescriptor)buildMap(type).get(name);
96 PropertyDescriptor descriptor = propertyDescriptorOrNull(type, name);
9697 if (descriptor == null) {
9798 throw new MissingFieldException(type.getName(), name);
9899 }
99100 return descriptor;
101 }
102
103 /**
104 * Locates a property descriptor.
105 *
106 * @param type
107 * @param name
108 * @return {@code null} if property does not exist
109 * @since 1.4.10
110 */
111 public PropertyDescriptor propertyDescriptorOrNull(Class type, String name) {
112 return (PropertyDescriptor)buildMap(type).get(name);
100113 }
101114
102115 private Map buildMap(Class type) {
00 /*
11 * Copyright (C) 2004, 2005, 2006 Joe Walnes.
2 * Copyright (C) 2006, 2007, 2013, 2014 XStream Committers.
2 * Copyright (C) 2006, 2007, 2013, 2014, 2017 XStream Committers.
33 * All rights reserved.
44 *
55 * The software in this package is published under the terms of the BSD
1010 */
1111 package com.thoughtworks.xstream.converters.reflection;
1212
13 import com.thoughtworks.xstream.core.JVM;
1413 import com.thoughtworks.xstream.mapper.Mapper;
1514
1615 public class ReflectionConverter extends AbstractReflectionConverter {
1716
18 // Might be missing in Android
19 private final static Class eventHandlerType = JVM.loadClassForName("java.beans.EventHandler");
2017 private Class type;
2118
2219 public ReflectionConverter(Mapper mapper, ReflectionProvider reflectionProvider) {
3734 }
3835
3936 public boolean canConvert(Class type) {
40 return ((this.type != null && this.type == type) || (this.type == null && type != null && type != eventHandlerType))
41 && canAccess(type);
37 return (this.type != null && this.type == type || this.type == null && type != null) && canAccess(type);
4238 }
4339 }
00 /*
11 * Copyright (C) 2004, 2005 Joe Walnes.
2 * Copyright (C) 2006, 2007, 2008, 2011, 2013, 2014, 2016 XStream Committers.
2 * Copyright (C) 2006, 2007, 2008, 2011, 2013, 2014, 2016, 2017 XStream Committers.
33 * All rights reserved.
44 *
55 * Created on 08. January 2014 by Joerg Schaible, factored out from SunUnsafeReflectionProvider
7777 throw ex;
7878 }
7979 ErrorWritingException ex = null;
80 try {
81 return unsafe.allocateInstance(type);
82 } catch (SecurityException e) {
83 ex = new ObjectAccessException("Cannot construct type", e);
84 } catch (InstantiationException e) {
85 ex = new ConversionException("Cannot construct type", e);
86 } catch (IllegalArgumentException e) {
87 ex = new ObjectAccessException("Cannot construct type", e);
80 if (type == void.class || type == Void.class) {
81 ex = new ConversionException("Type void cannot have an instance");
82 } else {
83 try {
84 return unsafe.allocateInstance(type);
85 } catch (final SecurityException e) {
86 ex = new ObjectAccessException("Cannot construct type", e);
87 } catch (final InstantiationException e) {
88 ex = new ConversionException("Cannot construct type", e);
89 } catch (final IllegalArgumentException e) {
90 ex = new ObjectAccessException("Cannot construct type", e);
91 }
8892 }
8993 ex.add("construction-type", type.getName());
9094 throw ex;
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 22. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.DateTimeException;
13 import java.time.chrono.ChronoLocalDate;
14 import java.time.chrono.Chronology;
15 import java.time.chrono.Era;
16 import java.util.Set;
17 import java.util.regex.Matcher;
18 import java.util.regex.Pattern;
19
20 import com.thoughtworks.xstream.converters.ConversionException;
21 import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
22
23
24 /**
25 * Abstract base class for converters handling derived classes of {@link java.time.chrono.ChronoLocalDate} instances.
26 *
27 * @author J&ouml;rg Schaible
28 * @since 1.4.10
29 */
30 abstract class AbstractChronoLocalDateConverter<E extends Era> extends AbstractSingleValueConverter {
31 protected abstract ChronoLocalDate chronoLocalDateOf(final E era, final int prolepticYear, final int month,
32 final int dayOfMonth);
33
34 protected abstract E eraOf(final String id);
35
36 private final static Pattern CHRONO_DATE_PATTERN = Pattern.compile("^ (\\w+) (\\d+)-(\\d+)-(\\d+)$");
37
38 protected ChronoLocalDate parseChronoLocalDate(final String str, final String dateTypeName,
39 final Set<Chronology> chronologies) {
40 if (str == null) {
41 return null;
42 }
43
44 ConversionException exception = null;
45 for (final Chronology chronology : chronologies) {
46 final String id = chronology.getId();
47 if (str.startsWith(id + ' ')) {
48 final Matcher matcher = CHRONO_DATE_PATTERN.matcher(str.subSequence(id.length(), str.length()));
49 if (matcher.matches()) {
50 E era = null;
51 try {
52 era = eraOf(matcher.group(1));
53 } catch (final IllegalArgumentException e) {
54 exception = new ConversionException("Cannot parse value as " + dateTypeName + " date", e);
55 break;
56 }
57 if (era != null) {
58 try {
59 return chronoLocalDateOf(era, Integer.parseInt(matcher.group(2)), Integer.parseInt(matcher
60 .group(3)), Integer.parseInt(matcher.group(4)));
61 } catch (final DateTimeException e) {
62 exception = new ConversionException("Cannot parse value as " + dateTypeName + " date", e);
63 break;
64 }
65 }
66 }
67 }
68 }
69 if (exception == null) {
70 exception = new ConversionException("Cannot parse value as " + dateTypeName + " date");
71 }
72 exception.add("value", str);
73 throw exception;
74 }
75
76 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 19. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.DateTimeException;
13 import java.time.chrono.Chronology;
14
15 import com.thoughtworks.xstream.converters.ConversionException;
16 import com.thoughtworks.xstream.converters.SingleValueConverter;
17
18
19 /**
20 * Converts a {@link Chronology} instance to a string using its id.
21 *
22 * @author J&ouml;rg Schaible
23 * @since 1.4.10
24 */
25 public class ChronologyConverter implements SingleValueConverter {
26
27 @Override
28 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
29 return Chronology.class.isAssignableFrom(type);
30 }
31
32 @Override
33 public Chronology fromString(final String str) {
34 if (str == null) {
35 return null;
36 }
37 try {
38 return Chronology.of(str);
39 } catch (final DateTimeException e) {
40 final ConversionException exception = new ConversionException("Cannot parse value as chronology", e);
41 exception.add("value", str);
42 throw exception;
43 }
44 }
45
46 @Override
47 public String toString(final Object obj) {
48 return obj == null ? null : ((Chronology)obj).getId();
49 }
50 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 13. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.Duration;
13 import java.time.format.DateTimeParseException;
14
15 import com.thoughtworks.xstream.converters.ConversionException;
16 import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
17
18
19 /**
20 * Converts a {@link Duration} instance to string.
21 *
22 * @author J&ouml;rg Schaible
23 * @since 1.4.10
24 */
25 public class DurationConverter extends AbstractSingleValueConverter {
26
27 @Override
28 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
29 return Duration.class == type;
30 }
31
32 @Override
33 public Duration fromString(final String str) {
34 try {
35 return Duration.parse(str);
36 } catch (final DateTimeParseException ex) {
37 final ConversionException exception = new ConversionException("Cannot parse value as duration", ex);
38 exception.add("value", str);
39 throw exception;
40 }
41 }
42 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 21. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.chrono.ChronoLocalDate;
13 import java.time.chrono.Chronology;
14 import java.time.chrono.HijrahChronology;
15 import java.time.chrono.HijrahDate;
16 import java.time.chrono.HijrahEra;
17 import java.util.HashSet;
18 import java.util.Set;
19
20
21 /**
22 * Converts a {@link java.time.chrono.HijrahDate} to a string.
23 *
24 * @author J&ouml;rg Schaible
25 * @since 1.4.10
26 */
27 public class HijrahDateConverter extends AbstractChronoLocalDateConverter<HijrahEra> {
28
29 private final Set<Chronology> hijrahChronologies;
30
31 /**
32 * Constructs a HijrahDateConverter instance.
33 */
34 public HijrahDateConverter() {
35 hijrahChronologies = new HashSet<>();
36 final Set<Chronology> chronologies = Chronology.getAvailableChronologies();
37 for (final Chronology chronology : chronologies) {
38 if (chronology instanceof HijrahChronology) {
39 hijrahChronologies.add(chronology);
40 }
41 }
42 }
43
44 @Override
45 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
46 return HijrahDate.class == type;
47 }
48
49 @Override
50 public Object fromString(final String str) {
51 return parseChronoLocalDate(str, "Hijrah", hijrahChronologies);
52 }
53
54 @Override
55 protected ChronoLocalDate chronoLocalDateOf(final HijrahEra era, final int prolepticYear, final int month,
56 final int dayOfMonth) {
57 return era != null ? HijrahDate.of(prolepticYear, month, dayOfMonth) : null;
58 }
59
60 @Override
61 protected HijrahEra eraOf(final String id) {
62 return HijrahEra.valueOf(id);
63 }
64
65 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 15. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.Instant;
13 import java.time.format.DateTimeParseException;
14
15 import com.thoughtworks.xstream.converters.ConversionException;
16 import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
17
18
19 /**
20 * Converts a {@link Instant} instance to string.
21 *
22 * @author J&ouml;rg Schaible
23 * @since 1.4.10
24 */
25 public class InstantConverter extends AbstractSingleValueConverter {
26
27 @Override
28 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
29 return Instant.class == type;
30 }
31
32 @Override
33 public Instant fromString(final String str) {
34 try {
35 return Instant.parse(str);
36 } catch (final DateTimeParseException ex) {
37 final ConversionException exception = new ConversionException("Cannot parse value as instant", ex);
38 exception.add("value", str);
39 throw exception;
40 }
41 }
42 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 22. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.chrono.ChronoLocalDate;
13 import java.time.chrono.JapaneseChronology;
14 import java.time.chrono.JapaneseDate;
15 import java.time.chrono.JapaneseEra;
16 import java.util.Collections;
17
18
19 /**
20 * Converts a {@link java.time.chrono.JapaneseDate} to a string.
21 *
22 * @author J&ouml;rg Schaible
23 * @since 1.4.10
24 */
25 public class JapaneseDateConverter extends AbstractChronoLocalDateConverter<JapaneseEra> {
26
27 @Override
28 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
29 return JapaneseDate.class == type;
30 }
31
32 @Override
33 public Object fromString(final String str) {
34 return parseChronoLocalDate(str, "Japanese", Collections.singleton(JapaneseChronology.INSTANCE));
35 }
36
37 @Override
38 protected ChronoLocalDate chronoLocalDateOf(final JapaneseEra era, final int prolepticYear, final int month,
39 final int dayOfMonth) {
40 return JapaneseDate.of(era, prolepticYear, month, dayOfMonth);
41 }
42
43 @Override
44 protected JapaneseEra eraOf(final String id) {
45 return JapaneseEra.valueOf(id);
46 }
47
48 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 22. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.chrono.JapaneseEra;
13
14 import com.thoughtworks.xstream.converters.ConversionException;
15 import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
16
17
18 /**
19 * Converts a {@link JapaneseEra} instance to a string using its id.
20 *
21 * @author J&ouml;rg Schaible
22 * @since 1.4.10
23 */
24 public class JapaneseEraConverter extends AbstractSingleValueConverter {
25
26 @Override
27 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
28 return JapaneseEra.class.isAssignableFrom(type);
29 }
30
31 @Override
32 public JapaneseEra fromString(final String str) {
33 if (str == null) {
34 return null;
35 }
36 try {
37 return JapaneseEra.valueOf(str);
38 } catch (final IllegalArgumentException e) {
39 final ConversionException exception = new ConversionException("Cannot parse value as Japanese era", e);
40 exception.add("value", str);
41 throw exception;
42 }
43 }
44 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 13. January 2017 by Matej Cimbora
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.LocalDate;
13 import java.time.format.DateTimeParseException;
14
15 import com.thoughtworks.xstream.converters.ConversionException;
16 import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
17
18
19 /**
20 * Converts a {@link java.time.LocalDate} to a string.
21 *
22 * @author Matej Cimbora
23 * @since 1.4.10
24 */
25 public class LocalDateConverter extends AbstractSingleValueConverter {
26
27 @Override
28 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
29 return LocalDate.class == type;
30 }
31
32 @Override
33 public Object fromString(final String str) {
34 try {
35 return LocalDate.parse(str);
36 } catch (final DateTimeParseException e) {
37 final ConversionException exception = new ConversionException("Cannot parse value as local date", e);
38 exception.add("value", str);
39 throw exception;
40 }
41 }
42
43 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 13. January 2017 by Matej Cimbora
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.LocalDateTime;
13 import java.time.format.DateTimeFormatter;
14 import java.time.format.DateTimeFormatterBuilder;
15 import java.time.format.DateTimeParseException;
16 import java.time.temporal.ChronoField;
17
18 import com.thoughtworks.xstream.converters.ConversionException;
19 import com.thoughtworks.xstream.converters.SingleValueConverter;
20
21
22 /**
23 * Converts a {@link LocalDateTime} to a string.
24 *
25 * @author Matej Cimbora
26 * @since 1.4.10
27 */
28 public class LocalDateTimeConverter implements SingleValueConverter {
29
30 private static final DateTimeFormatter FORMATTER;
31
32 static {
33 FORMATTER = new DateTimeFormatterBuilder()
34 .appendPattern("uuuu-MM-dd'T'HH:mm:ss")
35 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
36 .toFormatter();
37 }
38
39 @Override
40 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
41 return LocalDateTime.class == type;
42 }
43
44 @Override
45 public Object fromString(final String str) {
46 try {
47 return LocalDateTime.parse(str);
48 } catch (final DateTimeParseException e) {
49 final ConversionException exception = new ConversionException("Cannot parse value as local date time", e);
50 exception.add("value", str);
51 throw exception;
52 }
53 }
54
55 @Override
56 public String toString(final Object obj) {
57 if (obj == null) {
58 return null;
59 }
60
61 final LocalDateTime localDateTime = (LocalDateTime)obj;
62 return FORMATTER.format(localDateTime);
63 }
64 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 13. January 2017 by Matej Cimbora
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.LocalTime;
13 import java.time.format.DateTimeFormatter;
14 import java.time.format.DateTimeFormatterBuilder;
15 import java.time.format.DateTimeParseException;
16 import java.time.temporal.ChronoField;
17
18 import com.thoughtworks.xstream.converters.ConversionException;
19 import com.thoughtworks.xstream.converters.SingleValueConverter;
20
21
22 /**
23 * Converts a {@link LocalTime} to a string.
24 *
25 * @author Matej Cimbora
26 * @since 1.4.10
27 */
28 public class LocalTimeConverter implements SingleValueConverter {
29
30 private static final DateTimeFormatter FORMATTER;
31
32 static {
33 FORMATTER = new DateTimeFormatterBuilder()
34 .appendPattern("HH:mm:ss")
35 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
36 .toFormatter();
37 }
38
39 @Override
40 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
41 return LocalTime.class == type;
42 }
43
44 @Override
45 public Object fromString(final String str) {
46 try {
47 return LocalTime.parse(str);
48 } catch (final DateTimeParseException e) {
49 final ConversionException exception = new ConversionException("Cannot parse value as local time", e);
50 exception.add("value", str);
51 throw exception;
52 }
53 }
54
55 @Override
56 public String toString(final Object obj) {
57 if (obj == null) {
58 return null;
59 }
60
61 final LocalTime localTime = (LocalTime)obj;
62 return FORMATTER.format(localTime);
63 }
64 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 22. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.chrono.ChronoLocalDate;
13 import java.time.chrono.MinguoChronology;
14 import java.time.chrono.MinguoDate;
15 import java.time.chrono.MinguoEra;
16 import java.util.Collections;
17
18
19 /**
20 * Converts a {@link java.time.chrono.MinguoDate} to a string.
21 *
22 * @author J&ouml;rg Schaible
23 * @since 1.4.10
24 */
25 public class MinguoDateConverter extends AbstractChronoLocalDateConverter<MinguoEra> {
26
27 @Override
28 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
29 return MinguoDate.class == type;
30 }
31
32 @Override
33 public Object fromString(final String str) {
34 return parseChronoLocalDate(str, "Minguo", Collections.singleton(MinguoChronology.INSTANCE));
35 }
36
37 @Override
38 protected ChronoLocalDate chronoLocalDateOf(final MinguoEra era, final int prolepticYear, final int month,
39 final int dayOfMonth) {
40 return MinguoDate.of(prolepticYear, month, dayOfMonth);
41 }
42
43 @Override
44 protected MinguoEra eraOf(final String id) {
45 return MinguoEra.valueOf(id);
46 }
47
48 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 13. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.MonthDay;
13 import java.time.format.DateTimeParseException;
14
15 import com.thoughtworks.xstream.converters.ConversionException;
16 import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
17
18
19 /**
20 * Converts a {@link MonthDay} instance to string.
21 *
22 * @author J&ouml;rg Schaible
23 * @since 1.4.10
24 */
25 public class MonthDayConverter extends AbstractSingleValueConverter {
26
27 @Override
28 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
29 return MonthDay.class == type;
30 }
31
32 @Override
33 public MonthDay fromString(final String str) {
34 try {
35 return MonthDay.parse(str);
36 } catch (final DateTimeParseException ex) {
37 final ConversionException exception = new ConversionException("Cannot parse value as month day", ex);
38 exception.add("value", str);
39 throw exception;
40 }
41 }
42 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 13. January 2017 by Matej Cimbora
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.OffsetDateTime;
13 import java.time.format.DateTimeFormatter;
14 import java.time.format.DateTimeFormatterBuilder;
15 import java.time.format.DateTimeParseException;
16 import java.time.temporal.ChronoField;
17
18 import com.thoughtworks.xstream.converters.ConversionException;
19 import com.thoughtworks.xstream.converters.SingleValueConverter;
20
21
22 /**
23 * Converts a {@link OffsetDateTime} to a string.
24 *
25 * @author Matej Cimbora
26 * @since 1.4.10
27 */
28 public class OffsetDateTimeConverter implements SingleValueConverter {
29
30 private static final DateTimeFormatter FORMATTER;
31
32 static {
33 FORMATTER = new DateTimeFormatterBuilder()
34 .appendPattern("uuuu-MM-dd'T'HH:mm:ss")
35 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
36 .appendOffsetId()
37 .toFormatter();
38 }
39
40 @Override
41 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
42 return OffsetDateTime.class == type;
43 }
44
45 @Override
46 public Object fromString(final String str) {
47 try {
48 return OffsetDateTime.parse(str);
49 } catch (final DateTimeParseException e) {
50 final ConversionException exception = new ConversionException("Cannot parse value as offset date time", e);
51 exception.add("value", str);
52 throw exception;
53 }
54 }
55
56 @Override
57 public String toString(final Object obj) {
58 if (obj == null) {
59 return null;
60 }
61
62 final OffsetDateTime offsetDateTime = (OffsetDateTime)obj;
63 return FORMATTER.format(offsetDateTime);
64 }
65 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 11. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.OffsetTime;
13 import java.time.format.DateTimeFormatter;
14 import java.time.format.DateTimeFormatterBuilder;
15 import java.time.format.DateTimeParseException;
16 import java.time.temporal.ChronoField;
17
18 import com.thoughtworks.xstream.converters.ConversionException;
19 import com.thoughtworks.xstream.converters.SingleValueConverter;
20
21
22 /**
23 * Converts a {@link OffsetTime} to a string.
24 *
25 * @author Matej Cimbora
26 * @author J&ouml;rg Schaible
27 * @since 1.4.10
28 */
29 public class OffsetTimeConverter implements SingleValueConverter {
30
31 private static final DateTimeFormatter FORMATTER;
32
33 static {
34 FORMATTER = new DateTimeFormatterBuilder()
35 .appendPattern("HH:mm:ss")
36 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
37 .appendOffsetId()
38 .toFormatter();
39 }
40
41 @Override
42 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
43 return OffsetTime.class == type;
44 }
45
46 @Override
47 public Object fromString(final String str) {
48 try {
49 return OffsetTime.parse(str);
50 } catch (final DateTimeParseException e) {
51 final ConversionException exception = new ConversionException("Cannot parse value as offset time", e);
52 exception.add("value", str);
53 throw exception;
54 }
55 }
56
57 @Override
58 public String toString(final Object obj) {
59 if (obj == null) {
60 return null;
61 }
62
63 final OffsetTime offsetTime = (OffsetTime)obj;
64 return FORMATTER.format(offsetTime);
65 }
66 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 13. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.Period;
13 import java.time.format.DateTimeParseException;
14
15 import com.thoughtworks.xstream.converters.ConversionException;
16 import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
17
18
19 /**
20 * Converts a {@link Period} instance to string.
21 *
22 * @author J&ouml;rg Schaible
23 * @since 1.4.10
24 */
25 public class PeriodConverter extends AbstractSingleValueConverter {
26
27 @Override
28 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
29 return Period.class == type;
30 }
31
32 @Override
33 public Period fromString(final String str) {
34 try {
35 return Period.parse(str);
36 } catch (final DateTimeParseException ex) {
37 final ConversionException exception = new ConversionException("Cannot parse period value", ex);
38 exception.add("period", str);
39 throw exception;
40 }
41 }
42 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 06. March 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.Clock;
13 import java.time.ZoneId;
14
15 import com.thoughtworks.xstream.converters.Converter;
16 import com.thoughtworks.xstream.converters.MarshallingContext;
17 import com.thoughtworks.xstream.converters.UnmarshallingContext;
18 import com.thoughtworks.xstream.io.ExtendedHierarchicalStreamWriterHelper;
19 import com.thoughtworks.xstream.io.HierarchicalStreamReader;
20 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
21 import com.thoughtworks.xstream.mapper.Mapper;
22
23
24 /**
25 * Converts a system {@link Clock}, using zone as nested element.
26 *
27 * @author J&ouml;rg Schaible
28 * @since 1.4.10
29 */
30 public class SystemClockConverter implements Converter {
31
32 private final Mapper mapper;
33 private final Class<?> type;
34
35 /**
36 * Constructs a SystemClockConverter instance.
37 *
38 * @param mapper the Mapper instance
39 */
40 public SystemClockConverter(final Mapper mapper) {
41 this.mapper = mapper;
42 type = Clock.systemUTC().getClass();
43 }
44
45 @Override
46 public boolean canConvert(final Class type) {
47 return type == this.type;
48 }
49
50 @Override
51 public void marshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) {
52 final Clock clock = (Clock)source;
53 ExtendedHierarchicalStreamWriterHelper.startNode(writer, mapper.serializedMember(Clock.class, "zone"), null);
54 context.convertAnother(clock.getZone());
55 writer.endNode();
56 }
57
58 @Override
59 public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
60 reader.moveDown();
61 final ZoneId zone = (ZoneId)context.convertAnother(null, ZoneId.class);
62 reader.moveUp();
63 return Clock.system(zone);
64 }
65 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 22. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.chrono.ChronoLocalDate;
13 import java.time.chrono.ThaiBuddhistChronology;
14 import java.time.chrono.ThaiBuddhistDate;
15 import java.time.chrono.ThaiBuddhistEra;
16 import java.util.Collections;
17
18
19 /**
20 * Converts a {@link java.time.chrono.ThaiBuddhistDate} to a string.
21 *
22 * @author J&ouml;rg Schaible
23 * @since 1.4.10
24 */
25 public class ThaiBuddhistDateConverter extends AbstractChronoLocalDateConverter<ThaiBuddhistEra> {
26
27 @Override
28 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
29 return ThaiBuddhistDate.class == type;
30 }
31
32 @Override
33 public Object fromString(final String str) {
34 return parseChronoLocalDate(str, "Thai Buddhist", Collections.singleton(ThaiBuddhistChronology.INSTANCE));
35 }
36
37 @Override
38 protected ChronoLocalDate chronoLocalDateOf(final ThaiBuddhistEra era, final int prolepticYear, final int month,
39 final int dayOfMonth) {
40 return ThaiBuddhistDate.of(prolepticYear, month, dayOfMonth);
41 }
42
43 @Override
44 protected ThaiBuddhistEra eraOf(final String id) {
45 return ThaiBuddhistEra.valueOf(id);
46 }
47
48 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 22. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.temporal.ValueRange;
13 import java.util.HashMap;
14 import java.util.Map;
15
16 import com.thoughtworks.xstream.converters.Converter;
17 import com.thoughtworks.xstream.converters.MarshallingContext;
18 import com.thoughtworks.xstream.converters.UnmarshallingContext;
19 import com.thoughtworks.xstream.io.ExtendedHierarchicalStreamWriterHelper;
20 import com.thoughtworks.xstream.io.HierarchicalStreamReader;
21 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
22 import com.thoughtworks.xstream.mapper.Mapper;
23
24
25 /**
26 * Converts a temporal {@link ValueRange}, using four nested elements: maxLargest, maxSmallest, minLargest, and
27 * minSmallest.
28 *
29 * @author J&ouml;rg Schaible
30 * @since 1.4.10
31 */
32 public class ValueRangeConverter implements Converter {
33
34 private final Mapper mapper;
35
36 /**
37 * Constructs a ValueRangeConverter instance.
38 *
39 * @param mapper the Mapper instance
40 */
41 public ValueRangeConverter(final Mapper mapper) {
42 this.mapper = mapper;
43
44 }
45
46 @Override
47 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
48 return type == ValueRange.class;
49 }
50
51 @Override
52 public void marshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) {
53 final ValueRange valueRange = (ValueRange)source;
54 write("maxLargest", valueRange.getMaximum(), writer);
55 write("maxSmallest", valueRange.getSmallestMaximum(), writer);
56 write("minLargest", valueRange.getLargestMinimum(), writer);
57 write("minSmallest", valueRange.getMinimum(), writer);
58 }
59
60 @Override
61 public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
62 final boolean oldFormat = "custom".equals(reader.getAttribute(mapper.aliasForSystemAttribute("serialization")));
63 if (oldFormat) {
64 reader.moveDown();
65 reader.moveDown();
66 }
67 final Map<String, Long> elements = new HashMap<>();
68 while (reader.hasMoreChildren()) {
69 reader.moveDown();
70
71 final String name = reader.getNodeName();
72 elements.put(oldFormat ? name : mapper.realMember(ValueRange.class, name), Long.valueOf(reader.getValue()));
73 reader.moveUp();
74 }
75 if (oldFormat) {
76 reader.moveUp();
77 reader.moveUp();
78 }
79 return ValueRange.of(elements.get("minSmallest").longValue(), elements.get("minLargest").longValue(), elements
80 .get("maxSmallest")
81 .longValue(), elements.get("maxLargest").longValue());
82 }
83
84 private void write(final String fieldName, final long value, final HierarchicalStreamWriter writer) {
85 ExtendedHierarchicalStreamWriterHelper.startNode(writer, mapper.serializedMember(ValueRange.class, fieldName),
86 long.class);
87 writer.setValue(String.valueOf(value));
88 writer.endNode();
89 }
90 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 22. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.DayOfWeek;
13 import java.time.temporal.WeekFields;
14
15 import com.thoughtworks.xstream.converters.Converter;
16 import com.thoughtworks.xstream.converters.MarshallingContext;
17 import com.thoughtworks.xstream.converters.UnmarshallingContext;
18 import com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.UnknownFieldException;
19 import com.thoughtworks.xstream.io.ExtendedHierarchicalStreamWriterHelper;
20 import com.thoughtworks.xstream.io.HierarchicalStreamReader;
21 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
22 import com.thoughtworks.xstream.mapper.Mapper;
23
24
25 /**
26 * Converts a {@link WeekFields} instance, using two nested elements: minimalDays and minSmallest.
27 *
28 * @author J&ouml;rg Schaible
29 * @since 1.4.10
30 */
31 public class WeekFieldsConverter implements Converter {
32
33 private final Mapper mapper;
34
35 /**
36 * Constructs a WeekFieldsConverter instance.
37 *
38 * @param mapper the Mapper instance
39 */
40 public WeekFieldsConverter(final Mapper mapper) {
41 this.mapper = mapper;
42
43 }
44
45 @Override
46 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
47 return type == WeekFields.class;
48 }
49
50 @Override
51 public void marshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) {
52 final WeekFields weekFields = (WeekFields)source;
53 ExtendedHierarchicalStreamWriterHelper.startNode(writer, mapper.serializedMember(WeekFields.class,
54 "minimalDays"), int.class);
55 writer.setValue(String.valueOf(weekFields.getMinimalDaysInFirstWeek()));
56 writer.endNode();
57 ExtendedHierarchicalStreamWriterHelper.startNode(writer, mapper.serializedMember(WeekFields.class,
58 "firstDayOfWeek"), DayOfWeek.class);
59 context.convertAnother(weekFields.getFirstDayOfWeek());
60 writer.endNode();
61 }
62
63 @Override
64 public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
65 final boolean oldFormat = "custom".equals(reader.getAttribute(mapper.aliasForSystemAttribute("serialization")));
66 if (oldFormat) {
67 reader.moveDown();
68 reader.moveDown();
69 }
70
71 int minimalDays = 0;
72 DayOfWeek firstDayOfWeek = null;
73 while (reader.hasMoreChildren()) {
74 reader.moveDown();
75 final String name = oldFormat
76 ? reader.getNodeName()
77 : mapper.realMember(WeekFields.class, reader.getNodeName());
78 if ("minimalDays".equals(name)) {
79 minimalDays = Integer.parseInt(reader.getValue());
80 } else if ("firstDayOfWeek".equals(name)) {
81 firstDayOfWeek = (DayOfWeek)context.convertAnother(null, DayOfWeek.class);
82 } else {
83 throw new UnknownFieldException(WeekFields.class.getName(), name);
84 }
85 reader.moveUp();
86 }
87 if (oldFormat) {
88 reader.moveUp();
89 reader.moveUp();
90 }
91 return WeekFields.of(firstDayOfWeek, minimalDays);
92 }
93 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 11. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.Year;
13
14 import com.thoughtworks.xstream.converters.ConversionException;
15 import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
16
17
18 /**
19 * Converts a {@link Year} instance to string.
20 *
21 * @author J&ouml;rg Schaible
22 * @since 1.4.10
23 */
24 public class YearConverter extends AbstractSingleValueConverter {
25
26 @Override
27 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
28 return Year.class == type;
29 }
30
31 @Override
32 public Year fromString(final String str) {
33 try {
34 return Year.of(Integer.parseInt(str));
35 } catch (final NumberFormatException ex) {
36 final ConversionException exception = new ConversionException("Cannot parse value as year", ex);
37 exception.add("value", str);
38 throw exception;
39 }
40 }
41 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 11. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.YearMonth;
13 import java.time.format.DateTimeParseException;
14
15 import com.thoughtworks.xstream.converters.ConversionException;
16 import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
17
18
19 /**
20 * Converts a {@link YearMonth} instance to string.
21 *
22 * @author J&ouml;rg Schaible
23 * @since 1.4.10
24 */
25 public class YearMonthConverter extends AbstractSingleValueConverter {
26
27 @Override
28 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
29 return YearMonth.class == type;
30 }
31
32 @Override
33 public YearMonth fromString(final String str) {
34 try {
35 return YearMonth.parse(str);
36 } catch (final DateTimeParseException ex) {
37 final ConversionException exception = new ConversionException("Cannot parse value as year month", ex);
38 exception.add("value", str);
39 throw exception;
40 }
41 }
42 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 8. February 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.DateTimeException;
13 import java.time.ZoneId;
14 import java.time.zone.ZoneRulesException;
15
16 import com.thoughtworks.xstream.converters.ConversionException;
17 import com.thoughtworks.xstream.converters.SingleValueConverter;
18
19
20 /**
21 * Converts a {@link ZoneId} instance to string.
22 *
23 * @author J&ouml;rg Schaible
24 * @since 1.4.10
25 */
26 public class ZoneIdConverter implements SingleValueConverter {
27
28 @Override
29 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
30 return ZoneId.class.isAssignableFrom(type);
31 }
32
33 @Override
34 public ZoneId fromString(final String str) {
35 ConversionException exception;
36 try {
37 return ZoneId.of(str);
38 } catch (final ZoneRulesException e) {
39 exception = new ConversionException("Not a valid zone id", e);
40 } catch (final DateTimeException e) {
41 exception = new ConversionException("Cannot parse value as zone id", e);
42 }
43 exception.add("value", str);
44 throw exception;
45 }
46
47 @Override
48 public String toString(final Object obj) {
49 if (obj == null) {
50 return null;
51 }
52 final ZoneId zoneId = (ZoneId)obj;
53 return zoneId.getId();
54 }
55 }
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 13. January 2017 by Matej Cimbora
9 */
10 package com.thoughtworks.xstream.converters.time;
11
12 import java.time.ZonedDateTime;
13 import java.time.format.DateTimeFormatter;
14 import java.time.format.DateTimeFormatterBuilder;
15 import java.time.format.DateTimeParseException;
16 import java.time.temporal.ChronoField;
17
18 import com.thoughtworks.xstream.converters.ConversionException;
19 import com.thoughtworks.xstream.converters.SingleValueConverter;
20
21
22 /**
23 * Converts a {@link ZonedDateTime} to a string.
24 *
25 * @author Matej Cimbora
26 * @since 1.4.10
27 */
28 public class ZonedDateTimeConverter implements SingleValueConverter {
29
30 private static final DateTimeFormatter FORMATTER;
31
32 static {
33 FORMATTER = new DateTimeFormatterBuilder()
34 .appendPattern("uuuu-MM-dd'T'HH:mm:ss")
35 .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
36 .appendOffsetId()
37 .appendLiteral("[")
38 .appendZoneId()
39 .appendLiteral("]")
40 .toFormatter();
41 }
42
43 @Override
44 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
45 return ZonedDateTime.class == type;
46 }
47
48 @Override
49 public String toString(final Object obj) {
50 if (obj == null) {
51 return null;
52 }
53
54 final ZonedDateTime zonedDateTime = (ZonedDateTime)obj;
55 return FORMATTER.format(zonedDateTime);
56 }
57
58 @Override
59 public Object fromString(final String str) {
60 try {
61 return ZonedDateTime.parse(str);
62 } catch (final DateTimeParseException e) {
63 final ConversionException exception = new ConversionException("Cannot parse value as zoned date time", e);
64 exception.add("value", str);
65 throw exception;
66 }
67 }
68
69 }
0 <!--
1 * Copyright (C) 2017 XStream committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 12. February 2017 by Joerg Schaible
9 -->
10 <body>
11 <p>Extra converters for the java.time package.</p>
12 </body>
00 /*
11 * Copyright (C) 2004, 2005, 2006 Joe Walnes.
2 * Copyright (C) 2006, 2007, 2008, 2009, 2011, 2013, 2016 XStream Committers.
2 * Copyright (C) 2006, 2007, 2008, 2009, 2011, 2013, 2016, 2017 XStream Committers.
33 * All rights reserved.
44 *
55 * The software in this package is published under the terms of the BSD
1919
2020 import java.util.Collections;
2121 import java.util.Iterator;
22 import java.util.LinkedHashMap;
2223 import java.util.Map;
2324 import java.util.WeakHashMap;
2425
4950 if (cachedConverter != null) {
5051 return cachedConverter;
5152 }
53
54 final Map errors = new LinkedHashMap();
5255 Iterator iterator = converters.iterator();
5356 while (iterator.hasNext()) {
5457 Converter converter = (Converter) iterator.next();
55 if (converter.canConvert(type)) {
56 typeToConverterMap.put(type, converter);
57 return converter;
58 try {
59 if (converter.canConvert(type)) {
60 typeToConverterMap.put(type, converter);
61 return converter;
62 }
63 } catch (final RuntimeException e) {
64 errors.put(converter.getClass().getName(), e.getMessage());
65 } catch (final LinkageError e) {
66 errors.put(converter.getClass().getName(), e.getMessage());
5867 }
5968 }
60 ConversionException exception = new ConversionException("No converter specified");
69
70 final ConversionException exception = new ConversionException(errors.isEmpty()
71 ? "No converter specified"
72 : "No converter available");
6173 exception.add("type", type.getName());
74 iterator = errors.entrySet().iterator();
75 while (iterator.hasNext()) {
76 final Map.Entry entry = (Map.Entry)iterator.next();
77 exception.add("converter", entry.getKey().toString());
78 exception.add("message", entry.getValue().toString());
79 }
6280 throw exception;
6381 }
6482
6684 converters.add(converter, priority);
6785 for (Iterator iter = typeToConverterMap.keySet().iterator(); iter.hasNext();) {
6886 Class type = (Class) iter.next();
69 if (converter.canConvert(type)) {
70 iter.remove();
87 try {
88 if (converter.canConvert(type)) {
89 iter.remove();
90 }
91 } catch (final RuntimeException e) {
92 // ignore
93 } catch (final LinkageError e) {
94 // ignore
7195 }
7296 }
7397 }
00 /*
11 * Copyright (C) 2004, 2005, 2006 Joe Walnes.
2 * Copyright (C) 2006, 2007, 2008, 2010, 2011, 2012, 2013, 2014, 2015 XStream Committers.
2 * Copyright (C) 2006, 2007, 2008, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 XStream Committers.
33 * All rights reserved.
44 *
55 * The software in this package is published under the terms of the BSD
201201 }
202202
203203 /**
204 * @deprecated As of 1.4.4, minimal JDK version will be 1.6 for next major release
204 * @deprecated As of 1.4.4, minimal JDK version will be 1.7 for next major release
205205 */
206206 public static boolean is15() {
207207 return majorJavaVersion >= 1.5f;
208208 }
209209
210210 /**
211 * @deprecated As of 1.4.4, minimal JDK version will be 1.6 for next major release
211 * @deprecated As of 1.4.4, minimal JDK version will be 1.7 for next major release
212212 */
213213 public static boolean is16() {
214214 return majorJavaVersion >= 1.6f;
216216
217217 /**
218218 * @since 1.4
219 * @deprecated As of 1.4.10, minimal JDK version will be 1.7 for next major release
219220 */
220221 public static boolean is17() {
221222 return majorJavaVersion >= 1.7f;
230231
231232 /**
232233 * @since 1.4.8
234 * @deprecated As of upcoming use {@link #is9()}
233235 */
234236 public static boolean is19() {
235237 return majorJavaVersion >= 1.9f;
238 }
239
240 /**
241 * @since 1.4.10
242 */
243 public static boolean is9() {
244 return majorJavaVersion >= 9f;
236245 }
237246
238247 private static boolean isIBM() {
0 /*
1 * Copyright (C) 2017 XStream Committers.
2 * All rights reserved.
3 *
4 * The software in this package is published under the terms of the BSD
5 * style license a copy of which has been included with this distribution in
6 * the LICENSE.txt file.
7 *
8 * Created on 05. May 2017 by Joerg Schaible
9 */
10 package com.thoughtworks.xstream.core.util;
11
12 import java.time.Instant;
13 import java.time.LocalDate;
14 import java.time.LocalDateTime;
15 import java.time.LocalTime;
16 import java.time.MonthDay;
17 import java.time.OffsetDateTime;
18 import java.time.OffsetTime;
19 import java.time.Year;
20 import java.time.YearMonth;
21 import java.time.ZoneId;
22 import java.time.ZoneOffset;
23 import java.time.format.DateTimeFormatter;
24 import java.time.format.DateTimeFormatterBuilder;
25 import java.time.format.DateTimeParseException;
26 import java.time.temporal.ChronoField;
27 import java.time.temporal.IsoFields;
28 import java.time.temporal.TemporalAccessor;
29 import java.time.temporal.WeekFields;
30 import java.util.Calendar;
31 import java.util.GregorianCalendar;
32 import java.util.Locale;
33
34 import com.thoughtworks.xstream.converters.ConversionException;
35 import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
36
37
38 /**
39 * A converter for {@link GregorianCalendar} conforming to the ISO8601 standard based on java.time.
40 * <p>
41 * The converter will always serialize the calendar value in UTC and deserialize it to a value in the current default
42 * time zone.
43 * </p>
44 *
45 * @author J&ouml;rg Schaible
46 * @see <a href="http://www.iso.org/iso/home/store/catalogue_ics/catalogue_detail_ics.htm?csnumber=40874">ISO 8601</a>
47 * @since 1.4.10
48 */
49 public class ISO8601JavaTimeConverter extends AbstractSingleValueConverter {
50 private static final DateTimeFormatter STD_DATE_TIME = new DateTimeFormatterBuilder()
51 .appendPattern("yyyy-MM-dd'T'HH:mm:ss")
52 .appendFraction(ChronoField.NANO_OF_SECOND, 3, 9, true)
53 .appendOffsetId()
54 .toFormatter();
55 private static final DateTimeFormatter STD_ORDINAL_DATE_TIME = new DateTimeFormatterBuilder()
56 .appendPattern("yyyy-DDD'T'HH:mm:ss")
57 .appendFraction(ChronoField.MILLI_OF_SECOND, 0, 3, true)
58 .appendOffsetId()
59 .toFormatter();
60 private static final DateTimeFormatter BASIC_DATE_TIME = new DateTimeFormatterBuilder()
61 .appendPattern("yyyyMMdd'T'HHmmss")
62 .appendFraction(ChronoField.MILLI_OF_SECOND, 0, 3, true)
63 .appendOffsetId()
64 .toFormatter();
65 private static final DateTimeFormatter BASIC_ORDINAL_DATE_TIME = new DateTimeFormatterBuilder()
66 .appendPattern("yyyyDDD'T'HHmmss")
67 .appendFraction(ChronoField.MILLI_OF_SECOND, 0, 3, true)
68 .appendOffsetId()
69 .toFormatter();
70 private static final DateTimeFormatter BASIC_TIME = new DateTimeFormatterBuilder()
71 .appendPattern("HHmmss")
72 .appendFraction(ChronoField.MILLI_OF_SECOND, 0, 3, true)
73 .appendOffsetId()
74 .toFormatter();
75 private static final DateTimeFormatter ISO_TTIME = new DateTimeFormatterBuilder()
76 .appendPattern("'T'HH:mm:ss")
77 .appendFraction(ChronoField.MILLI_OF_SECOND, 0, 3, true)
78 .appendOffsetId()
79 .toFormatter();
80 private static final DateTimeFormatter BASIC_TTIME = new DateTimeFormatterBuilder()
81 .appendPattern("'T'HHmmss")
82 .appendFraction(ChronoField.MILLI_OF_SECOND, 0, 3, true)
83 .appendOffsetId()
84 .toFormatter();
85 private static final DateTimeFormatter ISO_WEEK_DATE_TIME = new DateTimeFormatterBuilder()
86 .appendPattern("YYYY-'W'ww-e'T'HH:mm:ss")
87 .appendFraction(ChronoField.MILLI_OF_SECOND, 0, 3, true)
88 .appendOffsetId()
89 .toFormatter();
90 private static final DateTimeFormatter BASIC_WEEK_DATE_TIME = new DateTimeFormatterBuilder()
91 .appendPattern("YYYY'W'wwe'T'HHmmss")
92 .appendFraction(ChronoField.MILLI_OF_SECOND, 0, 3, true)
93 .appendOffsetId()
94 .toFormatter();
95 private static final DateTimeFormatter BASIC_ORDINAL_DATE = new DateTimeFormatterBuilder()
96 .appendPattern("yyyyDDD")
97 .toFormatter();
98 private static final DateTimeFormatter BASIC_WEEK_DATE = new DateTimeFormatterBuilder()
99 .appendPattern("YYYY'W'wwe")
100 .toFormatter();
101 private static final DateTimeFormatter STD_DATE_HOUR = new DateTimeFormatterBuilder()
102 .appendPattern("yyyy-MM-dd'T'HH")
103 .toFormatter();
104 private static final DateTimeFormatter STD_HOUR = new DateTimeFormatterBuilder().appendPattern("HH").toFormatter();
105 private static final DateTimeFormatter STD_YEAR_WEEK = new DateTimeFormatterBuilder()
106 .appendPattern("YYYY-'W'ww")
107 .parseDefaulting(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR, 1)
108 .toFormatter();
109
110 @Override
111 public boolean canConvert(@SuppressWarnings("rawtypes") final Class type) {
112 return false;
113 }
114
115 @Override
116 public Object fromString(final String str) {
117 try {
118 final OffsetDateTime odt = OffsetDateTime.parse(str);
119 return GregorianCalendar.from(odt.atZoneSameInstant(ZoneId.systemDefault()));
120 } catch (final DateTimeParseException e) {