Project

General

Profile

Download (2.63 KB) Statistics
| Branch: | Tag: | Revision:
1
package eu.etaxonomy.cdm.jaxb;
2

    
3
import java.util.regex.Matcher;
4
import java.util.regex.Pattern;
5

    
6
import javax.xml.bind.annotation.adapters.XmlAdapter;
7

    
8
import org.joda.time.DateTimeFieldType;
9
import org.joda.time.Partial;
10

    
11
public class PartialAdapter extends XmlAdapter<String, Partial> {
12
	
13
	protected static Pattern PATTERN;
14
	private static String REGEX = "^(\\d{4})(?:\\-(\\d{1,2})(?:\\-(\\d{1,2})(?:T(\\d{2})(?:\\:(\\d{2})(?:\\:(\\d{2})(?:\\.(\\d+))?)?)?)?)?)?$";
15
	
16
	static {
17
		PATTERN = Pattern.compile(REGEX);
18
	}
19

    
20
	@Override
21
	public String marshal(Partial partial) throws Exception {
22
		StringBuilder stringBuilder = new StringBuilder();
23
		int[] values = partial.getValues();
24
		
25
		switch(values.length) {
26
		case 7:
27
			stringBuilder.append("." + values[6]);
28
		case 6:
29
			stringBuilder.insert(0,":" + values[5]);
30
		case 5: 
31
			stringBuilder.insert(0,":" + values[4]);
32
		case 4:
33
			stringBuilder.insert(0, "T" + values[3]);
34
		case 3:
35
			stringBuilder.insert(0, "-" + values[2]);
36
		case 2:
37
			stringBuilder.insert(0, "-" + values[1]);
38
		case 1:
39
			stringBuilder.insert(0, values[0]);
40
		}
41
		
42
		return stringBuilder.toString();
43
	}
44

    
45
	@Override
46
	public Partial unmarshal(String string) throws Exception {
47
		Matcher matcher = PATTERN.matcher(string);
48
		if(matcher.matches()) {
49
            int nonNullGroups = 0;
50
			for(int i = 1; i <= matcher.groupCount(); i++) {
51
				if(matcher.group(i) != null)
52
					nonNullGroups++;
53
			}
54
			DateTimeFieldType[] dateTimeFieldTypes = new DateTimeFieldType[nonNullGroups];
55
			int[] values = new int[nonNullGroups];
56
			switch(nonNullGroups) {
57
			case 7:
58
				dateTimeFieldTypes[6] = DateTimeFieldType.millisOfSecond();
59
				values[6] = Integer.parseInt(matcher.group(7));
60
			case 6:
61
				dateTimeFieldTypes[5] = DateTimeFieldType.secondOfMinute();
62
				values[5] = Integer.parseInt(matcher.group(6));
63
			case 5:
64
				dateTimeFieldTypes[4] = DateTimeFieldType.minuteOfHour();
65
				values[4] = Integer.parseInt(matcher.group(5));
66
			case 4:
67
				dateTimeFieldTypes[3] = DateTimeFieldType.hourOfDay();
68
				values[3] = Integer.parseInt(matcher.group(4));
69
			case 3:
70
				dateTimeFieldTypes[2] = DateTimeFieldType.dayOfMonth();
71
				values[2] = Integer.parseInt(matcher.group(3));
72
			case 2:
73
				dateTimeFieldTypes[1] = DateTimeFieldType.monthOfYear();
74
				values[1] = Integer.parseInt(matcher.group(2));
75
			case 1:
76
				dateTimeFieldTypes[0] = DateTimeFieldType.year();
77
				values[0] = Integer.parseInt(matcher.group(1));
78
			}
79
			return new Partial(dateTimeFieldTypes, values);
80
		} else {
81
			throw new RuntimeException("Could not parse " + string + " with regex " + PartialAdapter.REGEX);
82
		}
83
	}
84

    
85
}
(12-12/14)