01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.config.schema.dynamic;
05:
06: import org.apache.xmlbeans.XmlException;
07: import org.apache.xmlbeans.XmlObject;
08:
09: import com.tc.config.schema.context.ConfigContext;
10: import com.tc.util.Assert;
11:
12: import java.math.BigInteger;
13:
14: /**
15: * An {@link XPathBasedConfigItem} that extracts a Java <code>int</code>.
16: */
17: public class IntXPathBasedConfigItem extends XPathBasedConfigItem
18: implements IntConfigItem {
19:
20: private static final BigInteger MAX_INT_AS_BIG_INTEGER = new BigInteger(
21: new Integer(Integer.MAX_VALUE).toString());
22: private static final BigInteger MIN_INT_AS_BIG_INTEGER = new BigInteger(
23: new Integer(Integer.MIN_VALUE).toString());
24:
25: public IntXPathBasedConfigItem(ConfigContext context, String xpath) {
26: super (context, xpath);
27:
28: try {
29: if (!context.hasDefaultFor(xpath)
30: && context.isOptional(xpath)) {
31: // formatting
32: throw Assert
33: .failure("XPath '"
34: + xpath
35: + "' is optional and has no default. As such, you can't use it in "
36: + "a ConfigItem returning only an int; what will we return if it's not there? Add a default "
37: + "in the schema, or make it mandatory.");
38: }
39: } catch (XmlException xmle) {
40: throw Assert.failure("Unable to fetch default for '"
41: + xpath + "'.");
42: }
43: }
44:
45: protected Object fetchDataFromXmlObject(XmlObject xmlObject) {
46: BigInteger out = (BigInteger) super
47: .fetchDataFromXmlObjectByReflection(xmlObject,
48: "getBigIntegerValue");
49:
50: if (out == null)
51: return null;
52:
53: boolean fits = (out.compareTo(MAX_INT_AS_BIG_INTEGER) <= 0)
54: && (out.compareTo(MIN_INT_AS_BIG_INTEGER) >= 0);
55: if (!fits)
56: throw Assert
57: .failure("Value "
58: + out
59: + " is too big to represent as an 'int'; you should either be using a "
60: + "ConfigItem that uses a BigInteger to represent its data, or the schema should "
61: + "restrict this value to one that fits in a Java 'int'.");
62: return new Integer(out.intValue());
63: }
64:
65: public int getInt() {
66: return ((Integer) getObject()).intValue();
67: }
68:
69: }
|