Merge "Fix modifier ordering"
[yangtools.git] / yang / yang-data-codec-gson / src / main / java / org / opendaylight / yangtools / yang / data / codec / gson / JSONStringIdentityrefCodec.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
15 import org.opendaylight.yangtools.yang.common.QName;
16 import org.opendaylight.yangtools.yang.common.QNameModule;
17 import org.opendaylight.yangtools.yang.data.util.AbstractModuleStringIdentityrefCodec;
18 import org.opendaylight.yangtools.yang.model.api.Module;
19 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
20
21 final class JSONStringIdentityrefCodec extends AbstractModuleStringIdentityrefCodec implements JSONCodec<QName> {
22     private final SchemaContext context;
23     private final QNameModule parentModuleQname;
24
25     JSONStringIdentityrefCodec(final SchemaContext context, final QNameModule parentModule) {
26         this.context = Preconditions.checkNotNull(context);
27         this.parentModuleQname = Preconditions.checkNotNull(parentModule);
28     }
29
30     @Override
31     protected Module moduleForPrefix(final String prefix) {
32         if (prefix.isEmpty()) {
33             return context.findModuleByNamespaceAndRevision(parentModuleQname.getNamespace(),
34                     parentModuleQname.getRevision());
35         } else {
36             return context.findModuleByName(prefix, null);
37         }
38     }
39
40     @Override
41     protected String prefixForNamespace(final URI namespace) {
42         final Module module = context.findModuleByNamespaceAndRevision(namespace, null);
43         return module == null ? null : module.getName();
44     }
45
46     @Override
47     public boolean needQuotes() {
48         return true;
49     }
50
51     /**
52      * Serialize QName with specified JsonWriter.
53      *
54      * @param writer JsonWriter
55      * @param value QName
56      */
57     @Override
58     public void serializeToWriter(JsonWriter writer, QName value) throws IOException {
59         writer.value(serialize(value));
60     }
61 }