1 package com.vladmihalcea.hibernate.type.basic.internal;
2
3 import org.hibernate.type.descriptor.WrapperOptions;
4 import org.hibernate.type.descriptor.java.AbstractTypeDescriptor;
5
6 import java.time.Instant;
7 import java.time.LocalDate;
8 import java.time.MonthDay;
9 import java.time.ZoneId;
10 import java.util.Date;
11 import java.util.Objects;
12
13 /**
14  * @author Mladen Savic (mladensavic94@gmail.com)
15  */

16
17 public class MonthDayTypeDescriptor extends AbstractTypeDescriptor<MonthDay> {
18
19     public static final MonthDayTypeDescriptor INSTANCE = new MonthDayTypeDescriptor();
20
21     protected MonthDayTypeDescriptor() {
22         super(MonthDay.class);
23     }
24
25     @Override
26     public MonthDay fromString(String s) {
27         return MonthDay.parse(s);
28     }
29
30     @SuppressWarnings({"unchecked"})
31     @Override
32     public <X> X unwrap(MonthDay monthDay, Class<X> type, WrapperOptions wrapperOptions) {
33         if (monthDay == null) {
34             return null;
35         }
36         if (String.class.isAssignableFrom(type)) {
37             return (X) toString(monthDay);
38         }
39         if (Number.class.isAssignableFrom(type)) {
40             Integer numericValue = (monthDay.getMonthValue() * 100) + monthDay.getDayOfMonth();
41             return (X) (numericValue);
42         }
43         if (Date.class.isAssignableFrom(type)) {
44             int currentYear = LocalDate.now().getYear();
45             return (X) java.sql.Date.valueOf(monthDay.atYear(currentYear));
46         }
47
48         throw unknownUnwrap(type);
49     }
50
51     @Override
52     public <X> MonthDay wrap(X value, WrapperOptions wrapperOptions) {
53         if (value == null) {
54             return null;
55         }
56         if (value instanceof String) {
57             return fromString((String) value);
58         }
59         if (value instanceof Number) {
60             int numericValue = ((Number) (value)).intValue();
61             int month = numericValue / 100;
62             int dayOfMonth = numericValue % 100;
63             return MonthDay.of(month, dayOfMonth);
64         }
65         if (value instanceof Date) {
66             Date date = (Date) value;
67             return MonthDay.from(Instant.ofEpochMilli(date.getTime())
68                 .atZone(ZoneId.systemDefault())
69                 .toLocalDate());
70         }
71         throw unknownWrap(value.getClass());
72     }
73
74     @Override
75     public boolean areEqual(MonthDay one, MonthDay another) {
76         return Objects.equals(one, another);
77     }
78
79     @Override
80     public String toString(MonthDay value) {
81         return value.toString();
82     }
83 }
84