*/
package org.opendaylight.netconf.mdsal.connector.ops.get;
+import static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
import java.net.URI;
import java.net.URISyntaxException;
-import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.util.ParserStreamUtils;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Class validates filter content against schema context.
*/
public class FilterContentValidator {
+ private static final Logger LOG = LoggerFactory.getLogger(FilterContentValidator.class);
private final CurrentSchemaContext schemaContext;
/**
}
/**
- * Validates filter content against this validator schema context. If the filter is valid, method returns {@link YangInstanceIdentifier}
- * of node which can be used as root for data selection.
+ * Validates filter content against this validator schema context. If the filter is valid,
+ * method returns {@link YangInstanceIdentifier} of node which can be used as root for data selection.
* @param filterContent filter content
* @return YangInstanceIdentifier
* @throws DocumentedException if filter content is not valid
final URI namespace = new URI(filterContent.getNamespace());
final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespace, null);
final DataSchemaNode schema = getRootDataSchemaNode(module, namespace, filterContent.getName());
- final FilterTree filterTree = validateNode(filterContent, schema, new FilterTree(schema.getQName(), Type.OTHER));
- return getFilterDataRoot(filterTree, YangInstanceIdentifier.builder());
+ final FilterTree filterTree = validateNode(filterContent, schema, new FilterTree(schema.getQName(),
+ Type.OTHER, schema));
+ return getFilterDataRoot(filterTree, filterContent, YangInstanceIdentifier.builder());
} catch (DocumentedException e) {
throw e;
} catch (Exception e) {
+ LOG.debug("Filter content isn't valid", e);
throw new DocumentedException("Validation failed. Cause: " + e.getMessage(),
DocumentedException.ErrorType.application,
DocumentedException.ErrorTag.unknown_namespace,
* @return child data node schema
* @throws DocumentedException if child with given name is not present
*/
- private DataSchemaNode getRootDataSchemaNode(Module module, URI nameSpace, String name) throws DocumentedException {
+ private DataSchemaNode getRootDataSchemaNode(final Module module, final URI nameSpace, final String name)
+ throws DocumentedException {
final Collection<DataSchemaNode> childNodes = module.getChildNodes();
for (DataSchemaNode childNode : childNodes) {
final QName qName = childNode.getQName();
return childNode;
}
}
- throw new DocumentedException("Unable to find node with namespace: " + nameSpace + "in schema context: " + schemaContext.getCurrentContext().toString(),
+ throw new DocumentedException("Unable to find node with namespace: " + nameSpace + "in schema context: " +
+ schemaContext.getCurrentContext().toString(),
DocumentedException.ErrorType.application,
DocumentedException.ErrorTag.unknown_namespace,
DocumentedException.ErrorSeverity.error);
* @return tree
* @throws ValidationException if filter content is not valid
*/
- private FilterTree validateNode(XmlElement element, DataSchemaNode parentNodeSchema, FilterTree tree) throws ValidationException {
+ private FilterTree validateNode(final XmlElement element, final DataSchemaNode parentNodeSchema,
+ final FilterTree tree) throws ValidationException {
final List<XmlElement> childElements = element.getChildElements();
for (XmlElement childElement : childElements) {
try {
- final Deque<DataSchemaNode> path = findSchemaNodeByNameAndNamespace(parentNodeSchema, childElement.getName(), new URI(childElement.getNamespace()));
+ final Deque<DataSchemaNode> path = ParserStreamUtils.findSchemaNodeByNameAndNamespace(parentNodeSchema,
+ childElement.getName(), new URI(childElement.getNamespace()));
if (path.isEmpty()) {
throw new ValidationException(element, childElement);
}
FilterTree subtree = tree;
for (DataSchemaNode dataSchemaNode : path) {
- subtree = subtree.addChild(dataSchemaNode);
+ subtree = subtree.addChild(dataSchemaNode);
}
final DataSchemaNode childSchema = path.getLast();
validateNode(childElement, childSchema, subtree);
/**
* Searches for YangInstanceIdentifier of node, which can be used as root for data selection.
- * It goes as deep in tree as possible. Method stops traversing, when there are multiple child elements
- * or when it encounters list node.
+ * It goes as deep in tree as possible. Method stops traversing, when there are multiple child elements. If element
+ * represents list and child elements are key values, then it builds YangInstanceIdentifier of list entry.
* @param tree QName tree
- * @param builder builder
- * @return YangInstanceIdentifier
+ * @param filterContent filter element
+ * @param builder builder @return YangInstanceIdentifier
*/
- private YangInstanceIdentifier getFilterDataRoot(FilterTree tree, YangInstanceIdentifier.InstanceIdentifierBuilder builder) {
+ private YangInstanceIdentifier getFilterDataRoot(FilterTree tree, final XmlElement filterContent,
+ final InstanceIdentifierBuilder builder) {
builder.node(tree.getName());
+ final List<String> path = new ArrayList<>();
while (tree.getChildren().size() == 1) {
final FilterTree child = tree.getChildren().iterator().next();
if (child.getType() == Type.CHOICE_CASE) {
continue;
}
builder.node(child.getName());
+ path.add(child.getName().getLocalName());
if (child.getType() == Type.LIST) {
+ appendKeyIfPresent(child, filterContent, path, builder);
return builder.build();
}
tree = child;
return builder.build();
}
- //FIXME this method will also be in yangtools ParserUtils, use that when https://git.opendaylight.org/gerrit/#/c/37031/ will be merged
- /**
- * Returns stack of schema nodes via which it was necessary to pass to get schema node with specified
- * {@code childName} and {@code namespace}
- *
- * @param dataSchemaNode
- * @param childName
- * @param namespace
- * @return stack of schema nodes via which it was passed through. If found schema node is direct child then stack
- * contains only one node. If it is found under choice and case then stack should contains 2*n+1 element
- * (where n is number of choices through it was passed)
- */
- private Deque<DataSchemaNode> findSchemaNodeByNameAndNamespace(final DataSchemaNode dataSchemaNode,
- final String childName, final URI namespace) {
- final Deque<DataSchemaNode> result = new ArrayDeque<>();
- final List<ChoiceSchemaNode> childChoices = new ArrayList<>();
- DataSchemaNode potentialChildNode = null;
- if (dataSchemaNode instanceof DataNodeContainer) {
- for (final DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
- if (childNode instanceof ChoiceSchemaNode) {
- childChoices.add((ChoiceSchemaNode) childNode);
- } else {
- final QName childQName = childNode.getQName();
-
- if (childQName.getLocalName().equals(childName) && childQName.getNamespace().equals(namespace)) {
- if (potentialChildNode == null ||
- childQName.getRevision().after(potentialChildNode.getQName().getRevision())) {
- potentialChildNode = childNode;
- }
- }
- }
- }
- }
- if (potentialChildNode != null) {
- result.push(potentialChildNode);
- return result;
+ private void appendKeyIfPresent(final FilterTree tree, final XmlElement filterContent,
+ final List<String> pathToList,
+ final InstanceIdentifierBuilder builder) {
+ Preconditions.checkArgument(tree.getSchemaNode() instanceof ListSchemaNode);
+ final ListSchemaNode listSchemaNode = (ListSchemaNode) tree.getSchemaNode();
+ final List<QName> keyDefinition = listSchemaNode.getKeyDefinition();
+ final Map<QName, Object> map = getKeyValues(pathToList, filterContent, keyDefinition);
+ if (!map.isEmpty()) {
+ builder.nodeWithKey(tree.getName(), map);
}
+ }
- // try to find data schema node in choice (looking for first match)
- for (final ChoiceSchemaNode choiceNode : childChoices) {
- for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
- final Deque<DataSchemaNode> resultFromRecursion = findSchemaNodeByNameAndNamespace(concreteCase, childName,
- namespace);
- if (!resultFromRecursion.isEmpty()) {
- resultFromRecursion.push(concreteCase);
- resultFromRecursion.push(choiceNode);
- return resultFromRecursion;
- }
+ private Map<QName, Object> getKeyValues(final List<String> path, final XmlElement filterContent,
+ final List<QName> keyDefinition) {
+ XmlElement current = filterContent;
+ //find list element
+ for (final String pathElement : path) {
+ final List<XmlElement> childElements = current.getChildElements(pathElement);
+ // if there are multiple list entries present in the filter, we can't use any keys and must read whole list
+ if (childElements.size() != 1) {
+ return Collections.emptyMap();
}
+ current = childElements.get(0);
}
- return result;
+ final Map<QName, Object> keys = new HashMap<>();
+ for (final QName qName : keyDefinition) {
+ final Optional<XmlElement> childElements = current.getOnlyChildElementOptionally(qName.getLocalName());
+ if (!childElements.isPresent()) {
+ return Collections.emptyMap();
+ }
+ final Optional<String> keyValue = childElements.get().getOnlyTextContentOptionally();
+ if (keyValue.isPresent()) {
+ keys.put(qName, keyValue.get());
+ }
+ }
+ return keys;
}
/**
private final QName name;
private final Type type;
+ private final DataSchemaNode schemaNode;
private final Map<QName, FilterTree> children;
- FilterTree(QName name, Type type) {
+ FilterTree(final QName name, final Type type, final DataSchemaNode schemaNode) {
this.name = name;
this.type = type;
+ this.schemaNode = schemaNode;
this.children = new HashMap<>();
}
final QName name = data.getQName();
FilterTree childTree = children.get(name);
if (childTree == null) {
- childTree = new FilterTree(name, type);
+ childTree = new FilterTree(name, type, data);
}
children.put(name, childTree);
return childTree;
Type getType() {
return type;
}
+
+ DataSchemaNode getSchemaNode() {
+ return schemaNode;
+ }
}
private enum Type {
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+import com.google.common.base.Preconditions;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collection;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.config.util.xml.XmlElement;
import org.opendaylight.controller.config.util.xml.XmlUtil;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
@RunWith(value = Parameterized.class)
public class FilterContentValidatorTest {
- private static final int TEST_CASE_COUNT = 8;
+ private static final int TEST_CASE_COUNT = 13;
+ private static final Pattern LIST_ENTRY_PATTERN =
+ Pattern.compile("(?<listName>.*)\\[\\{(?<keys>(.*)(, .*)*)\\}\\]");
+ private static final Pattern KEY_VALUE_PATTERN =
+ Pattern.compile("(?<key>\\(.*\\).*)=(?<value>.*)");
private final XmlElement filterContent;
private final String expected;
private FilterContentValidator validator;
@Parameterized.Parameters
public static Collection<Object[]> data() throws IOException, SAXException, URISyntaxException, InitializationError {
- List<Object[]> result = new ArrayList<>();
+ final List<Object[]> result = new ArrayList<>();
final Path path = Paths.get(FilterContentValidatorTest.class.getResource("/filter/expected.txt").toURI());
final List<String> expected = Files.readAllLines(path);
if (expected.size() != TEST_CASE_COUNT) {
return result;
}
- public FilterContentValidatorTest(Document filterContent, String expected) {
+ public FilterContentValidatorTest(final Document filterContent, final String expected) {
this.filterContent = XmlElement.fromDomDocument(filterContent);
this.expected = expected;
}
@Before
public void setUp() throws Exception {
- List<InputStream> sources = new ArrayList<>();
+ final List<InputStream> sources = new ArrayList<>();
sources.add(getClass().getResourceAsStream("/yang/filter-validator-test-mod-0.yang"));
sources.add(getClass().getResourceAsStream("/yang/filter-validator-test-augment.yang"));
- SchemaContext context = parseYangSources(sources);
- CurrentSchemaContext currentContext = mock(CurrentSchemaContext.class);
+ final SchemaContext context = parseYangSources(sources);
+ final CurrentSchemaContext currentContext = mock(CurrentSchemaContext.class);
doReturn(context).when(currentContext).getCurrentContext();
validator = new FilterContentValidator(currentContext);
}
public void testValidate() throws Exception {
if (expected.startsWith("success")) {
final String expId = expected.replace("success=", "");
- Assert.assertEquals(expId, validator.validate(filterContent).toString());
+ final YangInstanceIdentifier actual = validator.validate(filterContent);
+ final YangInstanceIdentifier expected = fromString(expId);
+ Assert.assertEquals(expected, actual);
} else if (expected.startsWith("error")) {
try {
validator.validate(filterContent);
Assert.fail(XmlUtil.toString(filterContent) + " is not valid and should throw exception.");
- } catch (Exception e) {
+ } catch (final Exception e) {
final String expectedExceptionClass = expected.replace("error=", "");
Assert.assertEquals(expectedExceptionClass, e.getClass().getName());
}
}
-
}
public static SchemaContext parseYangSources(Collection<InputStream> testFiles)
}
return reactor.buildEffective();
}
+
+ private static YangInstanceIdentifier fromString(final String input) {
+ //remove first /
+ final String yid = input.substring(1);
+ final List<String> pathElements = Arrays.asList(yid.split("/"));
+ final YangInstanceIdentifier.InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
+ //if not specified, PathArguments inherit namespace and revision from previous PathArgument
+ QName prev = null;
+ for (final String pathElement : pathElements) {
+ final Matcher matcher = LIST_ENTRY_PATTERN.matcher(pathElement);
+ if (matcher.matches()) {
+ prev = parseListEntry(builder, prev, matcher);
+ } else {
+ final QName qName = createNodeQName(prev, pathElement);
+ builder.node(qName);
+ prev = qName;
+ }
+ }
+ return builder.build();
+ }
+
+ private static QName parseListEntry(final YangInstanceIdentifier.InstanceIdentifierBuilder builder,
+ final QName prev, final Matcher matcher) {
+ final Map<QName, Object> keys = new HashMap<>();
+ final String listName = matcher.group("listName");
+ final QName listQName = createNodeQName(prev, listName);
+ final String keysString = matcher.group("keys");
+ final String[] split = keysString.split(",");
+ for (final String s : split) {
+ final Matcher keyMatcher = KEY_VALUE_PATTERN.matcher(s.trim());
+ if (keyMatcher.matches()) {
+ final QName keyName = QName.create(keyMatcher.group("key"));
+ final String keyValue = keyMatcher.group("value");
+ keys.put(keyName, keyValue);
+ }
+ }
+ builder.nodeWithKey(listQName, keys);
+ return prev;
+ }
+
+ private static QName createNodeQName(final QName prev, final String qNameString) {
+ final QName qName = QName.create(qNameString);
+ if (qName.getModule().getNamespace() != null) {
+ return qName;
+ } else {
+ return QName.create(Preconditions.checkNotNull(prev), qNameString);
+ }
+ }
}