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;
11 import com.google.gson.stream.JsonWriter;
12 import java.io.IOException;
14 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
15 import org.opendaylight.yangtools.yang.data.util.AbstractModuleStringInstanceIdentifierCodec;
16 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
17 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
18 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
19 import org.opendaylight.yangtools.yang.model.api.Module;
20 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
22 final class JSONStringInstanceIdentifierCodec extends AbstractModuleStringInstanceIdentifierCodec implements JSONCodec<YangInstanceIdentifier> {
23 private final SchemaContext context;
24 private final DataSchemaContextTree dataContextTree;
25 private final JSONCodecFactory codecFactory;
27 JSONStringInstanceIdentifierCodec(final SchemaContext context, final JSONCodecFactory jsonCodecFactory) {
28 this.context = Preconditions.checkNotNull(context);
29 this.dataContextTree = DataSchemaContextTree.from(context);
30 this.codecFactory = jsonCodecFactory;
34 protected Module moduleForPrefix(final String prefix) {
35 return context.findModuleByName(prefix, null);
39 protected String prefixForNamespace(final URI namespace) {
40 final Module module = context.findModuleByNamespaceAndRevision(namespace, null);
41 return module == null ? null : module.getName();
45 protected DataSchemaContextTree getDataContextTree() {
46 return dataContextTree;
50 public boolean needQuotes() {
55 protected Object deserializeKeyValue(DataSchemaNode schemaNode, String value) {
56 Preconditions.checkNotNull(schemaNode, "schemaNode cannot be null");
57 Preconditions.checkArgument(schemaNode instanceof LeafSchemaNode, "schemaNode must be of type LeafSchemaNode");
58 final JSONCodec<Object> objectJSONCodec = codecFactory.codecFor(schemaNode);
59 return objectJSONCodec.deserialize(value);
63 * Serialize YangInstanceIdentifier with specified JsonWriter.
65 * @param writer JsonWriter
66 * @param value YangInstanceIdentifier
69 public void serializeToWriter(JsonWriter writer, YangInstanceIdentifier value) throws IOException {
70 writer.value(serialize(value));