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 java.util.Objects.requireNonNull;
12 import com.google.common.escape.Escaper;
13 import com.google.common.escape.Escapers;
15 import javax.xml.XMLConstants;
16 import org.eclipse.jdt.annotation.NonNull;
17 import org.eclipse.jdt.annotation.Nullable;
18 import org.opendaylight.yangtools.yang.common.QName;
19 import org.opendaylight.yangtools.yang.common.QNameModule;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
23 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
24 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext.Composite;
25 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext.PathMixin;
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).
33 public abstract class AbstractStringInstanceIdentifierCodec extends AbstractNamespaceCodec<YangInstanceIdentifier>
34 implements InstanceIdentifierCodec<String> {
35 // Escaper as per https://www.rfc-editor.org/rfc/rfc7950#section-6.1.3
36 private static final Escaper DQUOT_ESCAPER = Escapers.builder()
37 .addEscape('\n', "\\n")
38 .addEscape('\t', "\\t")
39 .addEscape('"', "\\\"")
40 .addEscape('\\', "\\\\")
44 protected final String serializeImpl(final YangInstanceIdentifier data) {
45 final StringBuilder sb = new StringBuilder();
46 DataSchemaContext current = getDataContextTree().getRoot();
47 QNameModule lastModule = null;
48 for (var arg : data.getPathArguments()) {
49 current = current instanceof Composite composite ? composite.childByArg(arg) : null;
50 if (current == null) {
51 throw new IllegalArgumentException(
52 "Invalid input %s: schema for argument %s (after \"%s\") not found".formatted(data, arg, sb));
55 if (current instanceof PathMixin) {
57 * XML/YANG instance identifier does not have concept of augmentation identifier, or list as whole which
58 * identifies a mixin (same as the parent element), so we can safely ignore it if it is part of path
59 * (since child node) is identified in same fashion.
64 final var qname = arg.getNodeType();
66 appendQName(sb, qname, lastModule);
67 lastModule = qname.getModule();
69 if (arg instanceof NodeIdentifierWithPredicates nip) {
70 for (var entry : nip.entrySet()) {
71 final var keyName = entry.getKey();
72 appendQName(sb.append('['), keyName, lastModule).append('=');
73 appendValue(sb, keyName.getModule(), entry.getValue()).append(']');
75 } else if (arg instanceof NodeWithValue<?> val) {
76 appendValue(sb.append("[.="), lastModule, val.getValue()).append(']');
82 private StringBuilder appendValue(final StringBuilder sb, final QNameModule currentModule,
84 if (value instanceof QName qname) {
85 // QName implies identity-ref, which can never be escaped
86 return appendQName(sb.append('\''), qname, currentModule).append('\'');
88 // FIXME: YANGTOOLS-1426: update once we have a dedicated type
89 if (value instanceof Set<?> bits) {
90 // Set implies bits, which can never be escaped and need to be serialized as space-separated items
93 final var it = bits.iterator();
95 sb.append(checkBitsItem(it.next()));
96 while (it.hasNext()) {
97 sb.append(' ').append(checkBitsItem(it.next()));
101 return sb.append('\'');
104 final var str = value instanceof YangInstanceIdentifier id ? serialize(id) : String.valueOf(value);
106 // We have two specifications here: Section 6.1.3 of both RFC6020 and RFC7950:
108 // RFC6020 Section 6.1.3:
109 // If a string contains any space or tab characters, a semicolon (";"),
110 // braces ("{" or "}"), or comment sequences ("//", "/*", or "*/"), then
111 // it MUST be enclosed within double or single quotes.
113 // RFC7950 Section 6.1.3:
114 // An unquoted string is any sequence of characters that does not
115 // contain any space, tab, carriage return, or line feed characters, a
116 // single or double quote character, a semicolon (";"), braces ("{" or
117 // "}"), or comment sequences ("//", "/*", or "*/").
119 // Plus the common part:
120 // A single-quoted string (enclosed within ' ') preserves each character
121 // within the quotes. A single quote character cannot occur in a
122 // single-quoted string, even when preceded by a backslash.
124 // Unquoted strings are not interesting, as we are embedding the value in a string, not a YANG document, hence
125 // we have to use quotes. Single-quoted case is simpler, as it does not involve any escaping. The only case
126 // where we cannot use it is when the value itself has a single-quote in itself -- then we call back to
129 return str.indexOf('\'') == -1
130 // No escaping needed, use single quotes
131 ? sb.append('\'').append(str).append('\'')
132 // Escaping needed: use double quotes
133 : sb.append('"').append(DQUOT_ESCAPER.escape(str)).append('"');
137 * Returns DataSchemaContextTree associated with SchemaContext for which
138 * serialization / deserialization occurs.
141 * Implementations MUST provide non-null Data Tree context, in order
142 * for correct serialization / deserialization of PathArguments,
143 * since XML representation does not have Augmentation arguments
144 * and does not provide path arguments for cases.
147 * This effectively means same input XPath representation of Path Argument
148 * may result in different YangInstanceIdentifiers if models are different
149 * in uses of choices and cases.
151 * @return DataSchemaContextTree associated with SchemaContext for which
152 * serialization / deserialization occurs.
154 protected abstract @NonNull DataSchemaContextTree getDataContextTree();
156 protected abstract @NonNull Object deserializeKeyValue(@NonNull DataSchemaNode schemaNode,
157 @NonNull LeafrefResolver resolver, String value);
160 protected final YangInstanceIdentifier deserializeImpl(final String data) {
161 return YangInstanceIdentifier.of(
162 new XpathStringParsingPathArgumentBuilder(this, requireNonNull(data)).build());
166 * Create QName from unprefixed name, potentially taking last QNameModule encountered into account.
168 * @param lastModule last QNameModule encountered, potentially null
169 * @param localName Local name string
170 * @return A newly-created QName
172 protected @NonNull QName createQName(final @Nullable QNameModule lastModule, final String localName) {
173 // This implementation handles both XML encoding, where we follow XML namespace rules and old JSON encoding,
174 // which is the same thing: always encode prefixes
175 return createQName(XMLConstants.DEFAULT_NS_PREFIX, localName);
179 protected final QName createQName(final String prefix, final String localName) {
180 final var module = moduleForPrefix(prefix);
181 if (module != null) {
182 return QName.create(module, localName);
184 throw new IllegalArgumentException("Failed to lookup prefix " + prefix);
188 * Resolve a string prefix into the corresponding module.
190 * @param prefix Prefix
191 * @return module mapped to prefix, or null if the module cannot be resolved
193 protected abstract @Nullable QNameModule moduleForPrefix(@NonNull String prefix);
195 // FIXME: YANGTOOLS-1426: this will not be necessary when we have dedicated bits type
196 private static @NonNull String checkBitsItem(final Object obj) {
197 if (obj instanceof String str) {
200 throw new IllegalArgumentException("Unexpected bits component " + obj);