1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.juneau;
18
19 import static org.apache.juneau.TestUtils.*;
20 import static org.apache.juneau.commons.utils.CollectionUtils.*;
21 import static org.apache.juneau.junit.bct.BctAssertions.*;
22 import static org.junit.jupiter.api.Assertions.*;
23
24 import java.util.*;
25
26 import org.apache.juneau.collections.*;
27 import org.junit.jupiter.api.*;
28
29 @SuppressWarnings("rawtypes")
30 class DataConversion_Test extends TestBase {
31
32 @BeforeEach
33 void beforeTest() {
34 setLocale(Locale.US);
35 }
36
37 @AfterEach
38 void afterTest() {
39 unsetLocale();
40 }
41
42
43
44
45 @Test void a01_basic() throws Exception {
46 var m = new JsonMap();
47
48
49 m.put("x", 123);
50 assertEquals(123, (int)m.getInt("x"));
51 assertEquals(123, (long)m.getLong("x"));
52
53
54 m.put("x", true);
55 assertEquals(true, (boolean)m.getBoolean("x"));
56
57
58 m.put("x", null);
59 assertNull(m.getString("x"));
60 assertNull(m.getInt("x"));
61 assertNull(m.getLong("x"));
62 assertNull(m.getBoolean("x"));
63 assertNull(m.getMap("x"));
64 assertNull(m.getList("x"));
65
66
67 m.put("x", new HashMap());
68 assertEquals("{}", m.getString("x"));
69
70
71 m.put("x", JsonMap.ofJson("{foo:123}"));
72 assertEquals("{foo:123}", m.getString("x"));
73
74
75 var s = new HashSet<Integer>();
76 s.add(123);
77 m.put("x", s);
78 assertEquals("[123]", m.getString("x"));
79
80
81 m.put("x", JsonList.ofJson("[123]"));
82 assertEquals("[123]", m.getString("x"));
83 assertSize(1, m.getList("x"));
84
85
86 m.put("x", a(123));
87 assertEquals("[123]", m.getString("x"));
88 assertSize(1, m.getList("x"));
89
90
91 m.put("x", TestEnum.ENUM2);
92 assertEquals("ENUM2", m.getString("x"));
93 assertFalse(m.getBoolean("x"));
94 assertThrows(InvalidDataConversionException.class, ()->m.getMap("x"));
95
96
97 m.put("x", new NotABean("foo"));
98 assertEquals("foo", m.getString("x"));
99 assertThrows(InvalidDataConversionException.class, ()->m.getInt("x"));
100 assertThrows(InvalidDataConversionException.class, ()->m.getLong("x"));
101 assertFalse(m.getBoolean("x"));
102 assertThrows(InvalidDataConversionException.class, ()->m.getMap("x"));
103 }
104
105 public enum TestEnum {
106 ENUM0, ENUM1, ENUM2
107 }
108
109 public class NotABean {
110 private String arg;
111
112 public NotABean(String arg) {
113 this.arg = arg;
114 }
115
116 @Override
117 public String toString() {
118 return arg;
119 }
120 }
121
122
123
124
125 @Test void a02_objectSwaps() throws Exception {
126 var s = "2001-12-21T12:34:56Z";
127 var bc = BeanContext.DEFAULT;
128 var c = bc.convertToType(s, GregorianCalendar.class);
129 assertEquals(2001, c.get(Calendar.YEAR));
130 var c2 = bc.convertToType(s, Calendar.class);
131 assertEquals(2001, c2.get(Calendar.YEAR));
132 s = bc.convertToType(c2, String.class);
133 assertEquals("2001-12-21T12:34:56Z", s);
134 }
135 }