50379d30984d317b2ec4064483be39c7d3b0513c
[yangtools.git] / yang / yang-data-codec-gson / src / main / java / org / opendaylight / yangtools / yang / data / codec / gson / IdentityrefJSONCodec.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 org.opendaylight.yangtools.yang.common.QName;
14 import org.opendaylight.yangtools.yang.common.QNameModule;
15 import org.opendaylight.yangtools.yang.data.util.codec.QNameCodecUtil;
16 import org.opendaylight.yangtools.yang.model.api.Module;
17 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
18
19 final class IdentityrefJSONCodec implements JSONCodec<QName> {
20     private final SchemaContext schemaContext;
21     private final QNameModule parentModule;
22
23     IdentityrefJSONCodec(final SchemaContext context, final QNameModule parentModule) {
24         this.schemaContext = Preconditions.checkNotNull(context);
25         this.parentModule = Preconditions.checkNotNull(parentModule);
26     }
27
28     @Override
29     public Class<QName> getDataType() {
30         return QName.class;
31     }
32
33     @Override
34     public QName parseValue(final Object ctx, final String value) {
35         return QNameCodecUtil.decodeQName(value, prefix -> {
36             if (prefix.isEmpty()) {
37                 return parentModule;
38             }
39
40             final Module module = schemaContext.findModuleByName(prefix, null);
41             Preconditions.checkArgument(module != null, "Could not find module %s", prefix);
42             return module.getQNameModule();
43         });
44     }
45
46     /**
47      * Serialize QName with specified JsonWriter.
48      *
49      * @param writer JsonWriter
50      * @param value QName
51      */
52     @Override
53     public void writeValue(final JsonWriter writer, final QName value) throws IOException {
54         final String str = QNameCodecUtil.encodeQName(value, uri -> {
55             final Module module = schemaContext.findModuleByNamespaceAndRevision(uri.getNamespace(), null);
56             Preconditions.checkArgument(module != null, "Cannot find module for %s", uri);
57             return module.getName();
58         });
59         writer.value(str);
60     }
61 }