Merge "Bug 2766: Fixed parsing and serializing XPath Instance Identifiers"
[yangtools.git] / yang / yang-data-codec-gson / src / main / java / org / opendaylight / yangtools / yang / data / codec / gson / JSONStringInstanceIdentifierCodec.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.data.codec.gson;
9
10 import com.google.common.base.Preconditions;
11 import com.google.gson.stream.JsonWriter;
12 import java.io.IOException;
13 import java.net.URI;
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.Module;
18 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
19
20 final class JSONStringInstanceIdentifierCodec extends AbstractModuleStringInstanceIdentifierCodec implements JSONCodec<YangInstanceIdentifier> {
21     private final SchemaContext context;
22     private final DataSchemaContextTree dataContextTree;
23
24     JSONStringInstanceIdentifierCodec(final SchemaContext context) {
25         this.context = Preconditions.checkNotNull(context);
26         this.dataContextTree = DataSchemaContextTree.from(context);
27     }
28
29     @Override
30     protected Module moduleForPrefix(final String prefix) {
31         return context.findModuleByName(prefix, null);
32     }
33
34     @Override
35     protected String prefixForNamespace(final URI namespace) {
36         final Module module = context.findModuleByNamespaceAndRevision(namespace, null);
37         return module == null ? null : module.getName();
38     }
39
40     @Override
41     protected DataSchemaContextTree getDataContextTree() {
42         return dataContextTree;
43     }
44
45     @Override
46     public boolean needQuotes() {
47         return true;
48     }
49
50     /**
51      * Serialize YangInstanceIdentifier with specified JsonWriter.
52      *
53      * @param writer JsonWriter
54      * @param value YangInstanceIdentifier
55      */
56     @Override
57     public void serializeToWriter(JsonWriter writer, YangInstanceIdentifier value) throws IOException {
58         writer.value(serialize(value));
59     }
60 }