1 61 62 63 package org.jaxen.function; 64 65 import java.util.Iterator ; 66 import java.util.List ; 67 68 import org.jaxen.Context; 69 import org.jaxen.Function; 70 import org.jaxen.FunctionCallException; 71 import org.jaxen.Navigator; 72 import org.jaxen.UnsupportedAxisException; 73 74 114 public class LangFunction implements Function 115 { 116 private static final String LANG_LOCALNAME = "lang"; 117 private static final String XMLNS_URI = 118 "http://www.w3.org/XML/1998/namespace"; 119 120 121 124 public LangFunction() {} 125 126 127 141 public Object call(Context context, 142 List args) throws FunctionCallException 143 { 144 if (args.size() != 1) { 145 throw new FunctionCallException("lang() requires exactly one argument."); 146 } 147 148 Object arg = args.get(0); 149 150 try { 151 return evaluate(context.getNodeSet(), arg, context.getNavigator() ); 152 } 153 catch(UnsupportedAxisException e) { 154 throw new FunctionCallException("Can't evaluate lang()", 155 e); 156 } 157 158 } 159 160 private static Boolean evaluate(List contextNodes, Object lang, Navigator nav) 161 throws UnsupportedAxisException 162 { 163 return evaluate(contextNodes.get(0), 164 StringFunction.evaluate(lang, nav), nav) 165 ? Boolean.TRUE : Boolean.FALSE; 166 } 167 168 private static boolean evaluate(Object node, String lang, Navigator nav) 169 throws UnsupportedAxisException 170 { 171 172 Object element = node; 173 if (! nav.isElement(element)) { 174 element = nav.getParentNode(node); 175 } 176 while (element != null && nav.isElement(element)) 177 { 178 Iterator attrs = nav.getAttributeAxisIterator(element); 179 while(attrs.hasNext()) 180 { 181 Object attr = attrs.next(); 182 if(LANG_LOCALNAME.equals(nav.getAttributeName(attr)) && 183 XMLNS_URI.equals(nav.getAttributeNamespaceUri(attr))) 184 { 185 return 186 isSublang(nav.getAttributeStringValue(attr), lang); 187 } 188 } 189 element = nav.getParentNode(element); 190 } 191 return false; 192 } 193 194 private static boolean isSublang(String sublang, String lang) 195 { 196 if(sublang.equalsIgnoreCase(lang)) 197 { 198 return true; 199 } 200 int ll = lang.length(); 201 return 202 sublang.length() > ll && 203 sublang.charAt(ll) == '-' && 204 sublang.substring(0, ll).equalsIgnoreCase(lang); 205 } 206 207 } 208 209 | Popular Tags |