KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > config > schema > dynamic > IntXPathBasedConfigItem


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.config.schema.dynamic;
5
6 import org.apache.xmlbeans.XmlException;
7 import org.apache.xmlbeans.XmlObject;
8
9 import com.tc.config.schema.context.ConfigContext;
10 import com.tc.util.Assert;
11
12 import java.math.BigInteger JavaDoc;
13
14 /**
15  * An {@link XPathBasedConfigItem} that extracts a Java <code>int</code>.
16  */

17 public class IntXPathBasedConfigItem extends XPathBasedConfigItem implements IntConfigItem {
18
19   private static final BigInteger JavaDoc MAX_INT_AS_BIG_INTEGER = new BigInteger JavaDoc(new Integer JavaDoc(Integer.MAX_VALUE).toString());
20   private static final BigInteger JavaDoc MIN_INT_AS_BIG_INTEGER = new BigInteger JavaDoc(new Integer JavaDoc(Integer.MIN_VALUE).toString());
21
22   public IntXPathBasedConfigItem(ConfigContext context, String JavaDoc xpath) {
23     super(context, xpath);
24
25     try {
26       if (!context.hasDefaultFor(xpath) && context.isOptional(xpath)) {
27         // formatting
28
throw Assert
29             .failure("XPath '" + xpath + "' is optional and has no default. As such, you can't use it in "
30                      + "a ConfigItem returning only an int; what will we return if it's not there? Add a default "
31                      + "in the schema, or make it mandatory.");
32       }
33     } catch (XmlException xmle) {
34       throw Assert.failure("Unable to fetch default for '" + xpath + "'.");
35     }
36   }
37
38   protected Object JavaDoc fetchDataFromXmlObject(XmlObject xmlObject) {
39     BigInteger JavaDoc out = (BigInteger JavaDoc) super.fetchDataFromXmlObjectByReflection(xmlObject, "getBigIntegerValue");
40     
41     if (out == null) return null;
42     
43     boolean fits = (out.compareTo(MAX_INT_AS_BIG_INTEGER) <= 0) && (out.compareTo(MIN_INT_AS_BIG_INTEGER) >= 0);
44     if (!fits) throw Assert.failure("Value " + out
45                                     + " is too big to represent as an 'int'; you should either be using a "
46                                     + "ConfigItem that uses a BigInteger to represent its data, or the schema should "
47                                     + "restrict this value to one that fits in a Java 'int'.");
48     return new Integer JavaDoc(out.intValue());
49   }
50
51   public int getInt() {
52     return ((Integer JavaDoc) getObject()).intValue();
53   }
54
55 }
56
Popular Tags