1
2
3
4
5
6 package dev.metaschema.core.metapath.item.atomic;
7
8 import dev.metaschema.core.datatype.adapter.MetaschemaDataTypeProvider;
9 import dev.metaschema.core.metapath.function.InvalidValueForCastFunctionException;
10 import dev.metaschema.core.metapath.item.atomic.impl.BooleanItemImpl;
11 import dev.metaschema.core.metapath.type.IAtomicOrUnionType;
12 import dev.metaschema.core.metapath.type.InvalidTypeMetapathException;
13 import edu.umd.cs.findbugs.annotations.NonNull;
14
15
16
17
18 public interface IBooleanItem extends IAnyAtomicItem {
19
20
21
22 @NonNull
23 IBooleanItem TRUE = new BooleanItemImpl(true);
24
25
26
27 @NonNull
28 IBooleanItem FALSE = new BooleanItemImpl(false);
29
30
31
32
33
34
35 @NonNull
36 static IAtomicOrUnionType<IBooleanItem> type() {
37 return MetaschemaDataTypeProvider.BOOLEAN.getItemType();
38 }
39
40 @Override
41 default IAtomicOrUnionType<IBooleanItem> getType() {
42 return type();
43 }
44
45
46
47
48
49
50
51
52
53
54
55
56
57 @NonNull
58 static IBooleanItem valueOf(@NonNull String value) {
59 IBooleanItem retval;
60 if ("1".equals(value)) {
61 retval = TRUE;
62 } else {
63 try {
64 retval = valueOf(MetaschemaDataTypeProvider.BOOLEAN.parse(value));
65 } catch (IllegalArgumentException ex) {
66 throw new InvalidTypeMetapathException(
67 null,
68 String.format("Invalid boolean value '%s'. %s",
69 value,
70 ex.getLocalizedMessage()),
71 ex);
72 }
73 }
74 return retval;
75 }
76
77
78
79
80
81
82
83
84 @NonNull
85 static IBooleanItem valueOf(boolean value) {
86 return value ? TRUE : FALSE;
87 }
88
89
90
91
92
93
94
95
96
97
98
99 @NonNull
100 static IBooleanItem cast(@NonNull IAnyAtomicItem item) {
101 IBooleanItem retval;
102 if (item instanceof INumericItem) {
103 retval = valueOf(((INumericItem) item).toEffectiveBoolean());
104 } else {
105 try {
106 retval = valueOf(INumericItem.cast(item).toEffectiveBoolean());
107 } catch (InvalidValueForCastFunctionException ex) {
108 try {
109 retval = valueOf(item.asString());
110 } catch (IllegalStateException | InvalidTypeMetapathException ex2) {
111
112 InvalidValueForCastFunctionException thrown = new InvalidValueForCastFunctionException(ex2);
113 thrown.addSuppressed(ex);
114 throw thrown;
115 }
116 }
117 }
118 return retval;
119 }
120
121 @Override
122 default IBooleanItem castAsType(IAnyAtomicItem item) {
123 return cast(item);
124 }
125
126
127
128
129
130
131 boolean toBoolean();
132
133
134
135
136
137
138 @NonNull
139 default IBooleanItem negate() {
140 return this.toBoolean() ? FALSE : TRUE;
141 }
142
143
144
145
146
147
148
149
150
151 default int compareTo(@NonNull IBooleanItem item) {
152 return Boolean.compare(toBoolean(), item.toBoolean());
153 }
154 }