Clean up more Sonar warnings
[yangtools.git] / data / yang-data-util / src / main / java / org / opendaylight / yangtools / yang / data / util / AbstractStringInstanceIdentifierCodec.java
1 /*
2  * Copyright (c) 2014 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.util;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.escape.Escaper;
13 import com.google.common.escape.Escapers;
14 import java.util.Set;
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;
28
29 /**
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).
32  */
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('\\', "\\\\")
41         .build();
42
43     @Override
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));
53             }
54
55             if (current instanceof PathMixin) {
56                 /*
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.
60                  */
61                 continue;
62             }
63
64             final var qname = arg.getNodeType();
65             sb.append('/');
66             appendQName(sb, qname, lastModule);
67             lastModule = qname.getModule();
68
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(']');
74                 }
75             } else if (arg instanceof NodeWithValue<?> val) {
76                 appendValue(sb.append("[.="), lastModule, val.getValue()).append(']');
77             }
78         }
79         return sb.toString();
80     }
81
82     private StringBuilder appendValue(final StringBuilder sb, final QNameModule currentModule,
83             final Object value) {
84         if (value instanceof QName qname) {
85             // QName implies identity-ref, which can never be escaped
86             return appendQName(sb.append('\''), qname, currentModule).append('\'');
87         }
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
91             sb.append('\'');
92
93             final var it = bits.iterator();
94             if (it.hasNext()) {
95                 sb.append(checkBitsItem(it.next()));
96                 while (it.hasNext()) {
97                     sb.append(' ').append(checkBitsItem(it.next()));
98                 }
99             }
100
101             return sb.append('\'');
102         }
103
104         final var str = value instanceof YangInstanceIdentifier id ? serialize(id) : String.valueOf(value);
105
106         // We have two specifications here: Section 6.1.3 of both RFC6020 and RFC7950:
107         //
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.
112         //
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 "*/").
118         //
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.
123         //
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
127         // double-quoting.
128
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('"');
134     }
135
136     /**
137      * Returns DataSchemaContextTree associated with SchemaContext for which
138      * serialization / deserialization occurs.
139      *
140      * <p>
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.
145      *
146      * <p>
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.
150      *
151      * @return DataSchemaContextTree associated with SchemaContext for which
152      *         serialization / deserialization occurs.
153      */
154     protected abstract @NonNull DataSchemaContextTree getDataContextTree();
155
156     protected abstract @NonNull Object deserializeKeyValue(@NonNull DataSchemaNode schemaNode,
157         @NonNull LeafrefResolver resolver, String value);
158
159     @Override
160     protected final YangInstanceIdentifier deserializeImpl(final String data) {
161         return YangInstanceIdentifier.of(
162             new XpathStringParsingPathArgumentBuilder(this, requireNonNull(data)).build());
163     }
164
165     /**
166      * Create QName from unprefixed name, potentially taking last QNameModule encountered into account.
167      *
168      * @param lastModule last QNameModule encountered, potentially null
169      * @param localName Local name string
170      * @return A newly-created QName
171      */
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);
176     }
177
178     @Override
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);
183         }
184         throw new IllegalArgumentException("Failed to lookup prefix " + prefix);
185     }
186
187     /**
188      * Resolve a string prefix into the corresponding module.
189      *
190      * @param prefix Prefix
191      * @return module mapped to prefix, or null if the module cannot be resolved
192      */
193     protected abstract @Nullable QNameModule moduleForPrefix(@NonNull String prefix);
194
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) {
198             return str;
199         }
200         throw new IllegalArgumentException("Unexpected bits component " + obj);
201     }
202 }