|
| 1 | +package org.gitlab4j.models.utils; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.text.ParseException; |
| 5 | +import java.text.SimpleDateFormat; |
| 6 | +import java.util.Arrays; |
| 7 | +import java.util.Date; |
| 8 | + |
| 9 | +import com.fasterxml.jackson.core.JsonParseException; |
| 10 | +import com.fasterxml.jackson.core.JsonParser; |
| 11 | +import com.fasterxml.jackson.databind.DeserializationContext; |
| 12 | +import com.fasterxml.jackson.databind.JsonNode; |
| 13 | +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; |
| 14 | + |
| 15 | +public class MultiDateFormatDeserializer extends StdDeserializer<Date> { |
| 16 | + public static final String[] DATE_FORMATS = |
| 17 | + new String[] {"yyyy-MM-dd HH:mm:ss Z", "yyyy-MM-dd'T'HH:mm:ss.SSSXXX", "yyyy-MM-dd'T'HH:mm:ssXXX"}; |
| 18 | + private static final long serialVersionUID = 1L; |
| 19 | + |
| 20 | + public MultiDateFormatDeserializer() { |
| 21 | + this(null); |
| 22 | + } |
| 23 | + |
| 24 | + public MultiDateFormatDeserializer(Class<?> vc) { |
| 25 | + super(vc); |
| 26 | + } |
| 27 | + |
| 28 | + @Override |
| 29 | + /** |
| 30 | + * Deserializes a custom date in several international date formats |
| 31 | + */ |
| 32 | + public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { |
| 33 | + final String date = ((JsonNode) jp.getCodec().readTree(jp)).textValue(); |
| 34 | + if (date == null || date.isEmpty()) { |
| 35 | + return null; |
| 36 | + } |
| 37 | + for (String dateFormat : DATE_FORMATS) { |
| 38 | + try { |
| 39 | + SimpleDateFormat formatter = new SimpleDateFormat(dateFormat); |
| 40 | + return formatter.parse(date); |
| 41 | + } catch (ParseException e) { |
| 42 | + } |
| 43 | + } |
| 44 | + throw new JsonParseException( |
| 45 | + jp, "Unparseable date: \"" + date + "\". Supported formats: " + Arrays.toString(DATE_FORMATS)); |
| 46 | + } |
| 47 | +} |
0 commit comments