2 * Copyright (c) 2016 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
9 package org.opendaylight.yangtools.yang.data.codec.xml;
11 import com.google.common.base.Preconditions;
13 import java.util.Map.Entry;
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.codec.QNameCodecUtil;
20 import org.opendaylight.yangtools.yang.model.api.Module;
21 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
23 final class IdentityrefXmlCodec implements XmlCodec<QName> {
24 private final SchemaContext schemaContext;
25 private final QNameModule parentModule;
27 IdentityrefXmlCodec(final SchemaContext context, final QNameModule parentModule) {
28 this.schemaContext = Preconditions.checkNotNull(context);
29 this.parentModule = Preconditions.checkNotNull(parentModule);
33 public Class<QName> getDataType() {
38 public QName parseValue(final NamespaceContext ctx, final String str) {
39 return QNameCodecUtil.decodeQName(str, prefix -> {
40 if (prefix.isEmpty()) {
44 final String prefixedNS = ctx.getNamespaceURI(prefix);
45 final Module module = schemaContext.findModuleByNamespaceAndRevision(URI.create(prefixedNS), null);
46 Preconditions.checkArgument(module != null, "Could not find module for namespace %s", prefixedNS);
47 return module.getQNameModule();
52 public void writeValue(final XMLStreamWriter ctx, final QName value) throws XMLStreamException {
53 final RandomPrefix prefixes = new RandomPrefix(ctx.getNamespaceContext());
54 final String str = QNameCodecUtil.encodeQName(value, uri -> prefixes.encodePrefix(uri.getNamespace()));
56 for (Entry<URI, String> e : prefixes.getPrefixes()) {
57 ctx.writeNamespace(e.getValue(), e.getKey().toString());
59 ctx.writeCharacters(str);