2ea18600cd6adb357289147814b33efc32ea23b1
[yangtools.git] / yang / yang-data-codec-xml / src / main / java / org / opendaylight / yangtools / yang / data / codec / xml / XmlStringIdentityrefCodec.java
1 /*
2  * Copyright (c) 2016 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
9 package org.opendaylight.yangtools.yang.data.codec.xml;
10
11 import com.google.common.base.Preconditions;
12 import java.net.URI;
13 import javax.xml.stream.XMLStreamException;
14 import javax.xml.stream.XMLStreamWriter;
15 import org.opendaylight.yangtools.yang.common.QName;
16 import org.opendaylight.yangtools.yang.common.QNameModule;
17 import org.opendaylight.yangtools.yang.data.util.AbstractModuleStringIdentityrefCodec;
18 import org.opendaylight.yangtools.yang.model.api.Module;
19 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
20
21 final class XmlStringIdentityrefCodec extends AbstractModuleStringIdentityrefCodec implements XmlCodec<QName> {
22
23     private final SchemaContext context;
24     private final QNameModule parentModuleQname;
25
26     XmlStringIdentityrefCodec(final SchemaContext context, final QNameModule parentModule) {
27         this.context = Preconditions.checkNotNull(context);
28         this.parentModuleQname = Preconditions.checkNotNull(parentModule);
29     }
30
31     @Override
32     protected Module moduleForPrefix(final String prefix) {
33         if (prefix.isEmpty()) {
34             return context.findModuleByNamespaceAndRevision(parentModuleQname.getNamespace(),
35                     parentModuleQname.getRevision());
36         } else {
37             return context.findModuleByName(prefix, null);
38         }
39     }
40
41     @Override
42     protected String prefixForNamespace(final URI namespace) {
43         final Module module = context.findModuleByNamespaceAndRevision(namespace, null);
44         return module == null ? null : module.getName();
45     }
46
47     /**
48      * Serialize QName with specified XMLStreamWriter.
49      *
50      * @param writer XMLStreamWriter
51      * @param value QName
52      */
53     @Override
54     public void serializeToWriter(XMLStreamWriter writer, QName value) throws XMLStreamException {
55         writer.writeCharacters(serialize(value));
56     }
57 }