BUG-3876: Add jaxen-based XPath evaluation component
[yangtools.git] / yang / yang-data-jaxen / src / main / java / org / opendaylight / yangtools / yang / data / jaxen / YangFunctionContext.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.data.jaxen;
9
10 import com.google.common.base.Verify;
11 import java.util.List;
12 import org.jaxen.Context;
13 import org.jaxen.Function;
14 import org.jaxen.FunctionCallException;
15 import org.jaxen.FunctionContext;
16 import org.jaxen.UnresolvableException;
17 import org.jaxen.XPathFunctionContext;
18
19 /**
20  * A {@link FunctionContext} which contains also to YANG-specific current() function.
21  */
22 final class YangFunctionContext implements FunctionContext {
23     // Core XPath functions, as per http://tools.ietf.org/html/rfc6020#section-6.4.1
24     private static final FunctionContext XPATH_FUNCTION_CONTEXT = new XPathFunctionContext(false);
25     // current() function, as per http://tools.ietf.org/html/rfc6020#section-6.4.1
26     private static final Function CURRENT_FUNCTION = new Function() {
27         @Override
28         public NormalizedNodeContext call(final Context context, @SuppressWarnings("rawtypes") final List args)
29                 throws FunctionCallException {
30             if (!args.isEmpty()) {
31                 throw new FunctionCallException("current() takes no arguments.");
32             }
33
34             Verify.verify(context instanceof NormalizedNodeContext, "Unhandled context %s", context.getClass());
35             return ((NormalizedNodeContext) context);
36         }
37     };
38
39     // Singleton instance of reuse
40     private static final YangFunctionContext INSTANCE = new YangFunctionContext();
41
42     private YangFunctionContext() {
43     }
44
45     static YangFunctionContext getInstance() {
46         return INSTANCE;
47     }
48
49     @Override
50     public Function getFunction(final String namespaceURI, final String prefix, final String localName) throws UnresolvableException {
51         if (prefix == null && "current".equals(localName)) {
52             return CURRENT_FUNCTION;
53         }
54         return XPATH_FUNCTION_CONTEXT.getFunction(namespaceURI, prefix, localName);
55     }
56 }