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.codec.gson;
10 import com.google.common.base.Preconditions;
12 import java.io.IOException;
13 import java.util.Collection;
14 import java.util.HashMap;
15 import java.util.LinkedHashMap;
16 import java.util.List;
19 import org.opendaylight.yangtools.yang.common.QName;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
21 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
22 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
23 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
24 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
26 class ListEntryNodeDataWithSchema extends CompositeNodeDataWithSchema {
28 private final Map<QName, SimpleNodeDataWithSchema> qNameToKeys = new HashMap<>();
30 public ListEntryNodeDataWithSchema(final DataSchemaNode schema) {
35 public void addChild(final AbstractNodeDataWithSchema newChild) {
36 final DataSchemaNode childSchema = newChild.getSchema();
37 if (childSchema instanceof LeafSchemaNode && isPartOfKey((LeafSchemaNode) childSchema)) {
38 qNameToKeys.put(childSchema.getQName(), (SimpleNodeDataWithSchema)newChild);
40 super.addChild(newChild);
43 private boolean isPartOfKey(final LeafSchemaNode potentialKey) {
44 List<QName> keys = ((ListSchemaNode) getSchema()).getKeyDefinition();
45 for (QName qName : keys) {
46 if (qName.equals(potentialKey.getQName())) {
54 public void write(final NormalizedNodeStreamWriter writer) throws IOException {
55 final Collection<QName> keyDef = ((ListSchemaNode) getSchema()).getKeyDefinition();
56 if (keyDef.isEmpty()) {
57 writer.startUnkeyedListItem(provideNodeIdentifier(), childSizeHint());
63 Preconditions.checkState(keyDef.size() == qNameToKeys.size(), "Input is missing some of the keys of %s", getSchema().getQName());
65 // Need to restore schema order...
66 final Map<QName, Object> predicates = new LinkedHashMap<>();
67 for (QName qname : keyDef) {
68 predicates.put(qname, qNameToKeys.get(qname).getValue());
71 writer.startMapEntryNode(
72 new NodeIdentifierWithPredicates(getSchema().getQName(), predicates),