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