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;
14 import java.util.Iterator;
16 import javax.annotation.Nonnull;
17 import javax.annotation.Nullable;
19 import org.opendaylight.yangtools.yang.common.QName;
21 abstract class AbstractNamespaceCodec {
22 private static final Splitter COLON_SPLITTER = Splitter.on(':');
25 * Return string prefix for a particular namespace, allocating a new one if necessary.
27 * @param namespace Namespace to map
28 * @return Allocated unique prefix, or null if the prefix cannot be mapped.
30 protected abstract @Nullable String prefixForNamespace(final @Nonnull URI namespace);
33 * Create a QName for a prefix and local name.
35 * @param prefix Prefix for namespace
36 * @param localName local name
38 * @throws IllegalArgumentException if the prefix cannot be resolved
40 protected abstract @Nullable QName createQName(final @Nonnull String prefix, final @Nonnull String localName);
42 private static String getIdAndPrefixAsStr(final String pathPart) {
43 int predicateStartIndex = pathPart.indexOf('[');
44 return predicateStartIndex == -1 ? pathPart : pathPart.substring(0, predicateStartIndex);
47 protected final StringBuilder appendQName(final StringBuilder sb, final QName qname) {
48 final String prefix = prefixForNamespace(qname.getNamespace());
49 Preconditions.checkArgument(prefix != null, "Failed to map QName {}", qname);
52 sb.append(qname.getLocalName());
56 protected final QName parseQName(final String str) {
57 final String xPathPartTrimmed = getIdAndPrefixAsStr(str).trim();
58 final Iterator<String> it = COLON_SPLITTER.split(xPathPartTrimmed).iterator();
65 final String prefix = it.next().trim();
66 if (prefix.isEmpty()) {
70 // it is not "prefix:value"
75 final String identifier = it.next().trim();
76 if (identifier.isEmpty()) {
80 return createQName(prefix, identifier);