2 * Copyright (c) 2014 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
8 package org.opendaylight.yangtools.yang.data.util;
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Splitter;
13 import java.util.Iterator;
14 import javax.annotation.Nonnull;
15 import javax.annotation.Nullable;
16 import org.opendaylight.yangtools.yang.common.QName;
18 abstract class AbstractNamespaceCodec {
19 private static final Splitter COLON_SPLITTER = Splitter.on(':');
22 * Return string prefix for a particular namespace, allocating a new one if necessary.
24 * @param namespace Namespace to map
25 * @return Allocated unique prefix, or null if the prefix cannot be mapped.
27 @Nullable protected abstract String prefixForNamespace(@Nonnull URI namespace);
30 * Create a QName for a prefix and local name.
32 * @param prefix Prefix for namespace
33 * @param localName local name
35 * @throws IllegalArgumentException if the prefix cannot be resolved
37 @Nullable protected abstract QName createQName(@Nonnull String prefix, @Nonnull String localName);
39 private static String getIdAndPrefixAsStr(final String pathPart) {
40 int predicateStartIndex = pathPart.indexOf('[');
41 return predicateStartIndex == -1 ? pathPart : pathPart.substring(0, predicateStartIndex);
44 protected final StringBuilder appendQName(final StringBuilder sb, final QName qname) {
45 final String prefix = prefixForNamespace(qname.getNamespace());
46 Preconditions.checkArgument(prefix != null, "Failed to map QName {}", qname);
49 sb.append(qname.getLocalName());
53 protected final QName parseQName(final String str) {
54 final String xPathPartTrimmed = getIdAndPrefixAsStr(str).trim();
55 final Iterator<String> it = COLON_SPLITTER.split(xPathPartTrimmed).iterator();
63 final String first = it.next().trim();
64 if (first.isEmpty()) {
68 final String identifier;
71 // It is "prefix:value"
73 identifier = it.next().trim();
78 if (identifier.isEmpty()) {
82 return createQName(prefix, identifier);