2 * Copyright (c) 2016 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 com.google.common.base.Preconditions;
11 import java.io.IOException;
12 import java.util.Collection;
13 import java.util.HashMap;
14 import java.util.LinkedHashMap;
16 import org.opendaylight.yangtools.yang.common.QName;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
18 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
19 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
20 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
21 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
24 * Utility class used for tracking parser state as needed by a StAX-like parser.
25 * This class is to be used only by respective XML and JSON parsers in yang-data-codec-xml and yang-data-codec-gson.
28 * Represents a YANG list entry node.
30 public class ListEntryNodeDataWithSchema extends CompositeNodeDataWithSchema {
32 private final Map<QName, SimpleNodeDataWithSchema> qnameToKeys = new HashMap<>();
34 public ListEntryNodeDataWithSchema(final DataSchemaNode schema) {
39 public void addChild(final AbstractNodeDataWithSchema newChild) {
40 final DataSchemaNode childSchema = newChild.getSchema();
41 if (childSchema instanceof LeafSchemaNode && isPartOfKey((LeafSchemaNode) childSchema)) {
42 qnameToKeys.put(childSchema.getQName(), (SimpleNodeDataWithSchema)newChild);
44 super.addChild(newChild);
47 private boolean isPartOfKey(final LeafSchemaNode potentialKey) {
48 for (QName qname : ((ListSchemaNode) getSchema()).getKeyDefinition()) {
49 if (qname.equals(potentialKey.getQName())) {
57 public void write(final NormalizedNodeStreamWriter writer) throws IOException {
58 final Collection<QName> keyDef = ((ListSchemaNode) getSchema()).getKeyDefinition();
59 if (keyDef.isEmpty()) {
60 writer.nextDataSchemaNode(getSchema());
61 writer.startUnkeyedListItem(provideNodeIdentifier(), childSizeHint());
67 Preconditions.checkState(keyDef.size() == qnameToKeys.size(), "Input is missing some of the keys of %s",
68 getSchema().getQName());
70 // Need to restore schema order...
71 final Map<QName, Object> predicates = new LinkedHashMap<>();
72 for (QName qname : keyDef) {
73 predicates.put(qname, qnameToKeys.get(qname).getValue());
76 writer.nextDataSchemaNode(getSchema());
77 writer.startMapEntryNode(
78 new NodeIdentifierWithPredicates(getSchema().getQName(), predicates),