1
2
3
4
5
6 package dev.metaschema.core.metapath.item.atomic;
7
8 import java.time.Period;
9
10 import dev.metaschema.core.datatype.adapter.MetaschemaDataTypeProvider;
11 import dev.metaschema.core.metapath.function.InvalidValueForCastFunctionException;
12 import dev.metaschema.core.metapath.item.atomic.impl.YearMonthDurationItemImpl;
13 import dev.metaschema.core.metapath.type.IAtomicOrUnionType;
14 import dev.metaschema.core.metapath.type.InvalidTypeMetapathException;
15 import dev.metaschema.core.util.ObjectUtils;
16 import edu.umd.cs.findbugs.annotations.NonNull;
17
18
19
20
21
22 public interface IYearMonthDurationItem extends IDurationItem {
23
24
25
26
27
28 @NonNull
29 static IAtomicOrUnionType<IYearMonthDurationItem> type() {
30 return MetaschemaDataTypeProvider.YEAR_MONTH_DURATION.getItemType();
31 }
32
33 @Override
34 default IAtomicOrUnionType<IYearMonthDurationItem> getType() {
35 return type();
36 }
37
38
39
40
41
42
43
44
45
46
47
48
49 @NonNull
50 static IYearMonthDurationItem valueOf(@NonNull String value) {
51 try {
52 Period period = ObjectUtils.notNull(MetaschemaDataTypeProvider.YEAR_MONTH_DURATION.parse(value).withDays(0));
53 return valueOf(period);
54 } catch (IllegalArgumentException ex) {
55 throw new InvalidTypeMetapathException(
56 null,
57 String.format("Invalid year/month duration value '%s'.",
58 value),
59 ex);
60 }
61 }
62
63
64
65
66
67
68
69
70
71 @NonNull
72 static IYearMonthDurationItem valueOf(@NonNull Period value) {
73 return new YearMonthDurationItemImpl(ObjectUtils.notNull(value.withDays(0)));
74 }
75
76
77
78
79
80
81
82
83
84
85 @NonNull
86 static IYearMonthDurationItem valueOf(int years, int months) {
87 return valueOf(ObjectUtils.notNull(Period.of(years, months, 0)));
88 }
89
90
91
92
93
94
95 @NonNull
96 Period asPeriod();
97
98
99
100
101
102
103 default long asTotalMonths() {
104 return asPeriod().toTotalMonths();
105 }
106
107
108
109
110
111
112 @NonNull
113 default IYearMonthDurationItem negate() {
114 return valueOf(ObjectUtils.notNull(asPeriod().negated()));
115 }
116
117
118
119
120
121
122
123
124
125
126
127 @NonNull
128 static IYearMonthDurationItem cast(@NonNull IAnyAtomicItem item) {
129 try {
130 return item instanceof IYearMonthDurationItem
131 ? (IYearMonthDurationItem) item
132 : valueOf(item.asString());
133 } catch (IllegalStateException | InvalidTypeMetapathException ex) {
134
135 throw new InvalidValueForCastFunctionException(ex);
136 }
137 }
138
139 @Override
140 default IYearMonthDurationItem castAsType(IAnyAtomicItem item) {
141 return cast(item);
142 }
143
144
145
146
147
148
149
150
151
152 default int compareTo(IYearMonthDurationItem item) {
153 Period thisPeriod = asPeriod().normalized();
154 Period thatPeriod = item.asPeriod().normalized();
155
156 int result = Integer.compare(thisPeriod.getYears(), thatPeriod.getYears());
157 return result == 0 ? Integer.compare(thisPeriod.getMonths(), thatPeriod.getMonths()) : result;
158 }
159 }