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.Function;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.Maps;
14 import java.io.IOException;
15 import java.util.HashMap;
16 import java.util.List;
19 import javax.annotation.Nonnull;
21 import org.opendaylight.yangtools.yang.common.QName;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
23 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
24 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
28 class ListEntryNodeDataWithSchema extends CompositeNodeDataWithSchema {
29 private static final Function<SimpleNodeDataWithSchema, Object> VALUE_FUNCTION = new Function<SimpleNodeDataWithSchema, Object>() {
31 public Object apply(@Nonnull final SimpleNodeDataWithSchema input) {
32 return input.getValue();
36 private final Map<QName, SimpleNodeDataWithSchema> qNameToKeys = new HashMap<>();
38 public ListEntryNodeDataWithSchema(final DataSchemaNode schema) {
43 public void addChild(final AbstractNodeDataWithSchema newChild) {
44 final DataSchemaNode childSchema = newChild.getSchema();
45 if (childSchema instanceof LeafSchemaNode && isPartOfKey((LeafSchemaNode) childSchema)) {
46 qNameToKeys.put(childSchema.getQName(), (SimpleNodeDataWithSchema)newChild);
48 super.addChild(newChild);
51 private boolean isPartOfKey(final LeafSchemaNode potentialKey) {
52 List<QName> keys = ((ListSchemaNode) getSchema()).getKeyDefinition();
53 for (QName qName : keys) {
54 if (qName.equals(potentialKey.getQName())) {
62 public void write(final NormalizedNodeStreamWriter writer) throws IOException {
63 final int keyCount = ((ListSchemaNode) getSchema()).getKeyDefinition().size();
65 writer.startUnkeyedListItem(provideNodeIdentifier(), childSizeHint());
71 Preconditions.checkState(keyCount == qNameToKeys.size(), "Input is missing some of the keys of %s", getSchema().getQName());
72 writer.startMapEntryNode(
73 new NodeIdentifierWithPredicates(getSchema().getQName(), Maps.transformValues(qNameToKeys, VALUE_FUNCTION)),