2 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.cluster.datastore.node.utils;
11 import java.util.HashMap;
13 import java.util.regex.Matcher;
14 import java.util.regex.Pattern;
15 import org.opendaylight.yangtools.yang.common.QName;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
17 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
18 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
19 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
20 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
24 public class NodeIdentifierWithPredicatesGenerator {
25 private static final Logger LOG = LoggerFactory.getLogger(NodeIdentifierWithPredicatesGenerator.class);
26 private static final Pattern PATTERN = Pattern.compile("(.*)\\Q[{\\E(.*)\\Q}]\\E");
28 private final String id;
29 private final Matcher matcher;
30 private final boolean doesMatch;
31 private final ListSchemaNode listSchemaNode;
33 public NodeIdentifierWithPredicatesGenerator(String id, DataSchemaNode schemaNode) {
35 matcher = PATTERN.matcher(this.id);
36 doesMatch = matcher.matches();
38 if (schemaNode instanceof ListSchemaNode) {
39 this.listSchemaNode = (ListSchemaNode) schemaNode;
41 this.listSchemaNode = null;
46 public boolean matches() {
50 public YangInstanceIdentifier.NodeIdentifierWithPredicates getPathArgument() {
51 final String group = matcher.group(2);
52 final String[] keyValues = group.split(",");
53 Map<QName, Object> nameValues = new HashMap<>();
55 for (String keyValue : keyValues) {
56 int eqIndex = keyValue.lastIndexOf('=');
58 final QName key = QNameFactory
59 .create(keyValue.substring(0, eqIndex));
60 nameValues.put(key, getValue(key, keyValue.substring(eqIndex + 1)));
61 } catch (IllegalArgumentException e) {
62 LOG.error("Error processing identifier {}", id, e);
67 return new YangInstanceIdentifier.NodeIdentifierWithPredicates(
68 QNameFactory.create(matcher.group(1)), nameValues);
72 private Object getValue(QName key, String value) {
73 if (listSchemaNode != null) {
74 for (DataSchemaNode node : listSchemaNode.getChildNodes()) {
75 if (node instanceof LeafSchemaNode && node.getQName().equals(key)) {
76 return TypeDefinitionAwareCodec.from(LeafSchemaNode.class.cast(node).getType()).deserialize(value);