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