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 static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import com.google.gson.stream.JsonWriter;
14 import java.io.IOException;
16 import java.util.Iterator;
17 import javax.annotation.Nonnull;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
19 import org.opendaylight.yangtools.yang.data.util.AbstractModuleStringInstanceIdentifierCodec;
20 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
21 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
22 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
23 import org.opendaylight.yangtools.yang.model.api.Module;
24 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
26 final class JSONStringInstanceIdentifierCodec extends AbstractModuleStringInstanceIdentifierCodec
27 implements JSONCodec<YangInstanceIdentifier> {
28 private final DataSchemaContextTree dataContextTree;
29 private final JSONCodecFactory codecFactory;
30 private final SchemaContext context;
32 JSONStringInstanceIdentifierCodec(final SchemaContext context, final JSONCodecFactory jsonCodecFactory) {
33 this.context = requireNonNull(context);
34 this.dataContextTree = DataSchemaContextTree.from(context);
35 this.codecFactory = requireNonNull(jsonCodecFactory);
39 protected Module moduleForPrefix(@Nonnull final String prefix) {
40 final Iterator<Module> modules = context.findModules(prefix).iterator();
41 return modules.hasNext() ? modules.next() : null;
45 protected String prefixForNamespace(@Nonnull final URI namespace) {
46 final Iterator<Module> modules = context.findModules(namespace).iterator();
47 return modules.hasNext() ? modules.next().getName() : null;
52 protected DataSchemaContextTree getDataContextTree() {
53 return dataContextTree;
57 protected Object deserializeKeyValue(final DataSchemaNode schemaNode, final String value) {
58 requireNonNull(schemaNode, "schemaNode cannot be null");
59 checkArgument(schemaNode instanceof LeafSchemaNode, "schemaNode must be of type LeafSchemaNode");
60 final JSONCodec<?> objectJSONCodec = codecFactory.codecFor((LeafSchemaNode) schemaNode);
61 return objectJSONCodec.parseValue(null, value);
65 public Class<YangInstanceIdentifier> getDataType() {
66 return YangInstanceIdentifier.class;
70 public YangInstanceIdentifier parseValue(final Object ctx, final String str) {
71 return deserialize(str);
75 public void writeValue(final JsonWriter ctx, final YangInstanceIdentifier value) throws IOException {
76 ctx.value(serialize(value));