2 * Copyright (c) 2014 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
8 package org.opendaylight.yangtools.yang.data.util;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.Beta;
14 import com.google.common.escape.Escaper;
15 import com.google.common.escape.Escapers;
17 import javax.xml.XMLConstants;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.common.QNameModule;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
25 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
26 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
27 import org.opendaylight.yangtools.yang.model.util.LeafrefResolver;
30 * Abstract utility class for representations which encode {@link YangInstanceIdentifier} as a
31 * prefix:name tuple. Typical uses are RESTCONF/JSON (module:name) and XML (prefix:name).
34 public abstract class AbstractStringInstanceIdentifierCodec extends AbstractNamespaceCodec<YangInstanceIdentifier>
35 implements InstanceIdentifierCodec<String> {
36 // Escaper as per https://www.rfc-editor.org/rfc/rfc7950#section-6.1.3
37 private static final Escaper DQUOT_ESCAPER = Escapers.builder()
38 .addEscape('\n', "\\n")
39 .addEscape('\t', "\\t")
40 .addEscape('"', "\\\"")
41 .addEscape('\\', "\\\\")
45 protected final String serializeImpl(final YangInstanceIdentifier data) {
46 final StringBuilder sb = new StringBuilder();
47 DataSchemaContextNode<?> current = getDataContextTree().getRoot();
48 QNameModule lastModule = null;
49 for (var arg : data.getPathArguments()) {
50 current = current.getChild(arg);
51 checkArgument(current != null, "Invalid input %s: schema for argument %s (after %s) not found", data, arg,
54 if (current.isMixin()) {
56 * XML/YANG instance identifier does not have concept
57 * of augmentation identifier, or list as whole which
58 * identifies a mixin (same as the parent element),
59 * so we can safely ignore it if it is part of path
60 * (since child node) is identified in same fashion.
65 final var qname = arg.getNodeType();
67 appendQName(sb, qname, lastModule);
68 lastModule = qname.getModule();
70 if (arg instanceof NodeIdentifierWithPredicates) {
71 for (var entry : ((NodeIdentifierWithPredicates) arg).entrySet()) {
72 final var keyName = entry.getKey();
73 appendQName(sb.append('['), keyName, lastModule).append('=');
74 appendValue(sb, keyName.getModule(), entry.getValue()).append(']');
76 } else if (arg instanceof NodeWithValue) {
77 appendValue(sb.append("[.="), lastModule, ((NodeWithValue<?>) arg).getValue()).append(']');
83 private StringBuilder appendValue(final StringBuilder sb, final QNameModule currentModule,
85 if (value instanceof QName) {
86 // QName implies identity-ref, which can never be escaped
87 return appendQName(sb.append('\''), (QName) value, currentModule).append('\'');
89 // FIXME: YANGTOOLS-1426: update once we have a dedicated type
90 if (value instanceof Set) {
91 final var bits = (Set<?>) value;
92 // Set implies bits, which can never be escaped and need to be serialized as space-separated items
95 final var it = bits.iterator();
97 sb.append(checkBitsItem(it.next()));
98 while (it.hasNext()) {
99 sb.append(' ').append(checkBitsItem(it.next()));
103 return sb.append('\'');
106 final String str = value instanceof YangInstanceIdentifier ? serialize((YangInstanceIdentifier) value)
107 : String.valueOf(value);
109 // We have two specifications here: Section 6.1.3 of both RFC6020 and RFC7950:
111 // RFC6020 Section 6.1.3:
112 // If a string contains any space or tab characters, a semicolon (";"),
113 // braces ("{" or "}"), or comment sequences ("//", "/*", or "*/"), then
114 // it MUST be enclosed within double or single quotes.
116 // RFC7950 Section 6.1.3:
117 // An unquoted string is any sequence of characters that does not
118 // contain any space, tab, carriage return, or line feed characters, a
119 // single or double quote character, a semicolon (";"), braces ("{" or
120 // "}"), or comment sequences ("//", "/*", or "*/").
122 // Plus the common part:
123 // A single-quoted string (enclosed within ' ') preserves each character
124 // within the quotes. A single quote character cannot occur in a
125 // single-quoted string, even when preceded by a backslash.
127 // Unquoted strings are not interesting, as we are embedding the value in a string, not a YANG document, hence
128 // we have to use quotes. Single-quoted case is simpler, as it does not involve any escaping. The only case
129 // where we cannot use it is when the value itself has a single-quote in itself -- then we call back to
132 return str.indexOf('\'') == -1
133 // No escaping needed, use single quotes
134 ? sb.append('\'').append(str).append('\'')
135 // Escaping needed: use double quotes
136 : sb.append('"').append(DQUOT_ESCAPER.escape(str)).append('"');
140 * Returns DataSchemaContextTree associated with SchemaContext for which
141 * serialization / deserialization occurs.
144 * Implementations MUST provide non-null Data Tree context, in order
145 * for correct serialization / deserialization of PathArguments,
146 * since XML representation does not have Augmentation arguments
147 * and does not provide path arguments for cases.
150 * This effectively means same input XPath representation of Path Argument
151 * may result in different YangInstanceIdentifiers if models are different
152 * in uses of choices and cases.
154 * @return DataSchemaContextTree associated with SchemaContext for which
155 * serialization / deserialization occurs.
157 protected abstract @NonNull DataSchemaContextTree getDataContextTree();
159 protected Object deserializeKeyValue(final DataSchemaNode schemaNode, final LeafrefResolver resolver,
160 final String value) {
165 protected final YangInstanceIdentifier deserializeImpl(final String data) {
166 return YangInstanceIdentifier.create(
167 new XpathStringParsingPathArgumentBuilder(this, requireNonNull(data)).build());
171 * Create QName from unprefixed name, potentially taking last QNameModule encountered into account.
173 * @param lastModule last QNameModule encountered, potentially null
174 * @param localName Local name string
175 * @return A newly-created QName
177 protected QName createQName(final @Nullable QNameModule lastModule, final String localName) {
178 // This implementation handles both XML encoding, where we follow XML namespace rules and old JSON encoding,
179 // which is the same thing: always encode prefixes
180 return createQName(XMLConstants.DEFAULT_NS_PREFIX, localName);
183 // FIXME: YANGTOOLS-1426: this will not be necessary when we have dedicated bits type
184 private static @NonNull String checkBitsItem(final Object obj) {
185 if (obj instanceof String) {
188 throw new IllegalArgumentException("Unexpected bits component " + obj);