2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.codec.gson;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
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;
22 final class IdentityrefJSONCodec implements JSONCodec<QName> {
23 private final @NonNull EffectiveModelContext context;
24 private final @NonNull QNameModule parentModule;
26 IdentityrefJSONCodec(final EffectiveModelContext context, final QNameModule parentModule) {
27 this.context = requireNonNull(context);
28 this.parentModule = requireNonNull(parentModule);
32 public Class<QName> getDataType() {
37 public QName parseValue(final Object ctx, final String value) {
38 return IdentityCodecUtil.parseIdentity(value, context, prefix -> {
39 if (prefix.isEmpty()) {
43 final var modules = context.findModuleStatements(prefix).iterator();
44 checkArgument(modules.hasNext(), "Could not find module %s", prefix);
45 return modules.next().localQNameModule();
50 * Serialize QName with specified JsonWriter.
52 * @param writer JsonWriter
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))));