f2f434af9dc1731eb108ca0e209573387099125e
[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.namespace.NamespaceContext;
14 import javax.xml.stream.XMLStreamException;
15 import javax.xml.stream.XMLStreamWriter;
16 import org.opendaylight.yangtools.yang.common.QName;
17 import org.opendaylight.yangtools.yang.common.QNameModule;
18 import org.opendaylight.yangtools.yang.data.util.ModuleStringIdentityrefCodec;
19 import org.opendaylight.yangtools.yang.model.api.Module;
20 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
21
22 final class XmlStringIdentityrefCodec extends ModuleStringIdentityrefCodec implements XmlCodec<QName> {
23
24     private final NamespaceContext namespaceContext;
25
26     XmlStringIdentityrefCodec(final SchemaContext context, final QNameModule parentModule,
27                               final NamespaceContext namespaceContext) {
28         super(context, parentModule);
29         this.namespaceContext = Preconditions.checkNotNull(namespaceContext);
30     }
31
32     @Override
33     protected Module moduleForPrefix(final String prefix) {
34         if (prefix.isEmpty()) {
35             return context.findModuleByNamespaceAndRevision(parentModuleQname.getNamespace(),
36                     parentModuleQname.getRevision());
37         } else {
38             final String prefixedNS = namespaceContext.getNamespaceURI(prefix);
39             return context.findModuleByNamespaceAndRevision(URI.create(prefixedNS), null);
40         }
41     }
42
43     /**
44      * Serialize QName with specified XMLStreamWriter.
45      *
46      * @param writer XMLStreamWriter
47      * @param value QName
48      */
49     @Override
50     public void serializeToWriter(final XMLStreamWriter writer, final QName value) throws XMLStreamException {
51         writer.writeCharacters(serialize(value));
52     }
53 }