BUG-4688: Rework SchemaContext module lookups
[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 static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.gson.stream.JsonWriter;
14 import java.io.IOException;
15 import java.util.Iterator;
16 import org.opendaylight.yangtools.yang.common.QName;
17 import org.opendaylight.yangtools.yang.common.QNameModule;
18 import org.opendaylight.yangtools.yang.data.util.codec.QNameCodecUtil;
19 import org.opendaylight.yangtools.yang.model.api.Module;
20 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
21
22 final class IdentityrefJSONCodec implements JSONCodec<QName> {
23     private final SchemaContext schemaContext;
24     private final QNameModule parentModule;
25
26     IdentityrefJSONCodec(final SchemaContext context, final QNameModule parentModule) {
27         this.schemaContext = requireNonNull(context);
28         this.parentModule = requireNonNull(parentModule);
29     }
30
31     @Override
32     public Class<QName> getDataType() {
33         return QName.class;
34     }
35
36     @Override
37     public QName parseValue(final Object ctx, final String value) {
38         return QNameCodecUtil.decodeQName(value, prefix -> {
39             if (prefix.isEmpty()) {
40                 return parentModule;
41             }
42
43             final Iterator<Module> modules = schemaContext.findModules(prefix).iterator();
44             checkArgument(modules.hasNext(), "Could not find module %s", prefix);
45             return modules.next().getQNameModule();
46         });
47     }
48
49     /**
50      * Serialize QName with specified JsonWriter.
51      *
52      * @param writer JsonWriter
53      * @param value QName
54      */
55     @Override
56     public void writeValue(final JsonWriter writer, final QName value) throws IOException {
57         final String str = QNameCodecUtil.encodeQName(value, uri -> {
58             final Iterator<Module> modules = schemaContext.findModules(uri.getNamespace()).iterator();
59             checkArgument(modules.hasNext(), "Cannot find module for %s", uri);
60             return modules.next().getName();
61         });
62         writer.value(str);
63     }
64 }