b2a2df6aace7d9593682847d11db0b6efda650cf
[yangtools.git] /
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 org.eclipse.jdt.annotation.NonNull;
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.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 Object ctx, 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     /**
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         writer.value(QNameCodecUtil.encodeQName(value, uri -> context.findModuleStatement(uri)
58             .map(module -> module.argument().getLocalName())
59             .orElseThrow(() -> new IllegalArgumentException("Cannot find module for " + uri))));
60     }
61 }