Add JSONValue and JSONCodec.unparseValue()
[yangtools.git] / codec / 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 java.io.IOException;
14 import org.eclipse.jdt.annotation.NonNull;
15 import org.opendaylight.yangtools.yang.common.QName;
16 import org.opendaylight.yangtools.yang.common.QNameModule;
17 import org.opendaylight.yangtools.yang.data.codec.gson.JSONValue.Kind;
18 import org.opendaylight.yangtools.yang.data.util.codec.IdentityCodecUtil;
19 import org.opendaylight.yangtools.yang.data.util.codec.QNameCodecUtil;
20 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
21
22 final class IdentityrefJSONCodec implements JSONCodec<QName> {
23     private final @NonNull EffectiveModelContext context;
24     private final @NonNull QNameModule parentModule;
25
26     IdentityrefJSONCodec(final EffectiveModelContext context, final QNameModule parentModule) {
27         this.context = 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 String value) {
38         return IdentityCodecUtil.parseIdentity(value, context, prefix -> {
39             if (prefix.isEmpty()) {
40                 return parentModule;
41             }
42
43             final var modules = context.findModuleStatements(prefix).iterator();
44             checkArgument(modules.hasNext(), "Could not find module %s", prefix);
45             return modules.next().localQNameModule();
46         }).getQName();
47     }
48
49     @Override
50     public JSONValue unparseValue(final QName value) {
51         return new JSONValue(encode(value), Kind.STRING);
52     }
53
54     @Override
55     public void writeValue(final JSONValueWriter ctx, final QName value) throws IOException {
56         ctx.writeString(encode(value));
57     }
58
59     private @NonNull String encode(final QName value) {
60         return QNameCodecUtil.encodeQName(value, uri -> context.findModuleStatement(uri)
61             .map(module -> module.argument().getLocalName())
62             .orElseThrow(() -> new IllegalArgumentException("Cannot find module for " + uri)));
63     }
64 }