87c8976740f3adb903550427606ad91343f083ec
[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 org.jaxen.Function;
12 import org.jaxen.FunctionCallException;
13 import org.jaxen.FunctionContext;
14 import org.jaxen.UnresolvableException;
15 import org.jaxen.XPathFunctionContext;
16
17 /**
18  * A {@link FunctionContext} which contains also to YANG-specific current() function.
19  */
20 final class YangFunctionContext implements FunctionContext {
21     // Core XPath functions, as per http://tools.ietf.org/html/rfc6020#section-6.4.1
22     private static final FunctionContext XPATH_FUNCTION_CONTEXT = new XPathFunctionContext(false);
23     // current() function, as per http://tools.ietf.org/html/rfc6020#section-6.4.1
24     private static final Function CURRENT_FUNCTION = (context, args) -> {
25         if (!args.isEmpty()) {
26             throw new FunctionCallException("current() takes no arguments.");
27         }
28
29         Verify.verify(context instanceof NormalizedNodeContext, "Unhandled context %s", context.getClass());
30         return ((NormalizedNodeContext) context);
31     };
32
33     // Singleton instance of reuse
34     private static final YangFunctionContext INSTANCE = new YangFunctionContext();
35
36     private YangFunctionContext() {
37     }
38
39     static YangFunctionContext getInstance() {
40         return INSTANCE;
41     }
42
43     @Override
44     public Function getFunction(final String namespaceURI, final String prefix, final String localName) throws UnresolvableException {
45         if (prefix == null && "current".equals(localName)) {
46             return CURRENT_FUNCTION;
47         }
48         return XPATH_FUNCTION_CONTEXT.getFunction(namespaceURI, prefix, localName);
49     }
50 }