1 package net.sf.saxon.value; 2 3 import net.sf.saxon.om.FastStringBuffer; 4 import net.sf.saxon.trans.DynamicError; 5 import net.sf.saxon.trans.XPathException; 6 import net.sf.saxon.type.BuiltInAtomicType; 7 import net.sf.saxon.type.ItemType; 8 import net.sf.saxon.type.Type; 9 import net.sf.saxon.type.ValidationException; 10 import net.sf.saxon.ConversionContext; 11 12 import java.util.Calendar ; 13 import java.util.GregorianCalendar ; 14 import java.util.regex.Matcher ; 15 import java.util.regex.Pattern ; 16 17 20 21 public class GYearValue extends DateValue { 22 23 private static Pattern regex = 24 Pattern.compile("(-?[0-9]+)(Z|[+-][0-9][0-9]:[0-9][0-9])?"); 25 26 public GYearValue(){}; 27 28 public GYearValue(CharSequence value) throws XPathException { 29 Matcher m = regex.matcher(value); 30 if (!m.matches()) { 31 throw new DynamicError("Cannot convert '" + value + "' to a gYear"); 32 } 33 String base = m.group(1); 34 String tz = m.group(2); 35 String date = base + "-01-01" + (tz==null ? "" : tz); 36 setLexicalValue(date); 37 } 38 39 public GYearValue(GregorianCalendar calendar, boolean timezoneSpecified, int tzoffset) { 40 super(calendar, timezoneSpecified, tzoffset); 41 } 42 43 47 48 public ItemType getItemType() { 49 return Type.G_YEAR_TYPE; 50 } 51 52 53 59 60 public AtomicValue convertPrimitive(BuiltInAtomicType requiredType, boolean validate, ConversionContext conversion) { 61 switch(requiredType.getPrimitiveType()) { 62 case Type.G_YEAR: 63 case Type.ATOMIC: 64 case Type.ITEM: 65 return this; 66 67 case Type.STRING: 68 return new StringValue(getStringValueCS()); 69 case Type.UNTYPED_ATOMIC: 70 return new UntypedAtomicValue(getStringValueCS()); 71 default: 72 ValidationException err = new ValidationException("Cannot convert gYear to " + 73 requiredType.getDisplayName()); 74 err.setErrorCode("FORG0001"); 75 return new ValidationErrorValue(err); 76 } 77 } 78 79 public String getStringValue() { 80 81 FastStringBuffer sb = new FastStringBuffer(16); 82 int era = calendar.get(GregorianCalendar.ERA); 83 int year = calendar.get(Calendar.YEAR); 84 if (era == GregorianCalendar.BC) { 85 sb.append('-'); 86 } 87 DateTimeValue.appendString(sb, year, (year>9999 ? (calendar.get(Calendar.YEAR)+"").length() : 4)); 88 89 if (zoneSpecified) { 90 DateTimeValue.appendTimezone(tzOffset, sb); 91 } 92 93 return sb.toString(); 94 95 } 96 } 97 98 | Popular Tags |