2 * Copyright (C) 2009 EDIT
3 * European Distributed Institute of Taxonomy
4 * http://www.e-taxonomy.eu
6 * The contents of this file are subject to the Mozilla Public License Version 1.1
7 * See LICENSE.TXT at the top of this package for the full license terms.
10 package eu
.etaxonomy
.cdm
.jaxb
;
12 import java
.util
.regex
.Matcher
;
13 import java
.util
.regex
.Pattern
;
15 import javax
.xml
.bind
.annotation
.adapters
.XmlAdapter
;
17 import org
.joda
.time
.DateTimeFieldType
;
18 import org
.joda
.time
.Partial
;
20 public class PartialAdapter
extends XmlAdapter
<String
, Partial
> {
22 protected static Pattern PATTERN
;
23 private static String REGEX
= "^(\\d{4})(?:\\-(\\d{1,2})(?:\\-(\\d{1,2})(?:T(\\d{2})(?:\\:(\\d{2})(?:\\:(\\d{2})(?:\\.(\\d+))?)?)?)?)?)?$";
26 PATTERN
= Pattern
.compile(REGEX
);
30 public String
marshal(Partial partial
) throws Exception
{
31 StringBuilder stringBuilder
= new StringBuilder();
32 int[] values
= partial
.getValues();
34 switch(values
.length
) {
36 stringBuilder
.append("." + values
[6]);
38 stringBuilder
.insert(0,":" + values
[5]);
40 stringBuilder
.insert(0,":" + values
[4]);
42 stringBuilder
.insert(0, "T" + values
[3]);
44 stringBuilder
.insert(0, "-" + values
[2]);
46 stringBuilder
.insert(0, "-" + values
[1]);
48 stringBuilder
.insert(0, values
[0]);
51 return stringBuilder
.toString();
55 public Partial
unmarshal(String string
) throws Exception
{
56 Matcher matcher
= PATTERN
.matcher(string
);
57 if(matcher
.matches()) {
58 int nonNullGroups
= 0;
59 for(int i
= 1; i
<= matcher
.groupCount(); i
++) {
60 if(matcher
.group(i
) != null)
63 DateTimeFieldType
[] dateTimeFieldTypes
= new DateTimeFieldType
[nonNullGroups
];
64 int[] values
= new int[nonNullGroups
];
65 switch(nonNullGroups
) {
67 dateTimeFieldTypes
[6] = DateTimeFieldType
.millisOfSecond();
68 values
[6] = Integer
.parseInt(matcher
.group(7));
70 dateTimeFieldTypes
[5] = DateTimeFieldType
.secondOfMinute();
71 values
[5] = Integer
.parseInt(matcher
.group(6));
73 dateTimeFieldTypes
[4] = DateTimeFieldType
.minuteOfHour();
74 values
[4] = Integer
.parseInt(matcher
.group(5));
76 dateTimeFieldTypes
[3] = DateTimeFieldType
.hourOfDay();
77 values
[3] = Integer
.parseInt(matcher
.group(4));
79 dateTimeFieldTypes
[2] = DateTimeFieldType
.dayOfMonth();
80 values
[2] = Integer
.parseInt(matcher
.group(3));
82 dateTimeFieldTypes
[1] = DateTimeFieldType
.monthOfYear();
83 values
[1] = Integer
.parseInt(matcher
.group(2));
85 dateTimeFieldTypes
[0] = DateTimeFieldType
.year();
86 values
[0] = Integer
.parseInt(matcher
.group(1));
88 return new Partial(dateTimeFieldTypes
, values
);
90 throw new RuntimeException("Could not parse " + string
+ " with regex " + PartialAdapter
.REGEX
);