Merge branch 'master' of ../controller
[yangtools.git] / yang / 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 com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.Beta;
14 import java.util.Map.Entry;
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.YangInstanceIdentifier.PathArgument;
24 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
25 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
26
27 /**
28  * Abstract utility class for representations which encode {@link YangInstanceIdentifier} as a
29  * prefix:name tuple. Typical uses are RESTCONF/JSON (module:name) and XML (prefix:name).
30  */
31 @Beta
32 public abstract class AbstractStringInstanceIdentifierCodec extends AbstractNamespaceCodec<YangInstanceIdentifier>
33         implements InstanceIdentifierCodec<String> {
34     @Override
35     protected final String serializeImpl(final YangInstanceIdentifier data) {
36         final StringBuilder sb = new StringBuilder();
37         DataSchemaContextNode<?> current = getDataContextTree().getRoot();
38         QNameModule lastModule = null;
39         for (PathArgument arg : data.getPathArguments()) {
40             current = current.getChild(arg);
41             checkArgument(current != null, "Invalid input %s: schema for argument %s (after %s) not found", data, arg,
42                     sb);
43
44             if (current.isMixin()) {
45                 /*
46                  * XML/YANG instance identifier does not have concept
47                  * of augmentation identifier, or list as whole which
48                  * identifies a mixin (same as the parent element),
49                  * so we can safely ignore it if it is part of path
50                  * (since child node) is identified in same fashion.
51                  */
52                 continue;
53             }
54
55             final QName qname = arg.getNodeType();
56             sb.append('/');
57             appendQName(sb, qname, lastModule);
58             lastModule = qname.getModule();
59
60             if (arg instanceof NodeIdentifierWithPredicates) {
61                 for (Entry<QName, Object> entry : ((NodeIdentifierWithPredicates) arg).entrySet()) {
62                     appendQName(sb.append('['), entry.getKey(), lastModule);
63                     sb.append("='").append(String.valueOf(entry.getValue())).append("']");
64                 }
65             } else if (arg instanceof NodeWithValue) {
66                 sb.append("[.='").append(((NodeWithValue<?>) arg).getValue()).append("']");
67             }
68         }
69         return sb.toString();
70     }
71
72     /**
73      * Returns DataSchemaContextTree associated with SchemaContext for which
74      * serialization / deserialization occurs.
75      *
76      * <p>
77      * Implementations MUST provide non-null Data Tree context, in order
78      * for correct serialization / deserialization of PathArguments,
79      * since XML representation does not have Augmentation arguments
80      * and does not provide path arguments for cases.
81      *
82      * <p>
83      * This effectively means same input XPath representation of Path Argument
84      * may result in different YangInstanceIdentifiers if models are different
85      * in uses of choices and cases.
86      *
87      * @return DataSchemaContextTree associated with SchemaContext for which
88      *         serialization / deserialization occurs.
89      */
90     protected abstract @NonNull DataSchemaContextTree getDataContextTree();
91
92     protected Object deserializeKeyValue(final DataSchemaNode schemaNode, final String value) {
93         return value;
94     }
95
96     @Override
97     protected final YangInstanceIdentifier deserializeImpl(final String data) {
98         XpathStringParsingPathArgumentBuilder builder = new XpathStringParsingPathArgumentBuilder(this,
99             requireNonNull(data));
100         return YangInstanceIdentifier.create(builder.build());
101     }
102
103     /**
104      * Create QName from unprefixed name, potentially taking last QNameModule encountered into account.
105      *
106      * @param lastModule last QNameModule encountered, potentially null
107      * @param localName Local name string
108      * @return A newly-created QName
109      */
110     protected QName createQName(final @Nullable QNameModule lastModule, final String localName) {
111         // This implementation handles both XML encoding, where we follow XML namespace rules and old JSON encoding,
112         // which is the same thing: always encode prefixes
113         return createQName(XMLConstants.DEFAULT_NS_PREFIX, localName);
114     }
115 }