private def Type createReturnTypeForUnion(GeneratedTOBuilder genTOBuilder, TypeDefinition<?> typeDef,
GeneratedTypeBuilder typeBuilder, Module parentModule) {
- val Type returnType = new ReferencedTypeImpl(genTOBuilder.packageName, genTOBuilder.name);
+ val GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.packageName, genTOBuilder.name)
genTOBuilder.setTypedef(true);
genTOBuilder.setIsUnion(true);
(typeProvider as TypeProviderImpl).addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
} else {
types.add(unionBuilder.toInstance)
}
- return returnType
+ return returnType.toInstance
}
private def GeneratedTypeBuilder addDefaultInterfaceDefinition(String packageName, SchemaNode schemaNode) {
private final ClassLoadingStrategy classLoadingStrategy;
- // FIXME: will become final
- private ClassPool pool;
- private AbstractTransformerGenerator binding;
- private LazyGeneratedCodecRegistry registry;
+ private final AbstractTransformerGenerator binding;
+ private final LazyGeneratedCodecRegistry registry;
+ private final ClassPool pool;
/*
* FIXME: updated here, access from AbstractTransformer
private final ConcurrentMap<Type, Type> typeDefinitions = new ConcurrentHashMap<>();
private SchemaContext schemaContext;
- @Deprecated
- public RuntimeGeneratedMappingServiceImpl() {
- this(GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy());
- }
-
- @Deprecated
- public RuntimeGeneratedMappingServiceImpl(final ClassLoadingStrategy strat) {
- classLoadingStrategy = strat;
- }
-
public RuntimeGeneratedMappingServiceImpl(final ClassPool pool) {
this(pool, GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy());
}
this.pool = Preconditions.checkNotNull(pool);
this.classLoadingStrategy = Preconditions.checkNotNull(strat);
- // FIXME: merge into constructor once legacy init() is removed
- doInit();
- }
-
- private void doInit() {
binding = new TransformerGenerator(this, pool);
registry = new LazyGeneratedCodecRegistry(this, binding, classLoadingStrategy);
binding.setListener(registry);
// }
}
- @Deprecated
- public void setPool(final ClassPool pool) {
- this.pool = pool;
- }
-
@Override
public synchronized SchemaContext getSchemaContext() {
return schemaContext;
for (Map.Entry<QName, Object> predicate : predicates.getKeyValues().entrySet()) {
newNodes.add(new SimpleNodeTOImpl<Object>(predicate.getKey(), null, predicate.getValue()));
}
- newNodes.addAll(ret.getChildren());
+ newNodes.addAll(ret.getValue());
return new CompositeNodeTOImpl(last.getNodeType(), null, newNodes);
}
return ret;
}
}
- @Deprecated
- public void init() {
- doInit();
- }
@Override
public Set<QName> getRpcQNamesFor(final Class<? extends RpcService> service) {
return null;
}
- private def Class<?> generateValueTransformer(Class<?> inputType, Enumeration typeSpec, TypeDefinition<?> type) {
+ private def dispatch Class<?> generateValueTransformer(Class<?> inputType, Enumeration typeSpec, TypeDefinition<?> type) {
var EnumerationType enumSchemaType
if (type instanceof EnumerationType) {
enumSchemaType = type as EnumerationType
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;
import java.util.Set;
+
import org.junit.Ignore;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.parser.util.RefineHolder;
import org.opendaylight.yangtools.yang.parser.util.RefineUtils;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+
//Test for class RefineUtils
public class RefineTest {
testModels.add(listModelFile);
}
- private void findUnknownNode(DataSchemaNodeBuilder childNode, String unknownNodeValue, String unknownNodeName) {
+ private void findUnknownNode(final DataSchemaNodeBuilder childNode, final String unknownNodeValue, final String unknownNodeName) {
List<UnknownSchemaNodeBuilder> unknownSchemaNodesBuilder = childNode.getUnknownNodes();
boolean refinedUnknownNodeLflstFound = false;
refinedUnknownNodeLflstFound);
}
- private void findMustConstraint(ConstraintsBuilder conDef, String mustValue) {
+ private void findMustConstraint(final ConstraintsBuilder conDef, final String mustValue) {
boolean mustLflstFound = false;
for (MustDefinition mustDef : conDef.getMustDefinitions()) {
if (mustDef.toString().equals(mustValue)) {
return moduleBuilder;
}
- private void checkAnyXmlRefineHolderAndSchemaNodeBuilder(String string, List<RefineHolder> refineHolders,
- Set<DataSchemaNodeBuilder> dataSchemaNodeBuilders) {
+ private void checkAnyXmlRefineHolderAndSchemaNodeBuilder(final String string, final List<RefineHolder> refineHolders,
+ final Set<DataSchemaNodeBuilder> dataSchemaNodeBuilders) {
RefineHolder refHolderData = getRefineHolder("data", refineHolders);
QName qname = createQname();
}
- private void checkChc2RefineHolderAndSchemaNodeBuilder(String nodeName, List<RefineHolder> refineHolders,
- Set<DataSchemaNodeBuilder> dataSchemaNodeBuilders) {
+ private void checkChc2RefineHolderAndSchemaNodeBuilder(final String nodeName, final List<RefineHolder> refineHolders,
+ final Set<DataSchemaNodeBuilder> dataSchemaNodeBuilders) {
RefineHolder refHolderChc2 = getRefineHolder("chc2", refineHolders);
QName qname = createQname();
List<QName> path = Lists.newArrayList(qname);
- DataSchemaNodeBuilder builderChc2 = new ChoiceBuilder("module", 4, qname, new SchemaPath(path, true));
+ DataSchemaNodeBuilder builderChc2 = new ChoiceBuilder("module", 4, qname, SchemaPath.create(path, true));
assertNotNull("Refine holder chc2 wasn't initialized.", refHolderChc2);
RefineUtils.refineChoice((ChoiceBuilder) builderChc2, refHolderChc2);
assertFalse("'chc2' has incorrect value for 'mandatory'", conDefChc2.isMandatory());
}
- private void checkChcRefineHolderAndSchemaNodeBuilder(String nodeName, List<RefineHolder> refineHolders,
- Set<DataSchemaNodeBuilder> dataSchemaNodeBuilders) {
+ private void checkChcRefineHolderAndSchemaNodeBuilder(final String nodeName, final List<RefineHolder> refineHolders,
+ final Set<DataSchemaNodeBuilder> dataSchemaNodeBuilders) {
RefineHolder refHolderChc = getRefineHolder("chc", refineHolders);
QName qname = createQname();
List<QName> path = Lists.newArrayList(qname);
- DataSchemaNodeBuilder builderChc = new ChoiceBuilder("module", 4, qname, new SchemaPath(path, true));
+ DataSchemaNodeBuilder builderChc = new ChoiceBuilder("module", 4, qname, SchemaPath.create(path, true));
assertNotNull("Refine holder chc wasn't initialized.", refHolderChc);
assertNotNull("Data schema node builder chc wasn't initialized.", builderChc);
findUnknownNode(choiceBuilder, unknownNodeChcValue, unknownNodeChcName);
}
- private void checkLflstRefineHolderAndSchemaNodeBuilder(String nodeName, List<RefineHolder> refineHolders,
- Set<DataSchemaNodeBuilder> dataSchemaNodeBuilders) {
+ private void checkLflstRefineHolderAndSchemaNodeBuilder(final String nodeName, final List<RefineHolder> refineHolders,
+ final Set<DataSchemaNodeBuilder> dataSchemaNodeBuilders) {
RefineHolder refHolderLflst = getRefineHolder(nodeName, refineHolders);
QName qname = createQname();
}
- private RefineHolder getRefineHolder(String refHolderName, List<RefineHolder> refineHolders) {
+ private RefineHolder getRefineHolder(final String refHolderName, final List<RefineHolder> refineHolders) {
for (RefineHolder refineHolder : refineHolders) {
if (refineHolder.getName().equals(refHolderName)) {
return refineHolder;
return qname;
}
- private SchemaPath createSchemaPath(QName qname) {
+ private SchemaPath createSchemaPath(final QName qname) {
List<QName> qnames = new ArrayList<>();
qnames.add(createQname());
- return new SchemaPath(qnames, true);
+ return SchemaPath.create(qnames, true);
}
}
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
-import java.util.HashSet;
import java.util.List;
-import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
import org.opendaylight.yangtools.yang.model.util.ExtendedType;
+import com.google.common.base.Splitter;
+
/**
* Contains the methods for converting strings to valid JAVA language strings
* (package names, class names, attribute names).
}
@Override
- public void set(SimpleDateFormat value) {
+ public void set(final SimpleDateFormat value) {
throw new UnsupportedOperationException();
}
};
- /**
- * Array of strings values which represents JAVA reserved words.
- */
- @Deprecated
- private static final String[] SET_VALUES = new String[] { "abstract", "assert", "boolean", "break", "byte", "case",
- "catch", "char", "class", "const", "continue", "default", "double", "do", "else", "enum", "extends",
- "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int",
- "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return",
- "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient",
- "true", "try", "void", "volatile", "while" };
-
/**
* Impossible to instantiate this class. All of the methods or attributes
* are static.
}
/**
- * Hash set of words which are reserved in JAVA language.
+ * Pre-compiled replacement pattern.
*/
- @Deprecated
- private static final Set<String> JAVA_RESERVED_WORDS = new HashSet<String>(Arrays.asList(SET_VALUES));
+ private static final Pattern COLON_SLASH_SLASH = Pattern.compile("://", Pattern.LITERAL);
+ private static final String QUOTED_DOT = Matcher.quoteReplacement(".");
+ private static final Splitter DOT = Splitter.on('.');
/**
* Converts string <code>packageName</code> to valid JAVA package name.
* @return package name which contains words separated by point.
*/
private static String validateJavaPackage(final String packageName) {
- if (packageName != null) {
- final String[] packNameParts = packageName.toLowerCase().split("\\.");
- if (packNameParts != null) {
- final StringBuilder builder = new StringBuilder();
- for (int i = 0; i < packNameParts.length; ++i) {
- final String packNamePart = packNameParts[i];
- if (Character.isDigit(packNamePart.charAt(0))) {
- packNameParts[i] = "_" + packNamePart;
- } else if (JAVA_RESERVED_WORDS.contains(packNamePart)) {
- packNameParts[i] = "_" + packNamePart;
- }
- if (i > 0) {
- builder.append(".");
- }
- builder.append(packNameParts[i]);
- }
- return builder.toString();
+ if (packageName == null) {
+ return null;
+ }
+
+ final StringBuilder builder = new StringBuilder();
+ boolean first = true;
+
+ for (String p : DOT.split(packageName.toLowerCase())) {
+ if (first) {
+ first = false;
+ } else {
+ builder.append('.');
+ }
+
+ if (Character.isDigit(p.charAt(0)) || BindingMapping.JAVA_RESERVED_WORDS.contains(p)) {
+ builder.append('_');
}
+ builder.append(p);
}
- return packageName;
+
+ return builder.toString();
}
/**
* @return string with the admissible parameter name
*/
public static String resolveJavaReservedWordEquivalency(final String parameterName) {
- if (parameterName != null && JAVA_RESERVED_WORDS.contains(parameterName)) {
+ if (parameterName != null && BindingMapping.JAVA_RESERVED_WORDS.contains(parameterName)) {
return "_" + parameterName;
}
return parameterName;
if (module.getRevision() == null) {
throw new IllegalArgumentException("Module " + module.getName() + " does not specify revision date!");
}
- packageNameBuilder.append("org.opendaylight.yang.gen.v");
- packageNameBuilder.append(module.getYangVersion());
- packageNameBuilder.append(".");
+ packageNameBuilder.append(BindingMapping.PACKAGE_PREFIX);
+ packageNameBuilder.append('.');
String namespace = module.getNamespace().toString();
- namespace = namespace.replace("://", ".");
- namespace = namespace.replace("/", ".");
- namespace = namespace.replace(":", ".");
- namespace = namespace.replace("-", ".");
- namespace = namespace.replace("@", ".");
- namespace = namespace.replace("$", ".");
- namespace = namespace.replace("#", ".");
- namespace = namespace.replace("'", ".");
- namespace = namespace.replace("*", ".");
- namespace = namespace.replace("+", ".");
- namespace = namespace.replace(",", ".");
- namespace = namespace.replace(";", ".");
- namespace = namespace.replace("=", ".");
-
- packageNameBuilder.append(namespace);
+ namespace = COLON_SLASH_SLASH.matcher(namespace).replaceAll(QUOTED_DOT);
+
+ final char[] chars = namespace.toCharArray();
+ for (int i = 0; i < chars.length; ++i) {
+ switch (chars[i]) {
+ case '/':
+ case ':':
+ case '-':
+ case '@':
+ case '$':
+ case '#':
+ case '\'':
+ case '*':
+ case '+':
+ case ',':
+ case ';':
+ case '=':
+ chars[i] = '.';
+ }
+ }
+
+ packageNameBuilder.append(chars);
packageNameBuilder.append(".rev");
packageNameBuilder.append(DATE_FORMAT.get().format(module.getRevision()));
* @return string with valid JAVA package name
*/
public static String packageNameForGeneratedType(final String basePackageName, final SchemaPath schemaPath,
- boolean isUsesAugment) {
+ final boolean isUsesAugment) {
if (basePackageName == null) {
throw new IllegalArgumentException("Base Package Name cannot be NULL!");
}
traversalSteps = (pathToNode.size() - 1);
}
for (int i = 0; i < traversalSteps; ++i) {
- builder.append(".");
+ builder.append('.');
String nodeLocalName = pathToNode.get(i).getLocalName();
- nodeLocalName = nodeLocalName.replace(":", ".");
- nodeLocalName = nodeLocalName.replace("-", ".");
+ nodeLocalName = nodeLocalName.replace(':', '.');
+ nodeLocalName = nodeLocalName.replace('-', '.');
builder.append(nodeLocalName);
}
return validateJavaPackage(builder.toString());
* @deprecated Use {@link BindingMapping#getClassName(QName)} instead.
*/
@Deprecated
- public static String parseToClassName(String token) {
+ public static String parseToClassName(final String token) {
return parseToCamelCase(token, true);
}
correctStr = replaceWithCamelCase(correctStr, '-');
correctStr = replaceWithCamelCase(correctStr, '_');
- String firstChar = correctStr.substring(0, 1);
- if (uppercase) {
- firstChar = firstChar.toUpperCase();
- } else {
- firstChar = firstChar.toLowerCase();
- }
+ char firstChar = correctStr.charAt(0);
+ firstChar = uppercase ? Character.toUpperCase(firstChar) : Character.toLowerCase(firstChar);
- if (firstChar.matches("[0-9]")) {
- correctStr = "_" + correctStr;
+ if (firstChar >= '0' && firstChar <= '9') {
+ return correctStr = '_' + correctStr;
} else {
- correctStr = firstChar + correctStr.substring(1);
+ return correctStr = firstChar + correctStr.substring(1);
}
- return correctStr;
}
/**
* @throws IllegalArgumentException
* if the length of the returning string has length 0
*/
- private static String replaceWithCamelCase(String text, char removalChar) {
+ private static String replaceWithCamelCase(final String text, final char removalChar) {
StringBuilder sb = new StringBuilder(text);
String toBeRemoved = String.valueOf(removalChar);
return sb.toString();
}
- public static long computeDefaultSUID(GeneratedTOBuilderImpl to) {
+ public static long computeDefaultSUID(final GeneratedTOBuilderImpl to) {
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
List<Type> impl = to.getImplementsTypes();
Collections.sort(impl, new Comparator<Type>() {
@Override
- public int compare(Type o1, Type o2) {
+ public int compare(final Type o1, final Type o2) {
return o1.getFullyQualifiedName().compareTo(o2.getFullyQualifiedName());
}
});
Comparator<TypeMemberBuilder<?>> comparator = new Comparator<TypeMemberBuilder<?>>() {
@Override
- public int compare(TypeMemberBuilder<?> o1, TypeMemberBuilder<?> o2) {
+ public int compare(final TypeMemberBuilder<?> o1, final TypeMemberBuilder<?> o2) {
return o1.getName().compareTo(o2.getName());
}
};
}
}
- public static Restrictions getRestrictions(TypeDefinition<?> type) {
+ public static Restrictions getRestrictions(final TypeDefinition<?> type) {
final List<LengthConstraint> length = new ArrayList<>();
final List<PatternConstraint> pattern = new ArrayList<>();
final List<RangeConstraint> range = new ArrayList<>();
--- /dev/null
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>common-parent</artifactId>
+ <version>0.6.2-SNAPSHOT</version>
+ </parent>
+ <artifactId>checkstyle-logging</artifactId>
+
+ <dependencies>
+ <dependency>
+ <groupId>com.puppycrawl.tools</groupId>
+ <artifactId>checkstyle</artifactId>
+ <version>5.6</version>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.yangtools.checkstyle;
+
+import java.util.List;
+
+import org.slf4j.Logger;
+
+import com.google.common.collect.Lists;
+import com.puppycrawl.tools.checkstyle.api.DetailAST;
+import com.puppycrawl.tools.checkstyle.api.FullIdent;
+import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+import com.puppycrawl.tools.checkstyle.checks.CheckUtils;
+
+public class CheckLoggingUtil {
+
+ public static final String LOGGER_TYPE_NAME = Logger.class.getSimpleName();
+ public static final String LOGGER_TYPE_FULL_NAME = Logger.class.getName();
+ public static final String LOGGER_VAR_NAME = "LOG";
+ private static final List<String> LOG_METHODS = Lists.newArrayList("debug", "info", "error", "warn", "trace");
+
+ private CheckLoggingUtil() {}
+
+ public static String getTypeName(final DetailAST aAST) {
+ final FullIdent ident = CheckUtils.createFullType(aAST.findFirstToken(TokenTypes.TYPE));
+ return ident.getText();
+ }
+
+ public static boolean isLoggerType(final DetailAST aAST) {
+ final String typeName = getTypeName(aAST);
+ if(typeName.equals(LOGGER_TYPE_FULL_NAME) || typeName.equals(LOGGER_TYPE_NAME)) {
+ return true;
+ }
+ return false;
+ }
+
+ public static String getVariableName(final DetailAST aAST) {
+ DetailAST identifier = aAST.findFirstToken(TokenTypes.IDENT);
+ return identifier.getText();
+ }
+
+ public static boolean itsAFieldVariable(final DetailAST aAST) {
+ return aAST.getParent().getType() == TokenTypes.OBJBLOCK;
+ }
+
+ public static String getMethodName(final DetailAST aAST) {
+ if(aAST.getFirstChild().getLastChild() != null) {
+ return aAST.getFirstChild().getLastChild().getText();
+ }
+ return aAST.getFirstChild().getText();
+ }
+
+ public static boolean isLogMethod(final String methodName) {
+ return LOG_METHODS.contains(methodName);
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.yangtools.checkstyle;
+
+import com.puppycrawl.tools.checkstyle.api.Check;
+import com.puppycrawl.tools.checkstyle.api.DetailAST;
+import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+
+public class LogMessageConcatenationCheck extends Check {
+
+ private static final String LOG_MESSAGE = "Log message contains string concatenation.";
+
+ @Override
+ public int[] getDefaultTokens() {
+ return new int[]{TokenTypes.METHOD_CALL};
+ }
+
+ @Override
+ public void visitToken(DetailAST aAST) {
+ final String methodName = CheckLoggingUtil.getMethodName(aAST);
+ if(CheckLoggingUtil.isLogMethod(methodName)) {
+ final String logMessage = aAST.findFirstToken(TokenTypes.ELIST).getFirstChild().getFirstChild().getText();
+ if(logMessage.contains("+")) {
+ log(aAST.getLineNo(), LOG_MESSAGE);
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.yangtools.checkstyle;
+
+import com.puppycrawl.tools.checkstyle.api.Check;
+import com.puppycrawl.tools.checkstyle.api.DetailAST;
+import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+
+public class LogMessagePlaceholderCountCheck extends Check {
+
+ private static final String LOG_MESSAGE = "Log message placeholders count is incorrect.";
+ private static final String PLACEHOLDER = "{}";
+ private static final String EXCEPTION_TYPE = "Exception";
+
+ @Override
+ public int[] getDefaultTokens() {
+ return new int[]{TokenTypes.METHOD_CALL};
+ }
+
+ @Override
+ public void visitToken(DetailAST aAST) {
+ final String methodName = CheckLoggingUtil.getMethodName(aAST);
+ if(CheckLoggingUtil.isLogMethod(methodName)) {
+ final String logMessage = aAST.findFirstToken(TokenTypes.ELIST).getFirstChild().getFirstChild().getText();
+ int placeholdersCount = placeholdersCount(logMessage);
+ int argumentsCount = aAST.findFirstToken(TokenTypes.ELIST).getChildCount(TokenTypes.EXPR) - 1;
+ final String lastArg = aAST.findFirstToken(TokenTypes.ELIST).getLastChild().getFirstChild().getText();
+ if(hasCatchBlockParentWithArgument(lastArg, aAST) || hasMethodDefinitionWithExceptionArgument(lastArg, aAST)) {
+ argumentsCount--;
+ }
+ if(placeholdersCount > argumentsCount) {
+ log(aAST.getLineNo(), LOG_MESSAGE);
+ }
+ }
+ }
+
+ private int placeholdersCount(final String message) {
+ return (message.length() - message.replace(PLACEHOLDER, "").length()) / PLACEHOLDER.length();
+ }
+
+ private boolean hasCatchBlockParentWithArgument(final String argumentName, final DetailAST aAST) {
+ DetailAST parent = aAST.getParent();
+ while(parent != null && parent.getType() != TokenTypes.LITERAL_CATCH) {
+ parent = parent.getParent();
+ }
+ if(parent != null) {
+ if(parent.findFirstToken(TokenTypes.PARAMETER_DEF) != null &&
+ parent.findFirstToken(TokenTypes.PARAMETER_DEF).findFirstToken(TokenTypes.IDENT).getText().equals(argumentName)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private boolean hasMethodDefinitionWithExceptionArgument(final String argumentName, final DetailAST aAST) {
+ DetailAST parent = aAST.getParent();
+ while(parent != null && parent.getType() != TokenTypes.METHOD_DEF) {
+ parent = parent.getParent();
+ }
+ if(parent != null) {
+ if(parent.findFirstToken(TokenTypes.PARAMETERS).findFirstToken(TokenTypes.PARAMETER_DEF) != null) {
+ DetailAST paramDef = parent.findFirstToken(TokenTypes.PARAMETERS).getFirstChild();
+ while(paramDef != null) {
+ if(paramDef.getType() == TokenTypes.PARAMETER_DEF) {
+ final String paramName = paramDef.findFirstToken(TokenTypes.IDENT).getText();
+ if(paramName.equals(argumentName) && isExceptionType(paramDef)) {
+ return true;
+ }
+ }
+ paramDef = paramDef.getNextSibling();
+ }
+ }
+ }
+ return false;
+ }
+
+ private boolean isExceptionType(final DetailAST parameterDef) {
+ if(parameterDef != null) {
+ final DetailAST type = parameterDef.findFirstToken(TokenTypes.TYPE);
+ if(type != null && type.findFirstToken(TokenTypes.IDENT) != null) {
+ final String argumentType = type.findFirstToken(TokenTypes.IDENT).getText();
+ if(argumentType.contains(EXCEPTION_TYPE)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.yangtools.checkstyle;
+
+import com.puppycrawl.tools.checkstyle.api.Check;
+import com.puppycrawl.tools.checkstyle.api.DetailAST;
+import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+
+public class LoggerFactoryClassParameterCheck extends Check {
+
+ private static final String LOG_MESSAGE = "LoggerFactory.getLogger Class argument is incorrect.";
+ private static final String METHOD_NAME = "getLogger";
+
+ @Override
+ public int[] getDefaultTokens() {
+ return new int[]{TokenTypes.METHOD_CALL};
+ }
+
+ @Override
+ public void visitToken(DetailAST aAST) {
+ final String methodName = CheckLoggingUtil.getMethodName(aAST);
+ if(methodName.equals(METHOD_NAME)) {
+ final String className = getClassName(aAST);
+ final String parameter = aAST.findFirstToken(TokenTypes.ELIST).getFirstChild().getFirstChild().getFirstChild().getText();
+ if(!parameter.equals(className)) {
+ log(aAST.getLineNo(), LOG_MESSAGE);
+ }
+ }
+ }
+
+ private String getClassName(final DetailAST aAST) {
+ DetailAST parent = aAST.getParent();
+ while(parent.getType() != TokenTypes.CLASS_DEF && parent.getType() != TokenTypes.ENUM_DEF) {
+ parent = parent.getParent();
+ }
+ return parent.findFirstToken(TokenTypes.IDENT).getText();
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.yangtools.checkstyle;
+
+import static org.opendaylight.yangtools.checkstyle.CheckLoggingUtil.LOGGER_TYPE_FULL_NAME;
+import static org.opendaylight.yangtools.checkstyle.CheckLoggingUtil.LOGGER_TYPE_NAME;
+
+import com.puppycrawl.tools.checkstyle.api.Check;
+import com.puppycrawl.tools.checkstyle.api.DetailAST;
+import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+
+public class LoggerMustBeSlf4jCheck extends Check {
+
+ private static final String LOG_MESSAGE = "Logger must be slf4j.";
+ private static final String SLF4J = "slf4j";
+
+ @Override
+ public int[] getDefaultTokens() {
+ return new int[]{TokenTypes.VARIABLE_DEF, TokenTypes.IMPORT};
+ }
+
+ @Override
+ public void visitToken(DetailAST aAST) {
+ if(aAST.getType() == TokenTypes.VARIABLE_DEF) {
+ final String typeName = CheckLoggingUtil.getTypeName(aAST);
+ if (CheckLoggingUtil.itsAFieldVariable(aAST) && typeName.contains("." + LOGGER_TYPE_NAME)) {
+ if(!typeName.equals(LOGGER_TYPE_FULL_NAME)) {
+ log(aAST.getLineNo(), LOG_MESSAGE);
+ }
+ }
+ } else if(aAST.getType() == TokenTypes.IMPORT) {
+ final String importType = aAST.getFirstChild().findFirstToken(TokenTypes.IDENT).getText();
+ if(importType.equals(CheckLoggingUtil.LOGGER_TYPE_NAME)) {
+ final String importIdent = aAST.getFirstChild().getFirstChild().getLastChild().getText();
+ if(!importIdent.equals(SLF4J)) {
+ log(aAST.getLineNo(), LOG_MESSAGE);
+ }
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.yangtools.checkstyle;
+
+import com.puppycrawl.tools.checkstyle.api.Check;
+import com.puppycrawl.tools.checkstyle.api.DetailAST;
+import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+
+public class LoggerVariableModifiersCheck extends Check {
+
+ private static final String LOG_MESSAGE = "Logger must be declared as private static final.";
+
+ @Override
+ public int[] getDefaultTokens() {
+ return new int[]{TokenTypes.VARIABLE_DEF};
+ }
+
+ @Override
+ public void visitToken(DetailAST aAST) {
+ if (CheckLoggingUtil.itsAFieldVariable(aAST) && CheckLoggingUtil.isLoggerType(aAST) && !hasPrivatStaticFinalModifier(aAST)) {
+ log(aAST.getLineNo(), LOG_MESSAGE);
+ }
+ }
+
+ private boolean hasPrivatStaticFinalModifier(DetailAST aAST) {
+ DetailAST modifiers = aAST.findFirstToken(TokenTypes.MODIFIERS);
+ if(modifiers != null) {
+ if(modifiers.branchContains(TokenTypes.LITERAL_PRIVATE) && modifiers.branchContains(TokenTypes.LITERAL_STATIC)
+ && modifiers.branchContains(TokenTypes.FINAL)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.yangtools.checkstyle;
+
+import static org.opendaylight.yangtools.checkstyle.CheckLoggingUtil.LOGGER_VAR_NAME;
+
+import com.puppycrawl.tools.checkstyle.api.Check;
+import com.puppycrawl.tools.checkstyle.api.DetailAST;
+import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+
+public class LoggerVariableNameCheck extends Check {
+
+ private static final String LOG_MESSAGE = "Logger name should be LOG.";
+
+ @Override
+ public int[] getDefaultTokens() {
+ return new int[]{TokenTypes.VARIABLE_DEF};
+ }
+
+ @Override
+ public void visitToken(DetailAST aAST) {
+ final String variableName = CheckLoggingUtil.getVariableName(aAST);
+ if (CheckLoggingUtil.itsAFieldVariable(aAST) && CheckLoggingUtil.isLoggerType(aAST) && !variableName.equals(LOGGER_VAR_NAME)) {
+ log(aAST.getLineNo(), LOG_MESSAGE);
+ }
+ }
+
+}
--- /dev/null
+<?xml version="1.0"?>
+<!DOCTYPE module PUBLIC
+ "-//Puppy Crawl//DTD Check Configuration 1.2//EN"
+ "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">
+
+<module name="Checker">
+
+ <module name="RegexpMultiline">
+ <property name="format" value="System\.(out)|(err)\.print(ln)?\("/>
+ <property name="message" value="Line contains console output."/>
+ </module>
+
+ <module name="RegexpMultiline">
+ <property name="format" value="\.printStackTrace?\("/>
+ <property name="message" value="Line contains printStacktrace()."/>
+ </module>
+
+ <module name="TreeWalker">
+ <module name="org.opendaylight.yangtools.checkstyle.LoggerVariableNameCheck" />
+ </module>
+
+ <module name="TreeWalker">
+ <module name="org.opendaylight.yangtools.checkstyle.LoggerVariableModifiersCheck" />
+ </module>
+
+ <module name="TreeWalker">
+ <module name="org.opendaylight.yangtools.checkstyle.LoggerMustBeSlf4jCheck" />
+ </module>
+
+ <module name="TreeWalker">
+ <module name="org.opendaylight.yangtools.checkstyle.LoggerFactoryClassParameterCheck" />
+ </module>
+
+ <module name="TreeWalker">
+ <module name="org.opendaylight.yangtools.checkstyle.LogMessageConcatenationCheck" />
+ </module>
+
+ <module name="TreeWalker">
+ <module name="org.opendaylight.yangtools.checkstyle.LogMessagePlaceholderCountCheck" />
+ </module>
+
+ <module name="RegexpSingleline">
+ <property name="format" value="(\.|\b)Logger "/>
+ <property name="message" value="Logger might be declared only once."/>
+ <property name="minimum" value="0"/>
+ <property name="maximum" value="1"/>
+ </module>
+</module>
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.yangtools.checkstyle;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class CheckLoggingTestClass {
+ final Logger logger = LoggerFactory.getLogger(CheckstyleTest.class);
+ private static final java.util.logging.Logger LOG2 = java.util.logging.Logger.getGlobal();
+ private static final Logger LOG = LoggerFactory.getLogger(CheckLoggingTestClass.class);
+ public void foo() {
+ try {
+ logger.debug("foo + bar {}", "foo");
+ } catch(Exception e) {
+ e.printStackTrace();
+ System.out.println(e.getMessage());
+ System.err.print(e.getMessage());
+ logger.debug("foo {}", "bar", e);
+ LOG.info("foo {} {}", e.getMessage(), e);
+ }
+ }
+
+ public void bar(String string, IllegalArgumentException e) {
+ LOG.warn("foo", e);
+ LOG.warn("foo {}", e);
+ LOG.warn("foo", string);
+ LOG.warn("foo {}", string);
+ LOG.warn("foo {}", string, e);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.yangtools.checkstyle;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.xml.sax.InputSource;
+
+import com.google.common.collect.Lists;
+import com.puppycrawl.tools.checkstyle.Checker;
+import com.puppycrawl.tools.checkstyle.ConfigurationLoader;
+import com.puppycrawl.tools.checkstyle.DefaultLogger;
+import com.puppycrawl.tools.checkstyle.PropertiesExpander;
+import com.puppycrawl.tools.checkstyle.api.AuditListener;
+import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
+import com.puppycrawl.tools.checkstyle.api.Configuration;
+
+public class CheckstyleTest {
+
+ private Checker checker;
+ private ByteArrayOutputStream baos;
+
+ @Before
+ public void setup() throws CheckstyleException {
+ baos = new ByteArrayOutputStream();
+ AuditListener listener = new DefaultLogger(baos, false);
+
+ InputSource inputSource = new InputSource(CheckstyleTest.class.getClassLoader().getResourceAsStream(
+ "checkstyle-logging.xml"));
+ Configuration configuration = ConfigurationLoader.loadConfiguration(inputSource,
+ new PropertiesExpander(System.getProperties()), false);
+
+ checker = new Checker();
+ checker.setModuleClassLoader(Checker.class.getClassLoader());
+ checker.configure(configuration);
+ checker.addListener(listener);
+ }
+
+ @After
+ public void destroy() {
+ checker.destroy();
+ }
+
+ @Test
+ public void testLoggerChecks() throws Exception {
+ verify(CheckLoggingTestClass.class, "15: Logger must be declared as private static final.", "15: Logger name should be LOG.",
+ "16: Logger might be declared only once.", "16: Logger must be slf4j.", "22: Line contains printStacktrace",
+ "23: Line contains console output", "24: Line contains console output",
+ "15: LoggerFactory.getLogger Class argument is incorrect.", "20: Log message contains string concatenation.",
+ "26: Log message placeholders count is incorrect.", "32: Log message placeholders count is incorrect");
+ }
+
+ private void verify(final Class<?> testClass, final String... expectedMessages) {
+ final String filePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + testClass.getName().replaceAll("\\.", "/") + ".java";
+ final File testFile = new File(filePath);
+ checker.process(Lists.newArrayList(testFile));
+ final String output = baos.toString();
+ for(final String message : expectedMessages) {
+ assertTrue("Expected message not found: " + message, output.contains(message));
+ }
+ }
+}
<packaging>pom</packaging>
<modules>
+ <module>checkstyle-logging</module>
<module>concepts</module>
<module>feature</module>
<module>mockito-configuration</module>
<module>object-cache-api</module>
<module>object-cache-guava</module>
<module>object-cache-noop</module>
+ <module>util</module>
</modules>
<dependencyManagement>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- vi: set et smarttab sw=4 tabstop=4: -->
+<!--
+ Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+
+ This program and the accompanying materials are made available under the
+ terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ and is available at http://www.eclipse.org/legal/epl-v10.html
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <parent>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>common-parent</artifactId>
+ <version>0.6.2-SNAPSHOT</version>
+ </parent>
+ <packaging>bundle</packaging>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>util</artifactId>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.github.romix</groupId>
+ <artifactId>java-concurrent-hash-trie-map</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ <configuration>
+ <instructions>
+ <Export-Package>org.opendaylight.yangtools.util</Export-Package>
+ <Embed-Dependency>java-concurrent-hash-trie-map;inline=true</Embed-Dependency>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.util;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Iterables;
+import com.romix.scala.collection.concurrent.TrieMap;
+
+/*
+ * A simple layer on top of maps, which performs snapshot mediation and optimization of
+ * what the underlying implementation is.
+ */
+public final class MapAdaptor {
+ public static final int DEFAULT_COPY_MAX_ITEMS = 100;
+ public static final String COPY_MAX_ITEMS_MAX_PROP = "org.opendaylight.yangtools.util.mapadaptor.maxcopy";
+
+ public static final int DEFAULT_PERSIST_MIN_ITEMS = 50;
+ public static final String PERSIST_MIN_ITEMS_PROP = "org.opendaylight.yangtools.util.mapadaptor.minpersist";
+
+ private static final Logger LOG = LoggerFactory.getLogger(MapAdaptor.class);
+ private static final MapAdaptor DEFAULT_INSTANCE;
+
+ private final boolean useSingleton;
+ private final int persistMinItems;
+ private final int copyMaxItems;
+
+ static {
+ DEFAULT_INSTANCE = new MapAdaptor(true,
+ getProperty(COPY_MAX_ITEMS_MAX_PROP, DEFAULT_COPY_MAX_ITEMS),
+ getProperty(PERSIST_MIN_ITEMS_PROP, DEFAULT_PERSIST_MIN_ITEMS));
+ LOG.debug("Configured HashMap/TrieMap cutoff at {}/{} entries",
+ DEFAULT_INSTANCE.persistMinItems, DEFAULT_INSTANCE.copyMaxItems);
+ }
+
+ private static final int getProperty(final String name, final int defaultValue) {
+ try {
+ final String p = System.getProperty(name);
+ if (p != null) {
+ try {
+ int pi = Integer.valueOf(p);
+ if (pi <= 0) {
+ LOG.warn("Ignoring illegal value of {}: has to be a positive number", name);
+ } else {
+ return pi;
+ }
+ } catch (NumberFormatException e) {
+ LOG.warn("Ignoring non-numerical value of {}", name, e);
+ }
+ }
+ } catch (Exception e) {
+ LOG.debug("Failed to get {}", name, e);
+ }
+ return defaultValue;
+ }
+
+ private MapAdaptor(final boolean useSingleton, final int copyMaxItems, final int persistMinItems) {
+ this.useSingleton = useSingleton;
+ this.copyMaxItems = copyMaxItems;
+ this.persistMinItems = persistMinItems;
+ }
+
+ /**
+ * Return the default-configured instance.
+ *
+ * @return the singleton global instance
+ */
+ public static MapAdaptor getDefaultInstance() {
+ return DEFAULT_INSTANCE;
+ }
+
+ public static MapAdaptor getInstance(final boolean useSingleton, final int copyMaxItems, final int persistMinItems) {
+ Preconditions.checkArgument(copyMaxItems >= 0, "copyMaxItems has to be a non-negative integer");
+ Preconditions.checkArgument(persistMinItems >= 0, "persistMinItems has to be a positive integer");
+ Preconditions.checkArgument(persistMinItems <= copyMaxItems, "persistMinItems must be less than or equal to copyMaxItems");
+ return new MapAdaptor(useSingleton, copyMaxItems, persistMinItems);
+ }
+
+ /**
+ * Input is treated is supposed to be left unmodified, result must be mutable.
+ *
+ * @param input
+ * @return
+ */
+ public <K, V> Map<K, V> takeSnapshot(final Map<K, V> input) {
+ if (input instanceof ReadOnlyTrieMap) {
+ return ((ReadOnlyTrieMap<K, V>)input).toReadWrite();
+ }
+
+ LOG.trace("Converting input {} to a HashMap", input);
+
+ // FIXME: be a bit smart about allocation based on observed size
+
+ final Map<K, V> ret = new HashMap<>(input);
+ LOG.trace("Read-write HashMap is {}", ret);
+ return ret;
+ }
+
+ /**
+ * Input will be thrown away, result will be retained for read-only access or
+ * {@link #takeSnapshot(Map)} purposes.
+ *
+ * @param input
+ * @return
+ */
+ public <K, V> Map<K, V> optimize(final Map<K, V> input) {
+ if (input instanceof ReadOnlyTrieMap) {
+ LOG.warn("Optimizing read-only map {}", input);
+ }
+
+ final int size = input.size();
+
+ /*
+ * No-brainer :)
+ */
+ if (size == 0) {
+ LOG.trace("Reducing input {} to an empty map", input);
+ return Collections.<K, V>emptyMap();
+ }
+
+ /*
+ * We retain the persistent map as long as it holds at least
+ * persistMinItems
+ */
+ if (input instanceof ReadWriteTrieMap && size >= persistMinItems) {
+ return ((ReadWriteTrieMap<K, V>)input).toReadOnly();
+ }
+
+ /*
+ * If the user opted to use singleton maps, use them. Except for the case
+ * when persistMinItems dictates we should not move off of the persistent
+ * map.
+ */
+ if (useSingleton && size == 1) {
+ final Entry<K, V> e = Iterables.getOnlyElement(input.entrySet());
+ final Map<K, V> ret = Collections.singletonMap(e.getKey(), e.getValue());
+ LOG.trace("Reducing input () to singleton map {}", input, ret);
+ return ret;
+ }
+
+ if (size <= copyMaxItems) {
+ /*
+ * Favor access speed: use a HashMap and copy it on modification.
+ */
+ if (input instanceof HashMap) {
+ return input;
+ }
+
+ LOG.trace("Copying input {} to a HashMap ({} entries)", input, size);
+ final Map<K, V> ret = new HashMap<>(input);
+ LOG.trace("Read-only HashMap is {}", ret);
+ return ret;
+ }
+
+ /*
+ * Favor isolation speed: use a TrieMap and perform snapshots
+ *
+ * This one is a bit tricky, as the TrieMap is concurrent and does not
+ * keep an uptodate size. Updating it requires a full walk -- which is
+ * O(N) and we want to avoid that. So we wrap it in an interceptor,
+ * which will maintain the size for us.
+ */
+ LOG.trace("Copying input {} to a TrieMap ({} entries)", input, size);
+ final TrieMap<K, V> map = TrieMap.empty();
+ map.putAll(input);
+ final Map<K, V> ret = new ReadOnlyTrieMap<>(map, size);
+ LOG.trace("Read-only TrieMap is {}", ret);
+ return ret;
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.util;
+
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ForwardingMap;
+import com.romix.scala.collection.concurrent.TrieMap;
+
+/**
+ * A read-only facade in front of a TrieMap. This is what we give out from
+ * MapAdaptor.optimize(). The idea is that we want our read-only users to
+ * share a single snapshot. That snapshot is instantiated lazily either on
+ * first access. Since we never leak the TrieMap and track its size as it
+ * changes, we can cache it for future reference.
+ */
+final class ReadOnlyTrieMap<K, V> extends ForwardingMap<K, V> {
+ private static final Logger LOG = LoggerFactory.getLogger(ReadOnlyTrieMap.class);
+ private final TrieMap<K, V> readWrite;
+ private final int size;
+ private TrieMap<K, V> readOnly;
+
+ ReadOnlyTrieMap(final TrieMap<K, V> map, final int size) {
+ super();
+ this.readWrite = Preconditions.checkNotNull(map);
+ this.size = size;
+ }
+
+ Map<K, V> toReadWrite() {
+ final Map<K, V> ret = new ReadWriteTrieMap<>(readWrite.snapshot(), size);
+ LOG.trace("Converted read-only TrieMap {} to read-write {}", this, ret);
+ return ret;
+ }
+
+ @Override
+ protected Map<K, V> delegate() {
+ if (readOnly == null) {
+ synchronized (this) {
+ if (readOnly == null) {
+ readOnly = readWrite.readOnlySnapshot();
+ }
+ }
+ }
+
+ return readOnly;
+ }
+
+ @Override
+ public int size() {
+ return size;
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.util;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.romix.scala.collection.concurrent.TrieMap;
+
+/**
+ * A TrieMap facade tracking modifications. Since we change structures based on
+ * their size, and determining the size of a TrieMap is expensive, we make sure
+ * to update it as we go.
+ *
+ * FIXME: this map does not support modification view the keySet()/values()/entrySet()
+ * methods.
+ *
+ * @param <K> Key type
+ * @param <V> Value type
+ */
+final class ReadWriteTrieMap<K, V> implements Map<K, V> {
+ private static final Logger LOG = LoggerFactory.getLogger(ReadOnlyTrieMap.class);
+ private final TrieMap<K, V> delegate;
+ private int size;
+
+ ReadWriteTrieMap(final TrieMap<K, V> delegate, final int size) {
+ this.delegate = Preconditions.checkNotNull(delegate);
+ this.size = size;
+ }
+
+ Map<K, V> toReadOnly() {
+ final Map<K, V> ret = new ReadOnlyTrieMap<>(delegate, size);
+ LOG.trace("Converted read-write TrieMap {} to read-only {}", this, ret);
+ return ret;
+ }
+
+ @Override
+ public int size() {
+ return size;
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return size == 0;
+ }
+
+ @Override
+ public boolean containsKey(final Object key) {
+ return delegate.containsKey(key);
+ }
+
+ @Override
+ public boolean containsValue(final Object value) {
+ return delegate.containsValue(value);
+ }
+
+ @Override
+ public V get(final Object key) {
+ return delegate.get(key);
+ }
+
+ @Override
+ public V put(final K key, final V value) {
+ final V ret = delegate.put(key, value);
+ if (ret == null) {
+ size++;
+ }
+ return ret;
+ }
+
+ @Override
+ public V remove(final Object key) {
+ final V ret = delegate.remove(key);
+ if (ret != null) {
+ size--;
+ }
+ return ret;
+ }
+
+ @Override
+ public void putAll(final Map<? extends K, ? extends V> m) {
+ for (Entry<? extends K, ? extends V> e : m.entrySet()) {
+ put(e.getKey(), e.getValue());
+ }
+ }
+
+ @Override
+ public void clear() {
+ delegate.clear();
+ size = 0;
+ }
+
+ @Override
+ public Set<K> keySet() {
+ return Collections.unmodifiableSet(delegate.keySet());
+ }
+
+ @Override
+ public Collection<V> values() {
+ return Collections.unmodifiableCollection(delegate.values());
+ }
+
+ @Override
+ public Set<Entry<K, V>> entrySet() {
+ return Collections.unmodifiableSet(delegate.entrySet());
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ return delegate.equals(o);
+ }
+
+ @Override
+ public int hashCode() {
+ return delegate.hashCode();
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.util;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class MapAdaptorTest {
+ private MapAdaptor adaptor;
+
+ @Before
+ public void setUp() {
+ adaptor = MapAdaptor.getInstance(true, 10, 5);
+ }
+
+ @Test
+ public void testTreeToEmpty() {
+ final Map<String, String> input = new TreeMap<>();
+
+ // Converts the input into a hashmap;
+ final Map<?, ?> snap = adaptor.takeSnapshot(input);
+ assertNotSame(input, snap);
+ assertTrue(snap instanceof HashMap);
+
+ final Map<?, ?> opt1 = adaptor.optimize(input);
+ assertSame(Collections.EMPTY_MAP, opt1);
+
+ final Map<?, ?> opt2 = adaptor.optimize(snap);
+ assertSame(Collections.EMPTY_MAP, opt2);
+ }
+
+ @Test
+ public void testTreeToSingleton() {
+ final Map<String, String> input = new TreeMap<>();
+ input.put("a", "b");
+
+ final Map<?, ?> snap = adaptor.takeSnapshot(input);
+ assertNotSame(input, snap);
+ assertTrue(snap instanceof HashMap);
+ assertEquals(input, snap);
+
+ final Map<?, ?> opt1 = adaptor.optimize(input);
+ assertNotSame(input, opt1);
+ assertEquals(input, opt1);
+ assertEquals(Collections.singletonMap(null, null).getClass(), opt1.getClass());
+ final Map<?, ?> snap1 = adaptor.takeSnapshot(opt1);
+ assertTrue(snap1 instanceof HashMap);
+ assertEquals(input, snap1);
+
+ final Map<?, ?> opt2 = adaptor.optimize(snap);
+ assertNotSame(snap, opt2);
+ assertEquals(input, opt2);
+ assertEquals(Collections.singletonMap(null, null).getClass(), opt2.getClass());
+
+ final Map<?, ?> snap2 = adaptor.takeSnapshot(opt2);
+ assertNotSame(opt2, snap2);
+ assertTrue(snap2 instanceof HashMap);
+ assertEquals(input, snap2);
+ }
+
+ @Test
+ public void testTreeToTrie() {
+ final Map<String, String> input = new TreeMap<>();
+ for (char c = 'a'; c <= 'z'; ++c) {
+ final String s = String.valueOf(c);
+ input.put(s, s);
+ }
+
+ final Map<String, String> snap = adaptor.takeSnapshot(input);
+ assertTrue(snap instanceof HashMap);
+ assertEquals(input, snap);
+
+ final Map<String, String> opt1 = adaptor.optimize(input);
+ assertEquals(input, opt1);
+ assertEquals(ReadOnlyTrieMap.class, opt1.getClass());
+
+ final Map<String, String> snap2 = adaptor.takeSnapshot(opt1);
+ assertTrue(snap2 instanceof ReadWriteTrieMap);
+ assertEquals(opt1, snap2);
+ assertEquals(26, snap2.size());
+
+ // snap2 and snap3 are independent
+ final Map<String, String> snap3 = adaptor.takeSnapshot(opt1);
+
+ snap2.remove("a");
+ assertEquals(25, snap2.size());
+ assertEquals(26, snap3.size());
+
+ snap3.remove("b");
+ snap3.remove("c");
+ assertEquals(25, snap2.size());
+ assertEquals(24, snap3.size());
+
+ snap2.put("foo", "foo");
+ snap2.put("bar", "baz");
+ snap3.put("bar", "baz");
+ assertEquals(27, snap2.size());
+ assertEquals(25, snap3.size());
+ }
+
+ @Test
+ public void testTrieToHash() {
+ final Map<String, String> input = new TreeMap<>();
+ for (char c = 'a'; c <= 'k'; ++c) {
+ final String s = String.valueOf(c);
+ input.put(s, s);
+ }
+
+ // Translated to read-only
+ final Map<String, String> opt1 = adaptor.optimize(input);
+ assertEquals(input, opt1);
+ assertEquals(ReadOnlyTrieMap.class, opt1.getClass());
+ assertEquals(11, opt1.size());
+
+ // 11 elements -- should retain TrieMap
+ final Map<String, String> snap1 = adaptor.takeSnapshot(opt1);
+ assertEquals(ReadWriteTrieMap.class, snap1.getClass());
+ assertEquals(11, snap1.size());
+
+ for (char c = 'e'; c <= 'k'; ++c) {
+ final String s = String.valueOf(c);
+ snap1.remove(s);
+ }
+
+ // 4 elements: should revert to HashMap
+ assertEquals(4, snap1.size());
+
+ final Map<String, String> opt2 = adaptor.optimize(snap1);
+ assertEquals(snap1, opt2);
+ assertEquals(HashMap.class, opt2.getClass());
+ assertEquals(4, opt2.size());
+ }
+}
assertNotNull(schemaContext);
assertTrue(schemaContext.isPresent());
- mappingService = new RuntimeGeneratedMappingServiceImpl(moduleInfoContext);
- mappingService.setPool(ClassPool.getDefault());
- mappingService.init();
+ mappingService = new RuntimeGeneratedMappingServiceImpl(ClassPool.getDefault(), moduleInfoContext);
mappingService.onGlobalContextUpdated(schemaContext.get());
}
<groovy.version>2.1.6</groovy.version>
<mockito.version>1.9.5</mockito.version>
<javassist.version>3.17.1-GA</javassist.version>
+ <ctrie.version>0.2.0</ctrie.version>
</properties>
<scm>
<artifactId>jsr305</artifactId>
<version>2.0.3</version>
</dependency>
+ <dependency>
+ <groupId>com.github.romix</groupId>
+ <artifactId>java-concurrent-hash-trie-map</artifactId>
+ <version>${ctrie.version}</version>
+ </dependency>
<!-- Plugin integration -->
<dependency>
<artifactId>object-cache-noop</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>util</artifactId>
+ <version>${project.version}</version>
+ </dependency>
</dependencies>
</dependencyManagement>
@Before
public void setupRestconfClientContext() throws MalformedURLException, UnsupportedProtocolException {
- mappingService = new RuntimeGeneratedMappingServiceImpl();
- mappingService.setPool(new ClassPool());
- mappingService.init();
+ mappingService = new RuntimeGeneratedMappingServiceImpl(new ClassPool());
final ModuleInfoBackedContext moduleInfo = ModuleInfoBackedContext.create();
moduleInfo.addModuleInfos(BindingReflections.loadModuleInfos());
@Before
public void setup() {
- this.mappingService = new RuntimeGeneratedMappingServiceImpl();
- this.mappingService.setPool(new ClassPool());
- this.mappingService.init();
+ this.mappingService = new RuntimeGeneratedMappingServiceImpl(new ClassPool());
final ModuleInfoBackedContext moduleInfo = ModuleInfoBackedContext.create();
moduleInfo.addModuleInfos(BindingReflections.loadModuleInfos());
public static final String QNAME_STATIC_FIELD_NAME = "QNAME";
public static final String PACKAGE_PREFIX = "org.opendaylight.yang.gen.v1";
- private static final Splitter SPACE_SPLITTER = Splitter.on(" ").omitEmptyStrings().trimResults();
+ private static final Splitter SPACE_SPLITTER = Splitter.on(' ').omitEmptyStrings().trimResults();
public static final String MODULE_INFO_CLASS_NAME = "$YangModuleInfoImpl";
public static final String MODEL_BINDING_PROVIDER_CLASS_NAME = "$YangModelBindingProvider";
* same local name, but from different schemas.
*
* <ul>
- * <li><b>XMLNamespace</b> - the namespace assigned to the YANG module which
+ * <li><b>XMLNamespace</b> - {@link #getNamespace()} - the namespace assigned to the YANG module which
* defined element, type, procedure or notification.</li>
- * <li><b>Revision</b> - the revision of the YANG module which describes the
+ * <li><b>Revision</b> - {@link #getRevision()} - the revision of the YANG module which describes the
* element</li>
- * <li><b>LocalName</b> - the YANG schema identifier which were defined for this
+ * <li><b>LocalName</b> - {@link #getLocalName()} - the YANG schema identifier which were defined for this
* node in the YANG module</li>
* </ul>
*
+ * QName may also have <code>prefix</code> assigned, but prefix does not
+ * affect equality and identity of two QNames and carry only information
+ * which may be useful for serializers / deserializers.
+ *
*
*/
public final class QName implements Immutable, Serializable, Comparable<QName> {
static final String QNAME_LEFT_PARENTHESIS = "(";
static final String QNAME_RIGHT_PARENTHESIS = ")";
- private static final Pattern QNAME_PATTERN_FULL = Pattern.compile(
- "^\\((.+)\\" + QNAME_REVISION_DELIMITER + "(.+)\\)(.+)$");
- private static final Pattern QNAME_PATTERN_NO_REVISION = Pattern.compile(
- "^\\((.+)\\)(.+)$");
- private static final Pattern QNAME_PATTERN_NO_NAMESPACE_NO_REVISION = Pattern.compile(
- "^(.+)$");
+ private static final Pattern QNAME_PATTERN_FULL = Pattern.compile("^\\((.+)\\" + QNAME_REVISION_DELIMITER
+ + "(.+)\\)(.+)$");
+ private static final Pattern QNAME_PATTERN_NO_REVISION = Pattern.compile("^\\((.+)\\)(.+)$");
+ private static final Pattern QNAME_PATTERN_NO_NAMESPACE_NO_REVISION = Pattern.compile("^(.+)$");
- private static final char[] ILLEGAL_CHARACTERS = new char[] {'?', '(', ')', '&'};
+ private static final char[] ILLEGAL_CHARACTERS = new char[] { '?', '(', ')', '&' };
- //Mandatory
+ // Mandatory
private final QNameModule module;
- //Mandatory
+ // Mandatory
private final String localName;
- //Nullable
+ // Nullable
private final String prefix;
+ private QName(final QNameModule module, final String prefix, final String localName) {
+ this.localName = checkLocalName(localName);
+ this.prefix = prefix;
+ this.module = module;
+ }
+
/**
* QName Constructor.
*
* locally defined prefix assigned to local name
* @param localName
* YANG schema identifier
+ *
*/
public QName(final URI namespace, final Date revision, final String prefix, final String localName) {
- this.localName = checkLocalName(localName);
- this.prefix = prefix;
- this.module = QNameModule.create(namespace, revision);
+ this(QNameModule.create(namespace, revision), prefix, localName);
}
/**
throw new IllegalArgumentException("Parameter 'localName' must be a non-empty string.");
}
- for (char c: ILLEGAL_CHARACTERS) {
+ for (char c : ILLEGAL_CHARACTERS) {
if (localName.indexOf(c) != -1) {
throw new IllegalArgumentException(String.format(
- "Parameter 'localName':'%s' contains illegal character '%s'",
- localName, c));
+ "Parameter 'localName':'%s' contains illegal character '%s'", localName, c));
}
}
return localName;
* the revision of the YANG module
* @param localName
* YANG schema identifier
+ *
+ * @deprecated Use {@link #create(URI, Date, String)} instead.
*/
+ @Deprecated
public QName(final URI namespace, final Date revision, final String localName) {
- this(namespace, revision, null, localName);
+ this(QNameModule.create(namespace, revision), null, localName);
}
+ /**
+ * Construct new QName which reuses namespace, revision and prefix from
+ * base.
+ *
+ * @param base
+ * @param localName
+ * @deprecated Use {@link #create(QName, String)} instead.
+ */
+ @Deprecated
public QName(final QName base, final String localName) {
this(base.getNamespace(), base.getRevision(), base.getPrefix(), localName);
}
/**
- * @deprecated Use {@link #create(String)} instead.
- * This implementation is broken.
+ * @deprecated Use {@link #create(String)} instead. This implementation is
+ * broken.
*/
@Deprecated
public QName(final String input) throws ParseException {
matcher = QNAME_PATTERN_NO_NAMESPACE_NO_REVISION.matcher(input);
if (matcher.matches()) {
String localName = matcher.group(1);
- return new QName((URI)null, localName);
+ return new QName((URI) null, localName);
}
throw new IllegalArgumentException("Invalid input:" + input);
}
return result;
}
+ /**
+ *
+ * Compares the specified object with this list for equality. Returns
+ * <tt>true</tt> if and only if the specified object is also instance of
+ * {@link QName} and its {@link #getLocalName()}, {@link #getNamespace()} and
+ * {@link #getRevision()} are equals to same properties of this instance.
+ *
+ * @param o the object to be compared for equality with this QName
+ * @return <tt>true</tt> if the specified object is equal to this QName
+ *
+ */
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
- public static QName create(final QName base, final String localName){
+ public static QName create(final QName base, final String localName) {
return new QName(base, localName);
}
- public static QName create(final URI namespace, final Date revision, final String localName){
- return new QName(namespace, revision, localName);
+ /**
+ *
+ * Creates new QName.
+ *
+ * @param namespace Namespace of QName or null if namespace is undefined.
+ * @param revision Revision of namespace or null if revision is unspecified.
+ * @param localName Local name part of QName. MUST NOT BE null.
+ * @return Instance of QName
+ */
+ public static QName create(final URI namespace, final Date revision, final String localName) {
+ return new QName(QNameModule.create(namespace, revision), null,localName);
}
-
- public static QName create(final String namespace, final String revision, final String localName) throws IllegalArgumentException{
+ /**
+ *
+ * Creates new QName.
+ *
+ * @param namespace
+ * Namespace of QName, MUST NOT BE Null.
+ * @param revision
+ * Revision of namespace / YANG module. MUST NOT BE null, MUST BE
+ * in format <code>YYYY-mm-dd</code>.
+ * @param localName
+ * Local name part of QName. MUST NOT BE null.
+ * @return
+ * @throws NullPointerException
+ * If any of paramaters is null.
+ * @throws IllegalArgumentException
+ * If <code>namespace</code> is not valid URI or
+ * <code>revision</code> is not according to format
+ * <code>YYYY-mm-dd</code>.
+ */
+ public static QName create(final String namespace, final String revision, final String localName)
+ throws IllegalArgumentException {
final URI namespaceUri;
try {
namespaceUri = new URI(namespace);
- } catch (URISyntaxException ue) {
+ } catch (URISyntaxException ue) {
throw new IllegalArgumentException(String.format("Namespace '%s' is not a valid URI", namespace), ue);
}
return sb.toString();
}
+ /**
+ * Return string representation of revision in format
+ * <code>YYYY-mm-dd</code>
+ *
+ * YANG Specification defines format for <code>revision</code> as
+ * YYYY-mm-dd. This format for revision is reused accross multiple places
+ * such as capabilities URI, YANG modules, etc.
+ *
+ * @return String representation of revision or null, if revision is not
+ * set.
+ */
public String getFormattedRevision() {
return module.getFormattedRevision();
}
+ /**
+ * Creates copy of this with revision and prefix unset.
+ *
+ * @return copy of this QName with revision and prefix unset.
+ */
public QName withoutRevision() {
return QName.create(getNamespace(), null, localName);
}
public static Date parseRevision(final String formatedDate) {
try {
return getRevisionFormat().parse(formatedDate);
- } catch (ParseException| RuntimeException e) {
- throw new IllegalArgumentException(String.format("Revision '%s'is not in a supported format", formatedDate), e);
+ } catch (ParseException | RuntimeException e) {
+ throw new IllegalArgumentException(
+ String.format("Revision '%s'is not in a supported format", formatedDate), e);
}
}
+ /**
+ * Formats {@link Date} representing revision to format
+ * <code>YYYY-mm-dd</code>
+ *
+ * YANG Specification defines format for <code>revision</code> as
+ * YYYY-mm-dd. This format for revision is reused accross multiple places
+ * such as capabilities URI, YANG modules, etc.
+ *
+ * @param revision
+ * Date object to format or null
+ * @return String representation or null if the input was null.
+ */
public static String formattedRevision(final Date revision) {
- if(revision == null) {
+ if (revision == null) {
return null;
}
return getRevisionFormat().format(revision);
}
+ /**
+ *
+ * Compares this QName to other, without comparing revision.
+ *
+ * Compares instance of this to other instance of QName and returns true if
+ * both instances have equal <code>localName</code> ({@link #getLocalName()}
+ * ) and <code>namespace</code> ({@link #getNamespace()}).
+ *
+ * @param other
+ * Other QName. Must not be null.
+ * @return true if this instance and other have equals localName and
+ * namespace.
+ * @throws NullPointerException
+ * if <code>other</code> is null.
+ */
public boolean isEqualWithoutRevision(final QName other) {
return localName.equals(other.getLocalName()) && Objects.equals(getNamespace(), other.getNamespace());
}
*/
package org.opendaylight.yangtools.yang.common;
+/**
+ *
+ * Representation of Error in YANG enabled system.
+ *
+ * Which may be send / received by YANG modeled / enabled systems.
+ *
+ */
public interface RpcError {
+
+ /**
+ *
+ * Returns error severity, as determined by component reporting the error.
+ *
+ * @return error severity
+ */
ErrorSeverity getSeverity();
+ /**
+ *
+ * Returns a string identifying the error condition.
+ *
+ * @return string identifying the error condition.
+ */
String getTag();
+ /**
+ *
+ * Returns a string identifying the data-model-specific or
+ * implementation-specific error condition, if one exists. This element will
+ * not be present if no appropriate application error-tag can be associated
+ * with a particular error condition. If a data-model-specific and an
+ * implementation-specific error-app-tag both exist, then the
+ * data-model-specific value MUST be used by the reporter.
+ *
+ * @return Returns a string identifying the data-model-specific or
+ * implementation-specific error condition, or null if does not
+ * exists.
+ */
String getApplicationTag();
+ /**
+ *
+ * Returns a string suitable for human display that describes the error
+ * condition. This element will not be present if no appropriate message is
+ * provided for a particular error condition.
+ *
+ * @return returns an error description for human display.
+ */
String getMessage();
+ /**
+ *
+ * Contains protocol- or data-model-specific error content. This value may
+ * be not be present if no such error content is provided for a particular
+ * error condition.
+ *
+ * The list in Appendix A defines any mandatory error-info content for each
+ * error. After any protocol-mandated content, a data model definition MAY
+ * mandate that certain application-layer error information be included in
+ * the error-info container.
+ *
+ * An implementation MAY include additional information to provide extended
+ * and/or implementation- specific debugging information.
+ *
+ * @return
+ */
String getInfo();
-
+
+ /**
+ *
+ * Return a cause if available.
+ *
+ * @return cause of this error, if error was triggered by exception.
+ */
Throwable getCause();
-
+
+ /**
+ * Returns the conceptual layer that on which the error occurred.
+ *
+ * @return the conceptual layer that on which the error occurred.
+ */
ErrorType getErrorType();
public enum ErrorSeverity {
import java.util.Collection;
+/**
+ *
+ * Result of call to YANG enabled system.
+ *
+ *
+ * @param <T> Return type
+ */
public interface RpcResult<T> {
+
+ /**
+ * True if processing of request was successful
+ *
+ * @return true if processing was successful.
+ */
boolean isSuccessful();
+ /**
+ *
+ * Returns result of call or null if no result is available.
+ *
+ * @return result of call or null if no result is available.
+ *
+ */
T getResult();
+ /**
+ *
+ * Returns set of errors and warnings which occured during processing
+ * the request.
+ *
+ * @return
+ */
Collection<RpcError> getErrors();
}
* Returns a list of children as seens in resulting XML serialization
* defined by YANG specification.
*
- *
* @return
+ *
+ * @deprecated Use {@link #getValue()} instead.
*/
@Deprecated
List<Node<?>> getChildren();
</build>
<dependencies>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>util</artifactId>
+ </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>yang-common</artifactId>
*/
public class LazyNodeToNodeMap {
- private Map<Node<?>, Node<?>> node2node = new HashMap<>();
+ private final Map<Node<?>, Node<?>> node2node = new HashMap<>();
private CompositeNode originalRoot;
private MutableCompositeNode mutableRoot;
* @param originalNode
* @return mutable twin
*/
- public Node<?> getMutableEquivalent(Node<?> originalNode) {
+ public Node<?> getMutableEquivalent(final Node<?> originalNode) {
Node<?> mutableNode = node2node.get(originalNode);
if (mutableNode == null) {
addPathMembers(originalNode);
/**
* @param originalNode
*/
- private void addPathMembers(Node<?> originalNode) {
+ private void addPathMembers(final Node<?> originalNode) {
Stack<Node<?>> jobQueue = new Stack<>();
jobQueue.push(originalNode);
while (!jobQueue.isEmpty()) {
mutableEquivalent = nodeMutant;
// tidy up children
- if (nodeMutant.getChildren() == null) {
+ if (nodeMutant.getValue() == null) {
nodeMutant.setValue(new ArrayList<Node<?>>());
}
- for (Node<?> originalChildNode : ((CompositeNode) node2add).getChildren()) {
+ for (Node<?> originalChildNode : ((CompositeNode) node2add).getValue()) {
MutableNode<?> mutableChild = (MutableNode<?>) node2node.get(originalChildNode);
fixChildrenRef(nodeMutant, mutableChild);
}
- if (nodeMutant.getChildren() != null && !nodeMutant.getChildren().isEmpty()) {
+ if (nodeMutant.getValue() != null && !nodeMutant.getValue().isEmpty()) {
nodeMutant.init();
}
* @param nodeMutant
* @param mutableChild
*/
- private static void fixChildrenRef(MutableCompositeNode nodeMutant,
- MutableNode<?> mutableChild) {
+ private static void fixChildrenRef(final MutableCompositeNode nodeMutant,
+ final MutableNode<?> mutableChild) {
if (mutableChild != null) {
- if (!nodeMutant.getChildren().contains(mutableChild)) {
- nodeMutant.getChildren().add(mutableChild);
+ if (!nodeMutant.getValue().contains(mutableChild)) {
+ nodeMutant.getValue().add(mutableChild);
}
CompositeNode parentOfChild = mutableChild.getParent();
if (parentOfChild == null) {
* @param value
* @return simple node modification, based on given qname, value and parent
*/
- public static <T> SimpleNode<T> createImmutableSimpleNode(QName qName,
- CompositeNode parent, T value) {
+ public static <T> SimpleNode<T> createImmutableSimpleNode(final QName qName,
+ final CompositeNode parent, final T value) {
return createImmutableSimpleNode(qName, parent, value, null);
}
* @param original originating node, if available
* @return simple node modification, based on given qname, value and parent
*/
- public static <T> MutableSimpleNode<T> createMutableSimpleNode(QName qName,
- CompositeNode parent, Object value, ModifyAction modifyAction, SimpleNode<T> original) {
+ public static <T> MutableSimpleNode<T> createMutableSimpleNode(final QName qName,
+ final CompositeNode parent, final Object value, final ModifyAction modifyAction, final SimpleNode<T> original) {
@SuppressWarnings("unchecked")
MutableSimpleNodeTOImpl<T> simpleNodeTOImpl =
new MutableSimpleNodeTOImpl<T>(qName, parent, (T) value, modifyAction);
* @param value
* @return composite node modification, based on given qname, value (children), parent and modifyAction
*/
- public static CompositeNode createImmutableCompositeNode(QName qName,
- CompositeNode parent, List<Node<?>> value) {
+ public static CompositeNode createImmutableCompositeNode(final QName qName,
+ final CompositeNode parent, final List<Node<?>> value) {
return createImmutableCompositeNode(qName, parent, value, null);
}
* @param original originating node, if available
* @return composite node modification, based on given qName, value (children), parent and modifyAction
*/
- public static MutableCompositeNode createMutableCompositeNode(QName qName,
- CompositeNode parent, List<Node<?>> valueArg, ModifyAction modifyAction, CompositeNode original) {
+ public static MutableCompositeNode createMutableCompositeNode(final QName qName,
+ final CompositeNode parent, final List<Node<?>> valueArg, final ModifyAction modifyAction, final CompositeNode original) {
List<Node<?>> value = valueArg;
if (value == null) {
value = new ArrayList<>();
* @param modifyAction
* @return simple node modification, based on given qname, value, parent and modifyAction
*/
- public static <T> SimpleNode<T> createImmutableSimpleNode(QName qName,
- CompositeNode parent, T value, ModifyAction modifyAction) {
+ public static <T> SimpleNode<T> createImmutableSimpleNode(final QName qName,
+ final CompositeNode parent, final T value, final ModifyAction modifyAction) {
SimpleNodeTOImpl<T> simpleNodeModTOImpl =
new SimpleNodeTOImpl<T>(qName, parent, value, modifyAction);
return simpleNodeModTOImpl;
* @param modifyAction
* @return composite node modification, based on given qname, value (children), parent and modifyAction
*/
- public static CompositeNode createImmutableCompositeNode(QName qName,
- CompositeNode parent, List<Node<?>> value, ModifyAction modifyAction) {
+ public static CompositeNode createImmutableCompositeNode(final QName qName,
+ final CompositeNode parent, final List<Node<?>> value, final ModifyAction modifyAction) {
CompositeNodeTOImpl compositeNodeModTOImpl =
new CompositeNodeTOImpl(qName, parent, value, modifyAction);
return compositeNodeModTOImpl;
* @return copy of given node, parent and value are the same, but parent
* has no reference to this copy
*/
- public static <T> SimpleNode<T> copyNode(SimpleNode<T> node) {
+ public static <T> SimpleNode<T> copyNode(final SimpleNode<T> node) {
SimpleNode<T> twinNode = createImmutableSimpleNode(
node.getNodeType(), node.getParent(), node.getValue());
return twinNode;
* @return copy of given node, parent and value are the same, but parent
* has no reference to this copy
*/
- public static <T> MutableSimpleNode<T> copyNodeAsMutable(SimpleNode<T> node) {
+ public static <T> MutableSimpleNode<T> copyNodeAsMutable(final SimpleNode<T> node) {
MutableSimpleNode<T> twinNode = createMutableSimpleNode(
node.getNodeType(), node.getParent(), node.getValue(),
node.getModificationAction(), null);
* @return copy of given node, parent and children are the same, but parent and children
* have no reference to this copy
*/
- public static CompositeNode copyNode(CompositeNode node, Node<?>... children) {
+ public static CompositeNode copyNode(final CompositeNode node, final Node<?>... children) {
CompositeNode twinNode = createImmutableCompositeNode(
node.getNodeType(), node.getParent(), Arrays.asList(children), node.getModificationAction());
return twinNode;
* @return copy of given node, parent and children are the same, but parent and children
* have no reference to this copy
*/
- public static CompositeNode copyNode(CompositeNode node) {
- return copyNode(node, node.getChildren().toArray(new Node<?>[0]));
+ public static CompositeNode copyNode(final CompositeNode node) {
+ return copyNode(node, node.getValue().toArray(new Node<?>[0]));
}
/**
* will be stored
* @return copy of given node and all subnodes recursively
*/
- public static MutableCompositeNode copyDeepAsMutable(CompositeNode node,
- Map<Node<?>, Node<?>> originalToCopyArg) {
+ public static MutableCompositeNode copyDeepAsMutable(final CompositeNode node,
+ final Map<Node<?>, Node<?>> originalToCopyArg) {
Map<Node<?>, Node<?>> originalToCopy = originalToCopyArg;
if (originalToCopy == null) {
MutableCompositeNode mutableNode = job.getValue();
mutableNode.setValue(new ArrayList<Node<?>>());
- for (Node<?> child : originalNode.getChildren()) {
+ for (Node<?> child : originalNode.getValue()) {
Node<?> mutableAscendant = null;
if (child instanceof CompositeNode) {
MutableCompositeNode newMutable =
+child.getClass().getName());
}
- mutableNode.getChildren().add(mutableAscendant);
+ mutableNode.getValue().add(mutableAscendant);
originalToCopy.put(child, mutableAscendant);
}
mutableNode.init();
* will be stored
* @return copy of given node and all subnodes recursively
*/
- public static CompositeNode copyDeepAsImmutable(CompositeNode node,
- Map<Node<?>, Node<?>> originalToCopyArg) {
+ public static CompositeNode copyDeepAsImmutable(final CompositeNode node,
+ final Map<Node<?>, Node<?>> originalToCopyArg) {
Stack<CompositeNode> jobQueue = new Stack<>();
jobQueue.push(node);
while (!jobQueue.isEmpty()) {
CompositeNode jobNode = jobQueue.peek();
if (!originalToCopy.isEmpty()
- && originalToCopy.keySet().containsAll(jobNode.getChildren())) {
+ && originalToCopy.keySet().containsAll(jobNode.getValue())) {
jobQueue.pop();
- List<Node<?>> newChildren = NodeUtils.collectMapValues(jobNode.getChildren(), originalToCopy);
+ List<Node<?>> newChildren = NodeUtils.collectMapValues(jobNode.getValue(), originalToCopy);
CompositeNode nodeCopy = createImmutableCompositeNode(jobNode.getNodeType(), null,
newChildren, jobNode.getModificationAction());
NodeUtils.fixChildrenRelation(nodeCopy);
originalToCopy.put(jobNode, nodeCopy);
} else {
- for (Node<?> child : jobNode.getChildren()) {
+ for (Node<?> child : jobNode.getValue()) {
if (child instanceof SimpleNode<?>) {
originalToCopy.put(child, createImmutableSimpleNode(
child.getNodeType(), null, child.getValue(),
/**
* @author michal.rehak
- *
+ *
*/
public class NodeModificationBuilderImpl implements NodeModificationBuilder {
- private SchemaContext context;
+ private final SchemaContext context;
- private Set<MutableNode<?>> changeLog;
- private LazyNodeToNodeMap originalToMutable;
+ private final Set<MutableNode<?>> changeLog;
+ private final LazyNodeToNodeMap originalToMutable;
/**
* @param context
*/
- public NodeModificationBuilderImpl(SchemaContext context) {
+ public NodeModificationBuilderImpl(final SchemaContext context) {
this.context = context;
originalToMutable = new LazyNodeToNodeMap();
changeLog = new HashSet<>();
* @param modNode
* @param action
*/
- private void addModificationToLog(MutableNode<?> modNode, ModifyAction action) {
+ private void addModificationToLog(final MutableNode<?> modNode, final ModifyAction action) {
modNode.setModifyAction(action);
changeLog.add(modNode);
}
@Override
- public void addNode(MutableSimpleNode<?> newNode) {
+ public void addNode(final MutableSimpleNode<?> newNode) {
NodeUtils.fixParentRelation(newNode);
addModificationToLog(newNode, ModifyAction.CREATE);
}
@Override
- public void addNode(MutableCompositeNode newNode) {
+ public void addNode(final MutableCompositeNode newNode) {
NodeUtils.fixParentRelation(newNode);
addModificationToLog(newNode, ModifyAction.CREATE);
}
@Override
- public void replaceNode(MutableSimpleNode<?> replacementNode) {
+ public void replaceNode(final MutableSimpleNode<?> replacementNode) {
addModificationToLog(replacementNode, ModifyAction.REPLACE);
}
@Override
- public void replaceNode(MutableCompositeNode replacementNode) {
+ public void replaceNode(final MutableCompositeNode replacementNode) {
addModificationToLog(replacementNode, ModifyAction.REPLACE);
}
@Override
- public void deleteNode(MutableCompositeNode deadNode) {
+ public void deleteNode(final MutableCompositeNode deadNode) {
addModificationToLog(deadNode, ModifyAction.DELETE);
}
@Override
- public void deleteNode(MutableSimpleNode<?> deadNode) {
+ public void deleteNode(final MutableSimpleNode<?> deadNode) {
addModificationToLog(deadNode, ModifyAction.DELETE);
}
@Override
- public void removeNode(MutableSimpleNode<?> deadNode) {
+ public void removeNode(final MutableSimpleNode<?> deadNode) {
addModificationToLog(deadNode, ModifyAction.REMOVE);
}
@Override
- public void removeNode(MutableCompositeNode deadNode) {
+ public void removeNode(final MutableCompositeNode deadNode) {
addModificationToLog(deadNode, ModifyAction.REMOVE);
}
@Override
- public void mergeNode(MutableCompositeNode alteredNode) {
+ public void mergeNode(final MutableCompositeNode alteredNode) {
addModificationToLog(alteredNode, ModifyAction.MERGE);
}
// try to add key subnode to wanted list
List<QName> supportedKeys = listSchema.getKeyDefinition();
CompositeNode outlawOriginal = ((MutableCompositeNode) outlaw).getOriginal();
- for (Node<?> outlawOriginalChild : outlawOriginal.getChildren()) {
+ for (Node<?> outlawOriginalChild : outlawOriginal.getValue()) {
if (supportedKeys.contains(outlawOriginalChild.getNodeType())) {
originalToMutable.getMutableEquivalent(outlawOriginalChild);
}
* @param focusedDescendant
* @return set of parents and focusedAncestor itself
*/
- private static Set<Node<?>> collectSelfAndAllParents(Node<?> focusedDescendant) {
+ private static Set<Node<?>> collectSelfAndAllParents(final Node<?> focusedDescendant) {
Set<Node<?>> family = new HashSet<>();
Node<?> tmpNode = focusedDescendant;
while (tmpNode != null) {
* @return mutable version of given node
*/
@Override
- public Node<?> getMutableEquivalent(Node<?> originalNode) {
+ public Node<?> getMutableEquivalent(final Node<?> originalNode) {
return originalToMutable.getMutableEquivalent(originalNode);
}
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
-import com.google.common.collect.Maps;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.opendaylight.yangtools.yang.data.api.ModifyAction;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
/**
* @author michal.rehak
* @param node
* @return node path up till root node
*/
- public static String buildPath(Node<?> node) {
+ public static String buildPath(final Node<?> node) {
List<String> breadCrumbs = new ArrayList<>();
Node<?> tmpNode = node;
while (tmpNode != null) {
* @return dom tree, containing same node structure, yang nodes are
* associated to dom nodes as user data
*/
- public static org.w3c.dom.Document buildShadowDomTree(CompositeNode treeRootNode) {
+ public static org.w3c.dom.Document buildShadowDomTree(final CompositeNode treeRootNode) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
org.w3c.dom.Document doc = null;
try {
jointPlace.appendChild(itemEl);
if (item instanceof CompositeNode) {
- for (Node<?> child : ((CompositeNode) item).getChildren()) {
+ for (Node<?> child : ((CompositeNode) item).getValue()) {
jobQueue.push(new SimpleEntry<org.w3c.dom.Node, Node<?>>(itemEl, child));
}
}
* @throws XPathExpressionException
*/
@SuppressWarnings("unchecked")
- public static <T> T findNodeByXpath(org.w3c.dom.Document doc, String xpathEx) throws XPathExpressionException {
+ public static <T> T findNodeByXpath(final org.w3c.dom.Document doc, final String xpathEx) throws XPathExpressionException {
T userNode = null;
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
* @return map of children, where key = qName and value is list of children
* groupped by qName
*/
- public static Map<QName, List<Node<?>>> buildNodeMap(List<Node<?>> value) {
+ public static Map<QName, List<Node<?>>> buildNodeMap(final List<Node<?>> value) {
Map<QName, List<Node<?>>> nodeMapTmp = Maps.newLinkedHashMap();
if (value == null) {
throw new IllegalStateException("nodeList should not be null or empty");
* @param context
* @return map of lists, where key = path; value = {@link DataSchemaNode}
*/
- public static Map<String, ListSchemaNode> buildMapOfListNodes(SchemaContext context) {
+ public static Map<String, ListSchemaNode> buildMapOfListNodes(final SchemaContext context) {
Map<String, ListSchemaNode> mapOfLists = new HashMap<>();
Stack<DataSchemaNode> jobQueue = new Stack<>();
* @param qNamesPath
* @return path
*/
- private static String schemaPathToPath(List<QName> qNamesPath) {
+ private static String schemaPathToPath(final List<QName> qNamesPath) {
List<String> pathSeed = new ArrayList<>();
for (QName qNameItem : qNamesPath) {
pathSeed.add(qNameItem.getLocalName());
*
* @param newNode
*/
- public static void fixParentRelation(Node<?> newNode) {
+ public static void fixParentRelation(final Node<?> newNode) {
if (newNode.getParent() != null) {
- List<Node<?>> siblings = newNode.getParent().getChildren();
+ List<Node<?>> siblings = newNode.getParent().getValue();
if (!siblings.contains(newNode)) {
siblings.add(newNode);
}
*
* @param parentNode
*/
- public static void fixChildrenRelation(CompositeNode parentNode) {
- if (parentNode.getChildren() != null) {
- for (Node<?> child : parentNode.getChildren()) {
+ public static void fixChildrenRelation(final CompositeNode parentNode) {
+ if (parentNode.getValue() != null) {
+ for (Node<?> child : parentNode.getValue()) {
if (child instanceof AbstractNodeTO<?>) {
((AbstractNodeTO<?>) child).setParent(parentNode);
}
* @param dataMap
* @return list of values of map, found by given keys
*/
- public static <T, K> List<K> collectMapValues(List<T> keys, Map<T, K> dataMap) {
+ public static <T, K> List<K> collectMapValues(final List<T> keys, final Map<T, K> dataMap) {
List<K> valueSubList = new ArrayList<>();
for (T key : keys) {
valueSubList.add(dataMap.get(key));
* @param nodes
* @return list of children in list of appropriate type
*/
- public static List<Node<?>> buildChildrenList(Node<?>... nodes) {
+ public static List<Node<?>> buildChildrenList(final Node<?>... nodes) {
return Lists.newArrayList(nodes);
}
* XML as {@link InputStream}. The output of the operation SHOULD be root
* <code>CompositeNode</code> or <code>SimpleElement</code> depends by which
* element XML begins. The XML header is omitted by XML parser.
- *
+ *
* @author Lukas Sedlak
- *
+ *
* @see CompositeNode
* @see SimpleNode
* @see Node
* output of the operation SHOULD be root <code>CompositeNode</code> or
* <code>SimpleElement</code> depends on element that XML document begins.
* The XML header is omitted by XML parser.
- *
+ *
* @param inputStream
* XML Input Stream
* @return root <code>Node</code> element conformant to XML start element in
if (newNode != null) {
processingQueue.push(newNode);
if (compParentNode != null) {
- compParentNode.getChildren().add(newNode);
+ compParentNode.getValue().add(newNode);
}
}
} else if (event.isEndElement()) {
* characters value. If the SimpleNode is composed only by empty XML tag
* (i.e. {@code <emptyTag />} or {@code<emptyTag></emptyTag>}) the result
* will be also <code>true</code>.
- *
+ *
* @param event
* actual XMLEvent that is processed
* @return <code>true</code> only and only if the XMLEvent Start Element is
* Simple element tag and contains character values or is empty XML
* tag.
* @throws XMLStreamException
- *
+ *
* @see SimpleNode
*/
private static boolean isSimpleNodeEvent(final XMLEvent event) throws XMLStreamException {
* contains 1..N XML child elements. (i.e. {@code <compositeNode>
* <simpleNode>data</simpleNode>
* </compositeNode>})
- *
+ *
* @param event
* actual XMLEvent that is processed
* @return <code>true</code> only if XML Element contains 1..N child
* elements, otherwise returns <code>false</code>
* @throws XMLStreamException
- *
+ *
* @see CompositeNode
*/
private static boolean isCompositeNodeEvent(final XMLEvent event) throws XMLStreamException {
/**
* Creates and returns <code>SimpleNode</code> instance from actually
* processed XML Start Element.
- *
+ *
* @param startElement
* actual XML Start Element that is processed
* @param parent
* @return <code>new SimpleNode</code> instance from actually processed XML
* Start Element
* @throws XMLStreamException
- *
+ *
* @see SimpleNode
*/
private static SimpleNode<String> resolveSimpleNodeFromStartElement(final StartElement startElement,
- CompositeNode parent) throws XMLStreamException {
+ final CompositeNode parent) throws XMLStreamException {
checkArgument(startElement != null, "Start Element cannot be NULL!");
String data = null;
/**
* Creates and returns <code>MutableCompositeNode</code> instance from
* actually processed XML Start Element.
- *
+ *
* @param startElement
* actual XML Start Element that is processed
* @param parent
* Parent CompositeNode
* @return <code>new MutableCompositeNode</code> instance from actually
* processed XML Start Element
- *
+ *
* @see CompositeNode
* @see MutableCompositeNode
*/
private static MutableCompositeNode resolveCompositeNodeFromStartElement(final StartElement startElement,
- CompositeNode parent) {
+ final CompositeNode parent) {
checkArgument(startElement != null, "Start Element cannot be NULL!");
return NodeFactory.createMutableCompositeNode(resolveElementQName(startElement), parent,
/**
* Extract and retrieve XML Element QName to OpenDaylight QName.
- *
+ *
* @param element
* Start Element
* @return QName instance composed of <code>elements</code> Namespace and
* Local Part.
- *
+ *
* @see QName
*/
private static QName resolveElementQName(final StartElement element) {
Element element;
SchemaContext schemaContext;
- ElementWithSchemaContext(Element element,SchemaContext schemaContext) {
+ ElementWithSchemaContext(final Element element,final SchemaContext schemaContext) {
this.schemaContext = schemaContext;
this.element = element;
}
private static final XmlCodecProvider DEFAULT_XML_VALUE_CODEC_PROVIDER = new XmlCodecProvider() {
@Override
- public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(TypeDefinition<?> baseType) {
+ public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(final TypeDefinition<?> baseType) {
return TypeDefinitionAwareCodec.from(baseType);
}
};
* @return new instance of XML Document
* @throws UnsupportedDataTypeException
*/
- public static Document toDocument(CompositeNode data, DataNodeContainer schema, XmlCodecProvider codecProvider)
+ public static Document toDocument(final CompositeNode data, final DataNodeContainer schema, final XmlCodecProvider codecProvider)
throws UnsupportedDataTypeException {
Preconditions.checkNotNull(data);
Preconditions.checkNotNull(schema);
* @return new instance of XML Document
* @throws UnsupportedDataTypeException
*/
- public static Document toDocument(CompositeNode data, XmlCodecProvider codecProvider)
+ public static Document toDocument(final CompositeNode data, final XmlCodecProvider codecProvider)
throws UnsupportedDataTypeException {
Preconditions.checkNotNull(data);
return doc;
}
- private static Element createXmlRootElement(Document doc, Node<?> data, SchemaNode schema,
- XmlCodecProvider codecProvider) throws UnsupportedDataTypeException {
+ private static Element createXmlRootElement(final Document doc, final Node<?> data, final SchemaNode schema,
+ final XmlCodecProvider codecProvider) throws UnsupportedDataTypeException {
Element itemEl = createElementFor(doc, data);
if (data instanceof SimpleNode<?>) {
if (schema instanceof LeafListSchemaNode) {
}
}
} else { // CompositeNode
- for (Node<?> child : ((CompositeNode) data).getChildren()) {
+ for (Node<?> child : ((CompositeNode) data).getValue()) {
DataSchemaNode childSchema = null;
if (schema != null) {
childSchema = findFirstSchemaForNode(child, ((DataNodeContainer) schema).getChildNodes());
return itemEl;
}
- public static Element createElementFor(Document doc, Node<?> data) {
+ public static Element createElementFor(final Document doc, final Node<?> data) {
QName dataType = data.getNodeType();
Element ret;
if (dataType.getNamespace() != null) {
return ret;
}
- public static void writeValueByType(Element element, SimpleNode<?> node, TypeDefinition<?> type,
- DataSchemaNode schema, XmlCodecProvider codecProvider) {
+ public static void writeValueByType(final Element element, final SimpleNode<?> node, final TypeDefinition<?> type,
+ final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
Object nodeValue = node.getValue();
writeValueByType(element, type, codecProvider, nodeValue);
}
- public static void writeValueByType(Element element, TypeDefinition<?> type, XmlCodecProvider codecProvider, Object nodeValue) {
+ public static void writeValueByType(final Element element, final TypeDefinition<?> type, final XmlCodecProvider codecProvider, final Object nodeValue) {
TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
if (baseType instanceof IdentityrefTypeDefinition) {
if (nodeValue instanceof QName) {
}
- public final static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
+ public final static TypeDefinition<?> resolveBaseTypeFrom(final TypeDefinition<?> type) {
TypeDefinition<?> superType = type;
while (superType.getBaseType() != null) {
superType = superType.getBaseType();
return superType;
}
- private static final DataSchemaNode findFirstSchemaForNode(Node<?> node, Set<DataSchemaNode> dataSchemaNode) {
+ private static final DataSchemaNode findFirstSchemaForNode(final Node<?> node, final Set<DataSchemaNode> dataSchemaNode) {
if (dataSchemaNode != null && node != null) {
for (DataSchemaNode dsn : dataSchemaNode) {
if (node.getNodeType().getLocalName().equals(dsn.getQName().getLocalName())) {
return null;
}
- public static Node<?> toDomNode(Element xmlElement, Optional<DataSchemaNode> schema,
- Optional<XmlCodecProvider> codecProvider) {
+ public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
+ final Optional<XmlCodecProvider> codecProvider) {
if (schema.isPresent()) {
return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(DEFAULT_XML_VALUE_CODEC_PROVIDER));
}
return toDomNode(xmlElement);
}
- public static CompositeNode fromElement(Element xmlElement) {
+ public static CompositeNode fromElement(final Element xmlElement) {
CompositeNodeBuilder<ImmutableCompositeNode> node = ImmutableCompositeNode.builder();
node.setQName(qNameFromElement(xmlElement));
return node.toInstance();
}
- public static QName qNameFromElement(Element xmlElement) {
+ public static QName qNameFromElement(final Element xmlElement) {
String namespace = xmlElement.getNamespaceURI();
String localName = xmlElement.getLocalName();
return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
}
- private static Node<?> toNodeWithSchema(Element xmlElement, DataSchemaNode schema, XmlCodecProvider codecProvider,SchemaContext schemaCtx) {
+ private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
checkQName(xmlElement, schema.getQName());
if (schema instanceof DataNodeContainer) {
return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider,schemaCtx);
return null;
}
- private static Node<?> toNodeWithSchema(Element xmlElement, DataSchemaNode schema, XmlCodecProvider codecProvider) {
+ private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
return toNodeWithSchema(xmlElement, schema, codecProvider, null);
}
- protected static Node<?> toSimpleNodeWithType(Element xmlElement, LeafSchemaNode schema,
- XmlCodecProvider codecProvider,SchemaContext schemaCtx) {
+ protected static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafSchemaNode schema,
+ final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
TypeDefinitionAwareCodec<? extends Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
String text = xmlElement.getTextContent();
Object value = null;
return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
}
- private static Node<?> toSimpleNodeWithType(Element xmlElement, LeafListSchemaNode schema,
- XmlCodecProvider codecProvider,SchemaContext schemaCtx) {
+ private static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafListSchemaNode schema,
+ final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
TypeDefinitionAwareCodec<? extends Object, ? extends TypeDefinition<?>> codec = codecProvider.codecFor(schema.getType());
String text = xmlElement.getTextContent();
Object value = null;
return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
}
- private static Node<?> toCompositeNodeWithSchema(Element xmlElement, QName qName, DataNodeContainer schema,
- XmlCodecProvider codecProvider,SchemaContext schemaCtx) {
+ private static Node<?> toCompositeNodeWithSchema(final Element xmlElement, final QName qName, final DataNodeContainer schema,
+ final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()),schemaCtx);
Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(URI.create("urn:ietf:params:xml:ns:netconf:base:1.0"), null, "operation");
- public static Optional<ModifyAction> getModifyOperationFromAttributes(Element xmlElement) {
+ public static Optional<ModifyAction> getModifyOperationFromAttributes(final Element xmlElement) {
Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
- if(attributeNodeNS == null)
- return Optional.absent();
+ if(attributeNodeNS == null) {
+ return Optional.absent();
+ }
ModifyAction action = ModifyAction.fromXmlValue(attributeNodeNS.getValue());
Preconditions.checkArgument(action.isOnElementPermitted(), "Unexpected operation %s on %s", action, xmlElement);
return Optional.of(action);
}
- private static void checkQName(Element xmlElement, QName qName) {
+ private static void checkQName(final Element xmlElement, final QName qName) {
checkState(Objects.equal(xmlElement.getNamespaceURI(), qName.getNamespace().toString()));
checkState(qName.getLocalName().equals(xmlElement.getLocalName()));
}
- public static final Optional<DataSchemaNode> findFirstSchema(QName qname, Set<DataSchemaNode> dataSchemaNode) {
+ public static final Optional<DataSchemaNode> findFirstSchema(final QName qname, final Set<DataSchemaNode> dataSchemaNode) {
if (dataSchemaNode != null && !dataSchemaNode.isEmpty() && qname != null) {
for (DataSchemaNode dsn : dataSchemaNode) {
if (qname.isEqualWithoutRevision(dsn.getQName())) {
return Optional.absent();
}
- public static Node<?> toDomNode(Document doc) {
+ public static Node<?> toDomNode(final Document doc) {
return toDomNode(doc.getDocumentElement());
}
- private static Node<?> toDomNode(Element element) {
+ private static Node<?> toDomNode(final Element element) {
QName qname = qNameFromElement(element);
ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
return ImmutableCompositeNode.create(qname, values.build());
}
- public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context,SchemaContext schemaCtx) {
+ public static List<Node<?>> toDomNodes(final Element element, final Optional<Set<DataSchemaNode>> context,final SchemaContext schemaCtx) {
return forEachChild(element.getChildNodes(),schemaCtx, new Function<ElementWithSchemaContext, Optional<Node<?>>>() {
@Override
- public Optional<Node<?>> apply(ElementWithSchemaContext input) {
+ public Optional<Node<?>> apply(final ElementWithSchemaContext input) {
if (context.isPresent()) {
QName partialQName = qNameFromElement(input.getElement());
Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
* Element with equal notification QName defined in XML Document.
*/
public static CompositeNode notificationToDomNodes(final Document document,
- final Optional<Set<NotificationDefinition>> notifications, SchemaContext schemaCtx) {
+ final Optional<Set<NotificationDefinition>> notifications, final SchemaContext schemaCtx) {
if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
for (int i = 0; i < originChildNodes.getLength(); i++) {
return Optional.<NotificationDefinition>absent();
}
- private static final <T> List<T> forEachChild(NodeList nodes, SchemaContext schemaContext, Function<ElementWithSchemaContext, Optional<T>> forBody) {
+ private static final <T> List<T> forEachChild(final NodeList nodes, final SchemaContext schemaContext, final Function<ElementWithSchemaContext, Optional<T>> forBody) {
ImmutableList.Builder<T> ret = ImmutableList.<T> builder();
for (int i = 0; i < nodes.getLength(); i++) {
org.w3c.dom.Node child = nodes.item(i);
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
-import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedAttrNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedValueAttrNode;
public class ImmutableLeafNodeBuilder<T> extends AbstractImmutableNormalizedNodeBuilder<InstanceIdentifier.NodeIdentifier, T, LeafNode<T>> {
return new ImmutableLeafNode<>(getNodeIdentifier(), getValue(), getAttributes());
}
- private static final class ImmutableLeafNode<T> extends AbstractImmutableNormalizedAttrNode<InstanceIdentifier.NodeIdentifier, T> implements LeafNode<T> {
+ private static final class ImmutableLeafNode<T> extends AbstractImmutableNormalizedValueAttrNode<InstanceIdentifier.NodeIdentifier, T> implements LeafNode<T> {
ImmutableLeafNode(final InstanceIdentifier.NodeIdentifier nodeIdentifier, final T value, final Map<QName, String> attributes) {
super(nodeIdentifier, value, attributes);
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedAttrNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedValueAttrNode;
import com.google.common.base.Preconditions;
return new ImmutableLeafSetEntryNode<>(getNodeIdentifier(), getValue(), getAttributes());
}
- private static final class ImmutableLeafSetEntryNode<T> extends AbstractImmutableNormalizedAttrNode<InstanceIdentifier.NodeWithValue, T> implements LeafSetEntryNode<T> {
+ private static final class ImmutableLeafSetEntryNode<T> extends AbstractImmutableNormalizedValueAttrNode<InstanceIdentifier.NodeWithValue, T> implements LeafSetEntryNode<T> {
ImmutableLeafSetEntryNode(final InstanceIdentifier.NodeWithValue nodeIdentifier, final T value, final Map<QName, String> attributes) {
super(nodeIdentifier, value, attributes);
package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
import java.util.Collections;
-import java.util.LinkedHashMap;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.util.MapAdaptor;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedValueNode;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
public class ImmutableLeafSetNodeBuilder<T> implements ListNodeBuilder<T, LeafSetEntryNode<T>> {
- private Map<InstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> value;
+ private final Map<InstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> value;
private InstanceIdentifier.NodeIdentifier nodeIdentifier;
- private boolean dirty;
protected ImmutableLeafSetNodeBuilder() {
- value = new LinkedHashMap<>();
- dirty = false;
+ value = new HashMap<>();
}
protected ImmutableLeafSetNodeBuilder(final ImmutableLeafSetNode<T> node) {
nodeIdentifier = node.getIdentifier();
- value = node.getChildren();
- dirty = true;
+ value = MapAdaptor.getDefaultInstance().takeSnapshot(node.children);
}
public static <T> ListNodeBuilder<T, LeafSetEntryNode<T>> create() {
return new ImmutableLeafSetNodeBuilder<T>((ImmutableLeafSetNode<T>) node);
}
- private void checkDirty() {
- if (dirty) {
- value = new LinkedHashMap<>(value);
- dirty = false;
- }
- }
-
@Override
public ListNodeBuilder<T, LeafSetEntryNode<T>> withChild(final LeafSetEntryNode<T> child) {
- checkDirty();
this.value.put(child.getIdentifier(), child);
return this;
}
@Override
public ListNodeBuilder<T, LeafSetEntryNode<T>> withoutChild(final PathArgument key) {
- checkDirty();
this.value.remove(key);
return this;
}
@Override
public LeafSetNode<T> build() {
- dirty = true;
- return new ImmutableLeafSetNode<>(nodeIdentifier, value);
+ return new ImmutableLeafSetNode<>(nodeIdentifier, MapAdaptor.getDefaultInstance().optimize(value));
}
@Override
@Override
public ListNodeBuilder<T, LeafSetEntryNode<T>> withValue(final List<LeafSetEntryNode<T>> value) {
- checkDirty();
for (final LeafSetEntryNode<T> leafSetEntry : value) {
withChild(leafSetEntry);
}
}
protected final static class ImmutableLeafSetNode<T> extends
- AbstractImmutableNormalizedNode<InstanceIdentifier.NodeIdentifier, Iterable<LeafSetEntryNode<T>>> implements
+ AbstractImmutableNormalizedValueNode<InstanceIdentifier.NodeIdentifier, Iterable<LeafSetEntryNode<T>>> implements
Immutable, LeafSetNode<T> {
private final Map<InstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> children;
return children.hashCode();
}
- private Map<InstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> getChildren() {
- return Collections.unmodifiableMap(children);
- }
-
@Override
protected boolean valueEquals(final AbstractImmutableNormalizedNode<?, ?> other) {
return children.equals(((ImmutableLeafSetNode<?>) other).children);
*/
package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
-import java.util.LinkedHashMap;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.util.MapAdaptor;
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
public class ImmutableMapNodeBuilder
implements CollectionNodeBuilder<MapEntryNode, MapNode> {
- private Map<InstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> value;
+ private final Map<InstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> value;
private InstanceIdentifier.NodeIdentifier nodeIdentifier;
- private boolean dirty = false;
protected ImmutableMapNodeBuilder() {
- this.value = new LinkedHashMap<>();
- this.dirty = false;
+ this.value = new HashMap<>();
}
protected ImmutableMapNodeBuilder(final ImmutableMapNode node) {
this.nodeIdentifier = node.getIdentifier();
- this.value = node.children;
- this.dirty = true;
+ this.value = MapAdaptor.getDefaultInstance().takeSnapshot(node.children);
}
public static CollectionNodeBuilder<MapEntryNode, MapNode> create() {
return new ImmutableMapNodeBuilder((ImmutableMapNode) node);
}
- private void checkDirty() {
- if (dirty) {
- value = new LinkedHashMap<>(value);
- dirty = false;
- }
- }
-
@Override
public CollectionNodeBuilder<MapEntryNode, MapNode> withChild(final MapEntryNode child) {
- checkDirty();
this.value.put(child.getIdentifier(), child);
return this;
}
@Override
public CollectionNodeBuilder<MapEntryNode, MapNode> withoutChild(final InstanceIdentifier.PathArgument key) {
- checkDirty();
this.value.remove(key);
return this;
}
@Override
public MapNode build() {
- dirty = true;
- return new ImmutableMapNode(nodeIdentifier, value);
+ return new ImmutableMapNode(nodeIdentifier, MapAdaptor.getDefaultInstance().optimize(value));
}
@Override
ImmutableMapNode(final InstanceIdentifier.NodeIdentifier nodeIdentifier,
final Map<InstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> children) {
- super(nodeIdentifier, Iterables.unmodifiableIterable(children.values()));
+ super(nodeIdentifier);
this.children = children;
}
return Optional.fromNullable(children.get(child));
}
+ @Override
+ public Iterable<MapEntryNode> getValue() {
+ return Iterables.unmodifiableIterable(children.values());
+ }
+
@Override
protected int valueHashCode() {
return children.hashCode();
ImmutableOrderedLeafSetNode(final InstanceIdentifier.NodeIdentifier nodeIdentifier,
final Map<InstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> children) {
- super(nodeIdentifier, Iterables.unmodifiableIterable(children.values()));
+ super(nodeIdentifier);
this.children = children;
}
// TODO Auto-generated method stub
return 0;
}
+
+ @Override
+ public Iterable<LeafSetEntryNode<T>> getValue() {
+ return Iterables.unmodifiableIterable(children.values());
+ }
}
@Override
ImmutableOrderedMapNode(final InstanceIdentifier.NodeIdentifier nodeIdentifier,
final Map<InstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> children) {
- super(nodeIdentifier, Iterables.unmodifiableIterable(children.values()));
+ super(nodeIdentifier);
this.children = children;
}
public int getSize() {
return children.size();
}
+
+ @Override
+ public Iterable<MapEntryNode> getValue() {
+ return Iterables.unmodifiableIterable(children.values());
+ }
}
}
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedValueNode;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
}
protected static final class ImmutableUnkeyedListNode extends
- AbstractImmutableNormalizedNode<InstanceIdentifier.NodeIdentifier, Iterable<UnkeyedListEntryNode>>
+ AbstractImmutableNormalizedValueNode<InstanceIdentifier.NodeIdentifier, Iterable<UnkeyedListEntryNode>>
implements Immutable, UnkeyedListNode {
private final ImmutableList<UnkeyedListEntryNode> children;
public AbstractImmutableDataContainerNode(
final Map<PathArgument, DataContainerChild<? extends PathArgument, ?>> children, final K nodeIdentifier) {
- super(nodeIdentifier, Iterables.unmodifiableIterable(children.values()));
+ super(nodeIdentifier);
this.children = children;
}
return Optional.<DataContainerChild<? extends PathArgument, ?>> fromNullable(children.get(child));
}
+ @Override
+ public final Iterable<DataContainerChild<? extends PathArgument, ?>> getValue() {
+ return Iterables.unmodifiableIterable(children.values());
+ }
+
@Override
protected int valueHashCode() {
return children.hashCode();
implements NormalizedNode<K, V>, Immutable {
private final K nodeIdentifier;
- private final V value;
- protected AbstractImmutableNormalizedNode(final K nodeIdentifier, final V value) {
+ protected AbstractImmutableNormalizedNode(final K nodeIdentifier) {
this.nodeIdentifier = Preconditions.checkNotNull(nodeIdentifier, "nodeIdentifier");
- this.value = Preconditions.checkNotNull(value, "value");
}
@Override
return getNodeType();
}
- @Override
- public final V getValue() {
- return value;
- }
-
@Override
public final V setValue(final V value) {
throw new UnsupportedOperationException("Immutable");
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.collect.ImmutableMap;
-public abstract class AbstractImmutableNormalizedAttrNode<K extends InstanceIdentifier.PathArgument,V>
- extends AbstractImmutableNormalizedNode<K, V>
+public abstract class AbstractImmutableNormalizedValueAttrNode<K extends InstanceIdentifier.PathArgument,V>
+ extends AbstractImmutableNormalizedValueNode<K, V>
implements AttributesContainer {
private final Map<QName, String> attributes;
- protected AbstractImmutableNormalizedAttrNode(final K nodeIdentifier, final V value, final Map<QName, String> attributes) {
+ protected AbstractImmutableNormalizedValueAttrNode(final K nodeIdentifier, final V value, final Map<QName, String> attributes) {
super(nodeIdentifier, value);
this.attributes = ImmutableMap.copyOf(attributes);
}
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.nodes;
+
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+
+import com.google.common.base.Preconditions;
+
+public abstract class AbstractImmutableNormalizedValueNode<K extends InstanceIdentifier.PathArgument,V>
+ extends AbstractImmutableNormalizedNode<K, V> {
+
+ private final V value;
+
+ protected AbstractImmutableNormalizedValueNode(final K nodeIdentifier, final V value) {
+ super(nodeIdentifier);
+ this.value = Preconditions.checkNotNull(value, "value");
+ }
+
+ @Override
+ public final V getValue() {
+ return value;
+ }
+}
Assert.assertEquals(2, lazyN2N.getKeyNodes().size());
Assert.assertEquals(mutableTree, subMutant.getParent());
- Assert.assertEquals(mutableTree.getChildren().size(), 1);
- Assert.assertEquals(mutableTree.getChildren().iterator().next(), subMutant);
+ Assert.assertEquals(mutableTree.getValue().size(), 1);
+ Assert.assertEquals(mutableTree.getValue().iterator().next(), subMutant);
}
/**
.getLogger(MyNodeBuilder.class);
private URI qnNamespace;
- private String qnPrefix;
- private Date qnRevision;
+ private final String qnPrefix;
+ private final Date qnRevision;
private CompositeNode rootNode;
/**
* @param baseQName
*/
- private MyNodeBuilder(QName baseQName) {
+ private MyNodeBuilder(final QName baseQName) {
qnNamespace = baseQName.getNamespace();
qnPrefix = baseQName.getPrefix();
qnRevision = baseQName.getRevision();
}
@Override
- protected void setParent(Object parent, Object child) {
+ protected void setParent(final Object parent, final Object child) {
// do nothing
if (child instanceof AbstractNodeTO<?>) {
((AbstractNodeTO<?>) child).setParent((CompositeNode) parent);
}
@Override
- protected Object createNode(Object name) {
+ protected Object createNode(final Object name) {
MutableCompositeNode newNode = NodeFactory.createMutableCompositeNode(
createQName(name), getCurrentNode(), null, null, null);
NodeUtils.fixParentRelation(newNode);
}
@Override
- protected Object createNode(Object name, @SuppressWarnings("rawtypes") Map attributes) {
+ protected Object createNode(final Object name, @SuppressWarnings("rawtypes") final Map attributes) {
ModifyAction modifyAction = processAttributes(attributes);
MutableCompositeNode newNode = NodeFactory.createMutableCompositeNode(
createQName(name), getCurrentNode(), null, modifyAction, null);
@Override
- protected Object createNode(Object name, @SuppressWarnings("rawtypes") Map attributes, Object value) {
+ protected Object createNode(final Object name, @SuppressWarnings("rawtypes") final Map attributes, final Object value) {
ModifyAction modifyAction = processAttributes(attributes);
SimpleNode<Object> newNode = NodeFactory.createImmutableSimpleNode(
createQName(name), (CompositeNode) getCurrent(), value, modifyAction);
* @param attributes
* @return
*/
- private ModifyAction processAttributes(@SuppressWarnings("rawtypes") Map attributes) {
+ private ModifyAction processAttributes(@SuppressWarnings("rawtypes") final Map attributes) {
LOG.debug("attributes:" + attributes);
ModifyAction modAction = null;
}
@Override
- protected Object createNode(Object name, Object value) {
+ protected Object createNode(final Object name, final Object value) {
SimpleNode<Object> newNode = NodeFactory.createImmutableSimpleNode(createQName(name), (CompositeNode) getCurrent(), value);
NodeUtils.fixParentRelation(newNode);
return newNode;
}
- private QName createQName(Object localName) {
+ private QName createQName(final Object localName) {
LOG.debug("qname for: "+localName);
return new QName(qnNamespace, qnRevision, qnPrefix, (String) localName);
}
}
@Override
- protected Object postNodeCompletion(Object parent, Object node) {
+ protected Object postNodeCompletion(final Object parent, final Object node) {
Node<?> nodeRevisited = (Node<?>) node;
LOG.debug("postNodeCompletion at: \n "+ nodeRevisited+"\n "+parent);
if (nodeRevisited instanceof MutableCompositeNode) {
rootNode = (CompositeNode) nodeRevisited;
} else {
NodeUtils.fixParentRelation(nodeRevisited);
- nodeRevisited.getParent().getChildren().remove(mutant);
+ nodeRevisited.getParent().getValue().remove(mutant);
}
}
*/
@Test
public void testImmutableNodes() throws Exception {
- Assert.assertEquals(2, network.getChildren().size());
+ Assert.assertEquals(2, network.getValue().size());
CompositeNode tpList = NodeUtils.findNodeByXpath(networkShadow,
NodeHelper.AddNamespaceToPattern(
"//{0}node[{0}node-id/text()='nodeId_19']/{0}termination-points", ns));
Document shadowConfig = NodeUtils.buildShadowDomTree(root);
NodeHelper.compareXmlTree(shadowConfig, "./mutableNodesConfig.xml", getClass());
- Assert.assertEquals(1, root.getChildren().size());
+ Assert.assertEquals(1, root.getValue().size());
Assert.assertEquals(1, ifNode.getSimpleNodesByName("name").size());
Assert.assertEquals(1, ifNode.getSimpleNodesByName("mtu").size());
Assert.assertEquals(2, topNode.getCompositesByName("interface").size());
" </network-elements>\n" +
"</network>";
- private static String domTreeString(Document domTree) throws TransformerException {
+ private static String domTreeString(final Document domTree) throws TransformerException {
TransformerFactory transformerFact = TransformerFactory.newInstance();
transformerFact.setAttribute("indent-number", 4);
Transformer transformer = transformerFact.newTransformer();
* @param out
* @throws Exception
*/
- private static void dumpDoc(Document domTree, PrintStream out) throws Exception {
+ private static void dumpDoc(final Document domTree, final PrintStream out) throws Exception {
out.println(domTreeString(domTree));
}
- public static void dumpDoc(Document domTree, Logger logger) throws TransformerException {
+ public static void dumpDoc(final Document domTree, final Logger logger) throws TransformerException {
logger.info("{}", domTreeString(domTree));
}
* @param qName
* @return example tree, see {@link #NETWORK_XML}
*/
- public static CompositeNode buildTestConfigTree(QName qName) {
+ public static CompositeNode buildTestConfigTree(final QName qName) {
List<Node<?>> value = new ArrayList<Node<?>>();
value.add(NodeFactory.createImmutableSimpleNode(new QName(qName, "element-id"), null, "ntElementId_09"));
CompositeNode ntElementNode1 = NodeFactory.createImmutableCompositeNode(new QName(qName, "network-element"), null, value);
/**
* @param parentNode
*/
- public static void assignParentToChildren(CompositeNode parentNode) {
- for (Node<?> child : parentNode.getChildren()) {
+ public static void assignParentToChildren(final CompositeNode parentNode) {
+ for (Node<?> child : parentNode.getValue()) {
((AbstractNodeTO<?>) child).setParent(parentNode);
}
}
* @return tree root
* @throws Exception
*/
- public static CompositeNode loadConfigByGroovy(String scriptName) throws Exception {
+ public static CompositeNode loadConfigByGroovy(final String scriptName) throws Exception {
InputStream configStream = NodeHelper.class.getResourceAsStream(scriptName);
Binding binding = new Binding();
GroovyShell gShell = new GroovyShell(binding);
* @param nsArg , e.g.: <pre>{"uri:ns1", "uri:ns2"}</pre>
* @return pattern with namespaces: <pre>//uri:ns1:network/uri:ns2:xx[text() = ''sss'']"</pre>
*/
- public static String AddNamespaceToPattern(String pattern, Object... nsArg) {
+ public static String AddNamespaceToPattern(final String pattern, final Object... nsArg) {
Object[] ns = nsArg;
String patternNs = pattern.replaceAll("'", "''");
if (ns == null) {
* @throws SAXException
* @throws IOException
*/
- public static void compareXmlTree(Document tree, String xmlFile, Class<?> clazz) throws Exception,
+ public static void compareXmlTree(final Document tree, final String xmlFile, final Class<?> clazz) throws Exception,
SAXException, IOException {
ByteArrayOutputStream actualRaw = new ByteArrayOutputStream();
dumpDoc(tree, new PrintStream(actualRaw));
CompositeNode topology = network.getCompositesByName("topologies").iterator().next()
.getCompositesByName("topology").iterator().next();
- Map<QName, List<Node<?>>> nodeMap = NodeUtils.buildNodeMap(topology.getChildren());
+ Map<QName, List<Node<?>>> nodeMap = NodeUtils.buildNodeMap(topology.getValue());
Assert.assertEquals(3, nodeMap.size());
}
NodeHelper.compareXmlTree(shadowTree, "./config02g-shadow.xml", getClass());
}
- private static void checkFamilyBinding(CompositeNode treeRoot) throws Exception {
+ private static void checkFamilyBinding(final CompositeNode treeRoot) throws Exception {
Stack<CompositeNode> jobQueue = new Stack<>();
jobQueue.push(treeRoot);
while (!jobQueue.isEmpty()) {
CompositeNode job = jobQueue.pop();
- for (Node<?> child : job.getChildren()) {
+ for (Node<?> child : job.getValue()) {
if (child instanceof CompositeNode) {
jobQueue.push((CompositeNode) child);
}
public class XmlTreeBuilderTest {
private InputStream inputStream;
-
+
/**
* Perform pre-test initialization
- *
+ *
* @throws Exception
*/
@Before
}
assertNotNull(rootNode);
assertTrue(rootNode instanceof CompositeNode);
-
+
CompositeNode compRootNode = (CompositeNode)rootNode;
- assertNotNull(compRootNode.getChildren());
-
+ assertNotNull(compRootNode.getValue());
+
SimpleNode<String> methodName = null;
SimpleNode<String> emptyTag = null;
CompositeNode params = null;
- for (final Node<?> childNode : compRootNode.getChildren()) {
+ for (final Node<?> childNode : compRootNode.getValue()) {
if (childNode instanceof SimpleNode) {
if ("emptyTag".equals(childNode.getNodeType().getLocalName())) {
emptyTag = (SimpleNode<String>) childNode;
} else if ("methodName".equals(childNode.getNodeType().getLocalName())) {
methodName = (SimpleNode<String>) childNode;
}
-
+
} else if (childNode instanceof CompositeNode) {
params = (CompositeNode) childNode;
}
}
-
+
assertNotNull(methodName);
assertNotNull(params);
assertTrue(emptyTag.getValue().isEmpty());
assertEquals(methodName.getValue(), "getDeviceEquipment");
-
+
String deviceId = null;
String deviceIP = null;
- for (final Node<?> param : params.getChildren()) {
+ for (final Node<?> param : params.getValue()) {
if (param instanceof CompositeNode) {
- final Node<?> valueNode = ((CompositeNode) param).getChildren().get(0);
-
+ final Node<?> valueNode = ((CompositeNode) param).getValue().get(0);
+
assertTrue(valueNode instanceof CompositeNode);
final CompositeNode value = (CompositeNode) valueNode;
- final Node<?> stringNode = value.getChildren().get(0);
+ final Node<?> stringNode = value.getValue().get(0);
assertTrue(stringNode instanceof SimpleNode);
-
+
final SimpleNode<String> string = (SimpleNode<String>) stringNode;
if ("DeviceID123".equals(string.getValue())) {
deviceId = string.getValue();
}
}
}
-
+
assertNotNull(deviceId);
assertNotNull(deviceIP);
}
-
+
@Test
public void nodeMapInCompositeNodeTest() {
Node<?> rootNode = null;
} catch (XMLStreamException e) {
e.printStackTrace();
}
-
+
CompositeNode compRootNode = (CompositeNode)rootNode;
List<CompositeNode> params = compRootNode.getCompositesByName("params");
assertEquals(1, params.size());
import org.opendaylight.yangtools.yang.common.QName;
/**
+ *
* The ChoiceNode defines a set of alternatives. It consists of a number of
* branches defined as ChoiceCaseNode objects.
*/
/**
* Returns cases of choice.
- *
+ *
* @return set of ChoiceCaseNode objects defined in this node which
* represents set of arguments of the YANG <code>case</code>
* substatement of the <code>choice</code> statement
Set<ChoiceCaseNode> getCases();
/**
- *
+ *
* Returns the concrete case according to specified Q name.
- *
+ *
* @param name
* QName of seeked Choice Case Node
* @return child case node of this Choice if child with given name is
/**
* Returns the concrete case according to specified name.
- *
+ *
* @param name
* name of seeked child as String
* @return child case node (or local name of case node) of this Choice if
ChoiceCaseNode getCaseNodeByName(String name);
/**
- *
+ *
* Returns name of case which is in the choice specified as default
- *
+ *
* @return string with the name of case which is specified in the argument
* of the YANG <code>default</code> substatement of
* <code>choice</code> statement.
package org.opendaylight.yangtools.yang.model.api;
/**
+ *
+ * Data Schema Node represents abstract supertype from which all data tree
+ * definitions are derived.
*
* Contains the method which are used for getting metadata from the schema nodes
* which contains data.
*
+ * @see ContainerSchemaNode
+ * @see ListSchemaNode
+ * @see LeafListSchemaNode
+ * @see ChoiceNode
+ * @see ChoiceCaseNode
+ * @see LeafSchemaNode
+ * @see AnyXmlSchemaNode
+ *
+ *
*/
public interface DataSchemaNode extends SchemaNode {
* @return set of the augmentation schema instances which are specified in
* the module as YANG {@link Module <b><font
* color="#dc143c">augment</font></b>} keyword and are
- * lexicographicaly ordered
+ * lexicographically ordered
*/
Set<AugmentationSchema> getAugmentations();
* @return set of identity schema node instances which are specified in the
* module as YANG {@link Module <b><font
* color="#bdb76b">identity</font></b>} keywords and are
- * lexicographicaly ordered
+ * lexicographically ordered
*/
Set<IdentitySchemaNode> getIdentities();
* @return set of extension definition instances which are specified in the
* module as YANG {@link Module <b><font
* color="#808000">extension</font></b>} keyword and are
- * lexicographicaly ordered
+ * lexicographically ordered
*/
List<ExtensionDefinition> getExtensionSchemaNodes();
*/
package org.opendaylight.yangtools.yang.model.api;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import java.util.Arrays;
import java.util.List;
-
import org.opendaylight.yangtools.yang.common.QName;
-import com.google.common.collect.ImmutableList;
-
/**
*
* Represents unique path to the every node inside the module.
*
*/
public class SchemaPath {
+ /**
+ * Shared instance of the conceptual root schema node.
+ */
+ public static final SchemaPath ROOT = new SchemaPath(ImmutableList.<QName> of(), true, null);
+
+ /**
+ * Shared instance of the "same" relative schema node.
+ */
+ public static final SchemaPath SAME = new SchemaPath(ImmutableList.<QName> of(), false, null);
+
/**
* List of QName instances which represents complete path to the node.
*/
- private final List<QName> path;
+ private final ImmutableList<QName> path;
/**
* Boolean value which represents type of schema path (relative or
* @param absolute
* boolean value which specifies if the path is absolute or
* relative
+ *
+ * @deprecated Use {@link #create(Iterable, boolean)} instead.
*/
+ @Deprecated
public SchemaPath(final List<QName> path, final boolean absolute) {
- this.path = ImmutableList.copyOf(path);
- this.absolute = absolute;
+ this(ImmutableList.copyOf(path), absolute, null);
}
/**
*
* @return list of <code>QName</code> instances which represents complete
* path to schema node
+ *
+ * @deprecated Use {@link #getPathFromRoot()} instead.
*/
+ @Deprecated
public List<QName> getPath() {
return path;
}
+ private SchemaPath(final ImmutableList<QName> path, final boolean absolute, final Void dummy) {
+ this.path = Preconditions.checkNotNull(path);
+ this.absolute = absolute;
+ }
+
+ /**
+ * Constructs new instance of this class with the concrete path.
+ *
+ * @param path
+ * list of QName instances which specifies exact path to the
+ * module node
+ * @param absolute
+ * boolean value which specifies if the path is absolute or
+ * relative
+ *
+ * @return A SchemaPath instance.
+ */
+ public static SchemaPath create(final Iterable<QName> path, final boolean absolute) {
+ if (Iterables.isEmpty(path)) {
+ return absolute ? ROOT : SAME;
+ } else {
+ return new SchemaPath(ImmutableList.copyOf(path), absolute, null);
+ }
+ }
+
+ /**
+ * Constructs new instance of this class with the concrete path.
+ *
+ * @param absolute
+ * boolean value which specifies if the path is absolute or
+ * relative
+ * @param path
+ * one or more QName instances which specifies exact path to the
+ * module node
+ *
+ * @return A SchemaPath instance.
+ */
+ public static SchemaPath create(final boolean absolute, final QName... path) {
+ return create(Arrays.asList(path), absolute);
+ }
+
+ /**
+ * Create a child path based on concatenation of this path and a relative path.
+ *
+ * @param relative Relative path
+ * @return A new child path
+ */
+ public SchemaPath createChild(final Iterable<QName> relative) {
+ if (Iterables.isEmpty(relative)) {
+ return this;
+ }
+ return create(Iterables.concat(path, relative), absolute);
+ }
+
+ /**
+ * Create a child path based on concatenation of this path and a relative path.
+ *
+ * @param relative Relative SchemaPath
+ * @return A new child path
+ */
+ public SchemaPath createChild(final SchemaPath relative) {
+ Preconditions.checkArgument(!relative.isAbsolute(), "Child creation requires relative path");
+ return createChild(relative.path);
+ }
+
+ /**
+ * Create a child path based on concatenation of this path and additional
+ * path elements.
+ *
+ * @param elements Relative SchemaPath elements
+ * @return A new child path
+ */
+ public SchemaPath createChild(final QName... elements) {
+ return createChild(Arrays.asList(elements));
+ }
+
+ /**
+ * Returns the list of nodes which need to be traversed to get from the
+ * starting point (root for absolute SchemaPaths) to the node represented
+ * by this object.
+ *
+ * @return list of <code>qname</code> instances which represents
+ * path from the root to the schema node.
+ */
+ public Iterable<QName> getPathFromRoot() {
+ return path;
+ }
+
+ /**
+ * Returns the list of nodes which need to be traversed to get from this
+ * node to the starting point (root for absolute SchemaPaths).
+ *
+ * @return list of <code>qname</code> instances which represents
+ * path from the schema node towards the root.
+ */
+ public Iterable<QName> getPathTowardsRoot() {
+ return path.reverse();
+ }
+
/**
* Describes whether schema path is|isn't absolute.
*
final int prime = 31;
int result = 1;
result = prime * result + absolute.hashCode();
- result = prime * result + ((path == null) ? 0 : path.hashCode());
+
+ // TODO: Temporary fix for Bug 1076 - hash computation
+ // Which adds same behaviour as using List.hashCode().
+ int pathHash = 1;
+ for (Object o : path) {
+ pathHash = prime * pathHash + o.hashCode();
+ }
+ result = prime * result + pathHash;
return result;
}
if (absolute != other.absolute) {
return false;
}
- if (path == null) {
- if (other.path != null) {
- return false;
- }
- } else if (!path.equals(other.path)) {
- return false;
- }
- return true;
+
+ return Iterables.elementsEqual(path, other.path);
}
@Override
*/
package org.opendaylight.yangtools.yang.model.util;
-import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
+import com.google.common.base.Optional;
+
/**
* The Abstract Integer class defines implementation of IntegerTypeDefinition
* interface which represents SIGNED Integer values defined in Yang language. <br>
private final List<RangeConstraint> rangeStatements;
/**
- * @param name
- * @param description
- * @param minRange
- * @param maxRange
- * @param units
+ * Construct SignedInteger
+ *
+ * @param name Name of type
+ * @param description Description of type
+ * @param minRange Minimal range
+ * @param maxRange Maxium range
+ * @param units Units
*/
- public AbstractSignedInteger(final QName name, final String description, final Number minRange,
+ protected AbstractSignedInteger(final QName name, final String description, final Number minRange,
final Number maxRange, final String units) {
this.name = name;
- this.path = new SchemaPath(Collections.singletonList(name), true);
+ this.path = SchemaPath.create(Collections.singletonList(name), true);
this.description = description;
this.units = units;
- this.rangeStatements = new ArrayList<RangeConstraint>();
final String rangeDescription = "Integer values between " + minRange + " and " + maxRange + ", inclusively.";
- this.rangeStatements.add(BaseConstraints.rangeConstraint(minRange, maxRange, rangeDescription,
- "https://tools.ietf.org/html/rfc6020#section-9.2.4"));
+ this.rangeStatements = Collections.singletonList(BaseConstraints.newRangeConstraint(minRange, maxRange, Optional.of(rangeDescription),
+ Optional.of("https://tools.ietf.org/html/rfc6020#section-9.2.4")));
}
@Override
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
*/
package org.opendaylight.yangtools.yang.model.util;
-import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
+import com.google.common.base.Optional;
+
/**
* The Abstract Integer class defines implementation of IntegerTypeDefinition
* interface which represents UNSIGNED Integer values defined in Yang language. <br>
private final List<RangeConstraint> rangeStatements;
/**
+ * Construct Unsigned Integer
*
- * @param name
- * @param description
- * @param maxRange
- * @param units
+ * @param name Name of type
+ * @param description Description of type
+ * @param maxRange Maximum value
+ * @param units Units
*/
public AbstractUnsignedInteger(final QName name, final String description, final Number maxRange, final String units) {
this.name = name;
- this.path = new SchemaPath(Collections.singletonList(name), true);
+ this.path = SchemaPath.create(Collections.singletonList(name), true);
this.description = description;
this.units = units;
- this.rangeStatements = new ArrayList<RangeConstraint>();
final String rangeDescription = "Integer values between " + MIN_VALUE + " and " + maxRange + ", inclusively.";
- this.rangeStatements.add(BaseConstraints.rangeConstraint(MIN_VALUE, maxRange, rangeDescription,
- "https://tools.ietf.org/html/rfc6020#section-9.2.4"));
+ this.rangeStatements = Collections.singletonList(BaseConstraints.newRangeConstraint(MIN_VALUE, maxRange, Optional.of(rangeDescription),
+ Optional.of("https://tools.ietf.org/html/rfc6020#section-9.2.4")));
}
@Override
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
+import com.google.common.base.Optional;
+
+/**
+ * Utility class which provides factory methods to construct Constraints.
+ *
+ * Provides static factory methods which constructs instances of
+ * <ul>
+ * <li>{@link LengthConstraint} - {@link #lengthConstraint(Number, Number, String, String)}
+ * <li>{@link RangeConstraint} - {@link #rangeConstraint(Number, Number, String, String)}
+ * <li>{@link PatternConstraint} - {@link #patternConstraint(String, String, String)}
+ * </ul>
+ */
public final class BaseConstraints {
private BaseConstraints() {
}
- public static LengthConstraint lengthConstraint(final Number min, final Number max, final String description,
- final String reference) {
+
+ /**
+ * Creates a {@link LengthConstraint}.
+ *
+ * Creates an instance of Length constraint based on supplied parameters
+ * with additional behaviour:
+ *
+ * <ul>
+ * <li>{@link LengthConstraint#getErrorAppTag()} returns <code>length-out-of-specified-bounds</code>
+ * <li>{@link LengthConstraint#getErrorMessage() returns <code>The argument is out of bounds <<i>min</i>, <i>max</i> ></code>
+ * </ul>
+ *
+ * @see LengthConstraint
+ *
+ * @param min length-restricting lower bound value. The value MUST NOT be negative.
+ * @param max length-restricting upper bound value. The value MUST NOT be negative.
+ * @param description Description associated with constraint. {@link Optional#absent()} if description is undefined.
+ * @param reference Reference associated with constraint. {@link Optional#absent()} if reference is undefined.
+ * @return Instance of {@link LengthConstraint}
+ */
+ public static LengthConstraint newLengthConstraint(final Number min, final Number max, final Optional<String> description,
+ final Optional<String> reference) {
return new LengthConstraintImpl(min, max, description, reference);
}
- public static RangeConstraint rangeConstraint(final Number min, final Number max, final String description,
- final String reference) {
+ /**
+ * Creates a {@link RangeConstraint}.
+ *
+ * Creates an instance of Range constraint based on supplied parameters
+ * with additional behaviour:
+ *
+ * <ul>
+ * <li>{@link RangeConstraint#getErrorAppTag()} returns <code>range-out-of-specified-bounds</code>
+ * <li>{@link RangeConstraint#getErrorMessage() returns <code>The argument is out of bounds <<i>min</i>, <i>max</i> ></code>
+ * </ul>
+ *
+ *
+ * @see RangeConstraint
+ *
+ * @param min value-restricting lower bound value. The value MUST NOT Be null.
+ * @param max value-restricting upper bound value. The value MUST NOT Be null.
+ * @param description Description associated with constraint. {@link Optional#absent()} if description is undefined.
+ * @param reference Reference associated with constraint. {@link Optional#absent()} if reference is undefined.
+ * @return Instance of {@link RangeConstraint}
+ */
+ public static RangeConstraint newRangeConstraint(final Number min, final Number max, final Optional<String> description,
+ final Optional<String> reference) {
return new RangeConstraintImpl(min, max, description, reference);
}
- public static PatternConstraint patternConstraint(final String pattern, final String description,
- final String reference) {
+
+ /**
+ * Creates a {@link PatternConstraint}.
+ *
+ * Creates an instance of Pattern constraint based on supplied parameters
+ * with additional behaviour:
+ *
+ * <ul>
+ * <li>{@link PatternConstraint#getErrorAppTag()} returns <code>invalid-regular-expression</code>
+ * </ul>
+ *
+ * @see PatternConstraint
+ *
+ * @param pattern Regular expression, MUST NOT BE null.
+ * @param description Description associated with constraint.
+ * @param reference Reference associated with constraint.
+ * @returnInstance of {@link PatternConstraint}
+ */
+ public static PatternConstraint newPatternConstraint(final String pattern, final Optional<String> description,
+ final Optional<String> reference) {
return new PatternConstraintImpl(pattern, description, reference);
}
- private static final class LengthConstraintImpl implements LengthConstraint {
-
- private final Number min;
- private final Number max;
-
- private final String description;
- private final String reference;
-
- private final String errorAppTag;
- private final String errorMessage;
- public LengthConstraintImpl(Number min, Number max, final String description, final String reference) {
- super();
- this.min = min;
- this.max = max;
- this.description = description;
- this.reference = reference;
-
- this.errorAppTag = "length-out-of-specified-bounds";
- this.errorMessage = "The argument is out of bounds <" + min + ", " + max + ">";
- }
-
- @Override
- public String getDescription() {
- return description;
- }
-
- @Override
- public String getErrorAppTag() {
- return errorAppTag;
- }
-
- @Override
- public String getErrorMessage() {
- return errorMessage;
- }
-
- @Override
- public String getReference() {
- return reference;
- }
-
- @Override
- public Number getMin() {
- return min;
- }
-
- @Override
- public Number getMax() {
- return max;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((description == null) ? 0 : description.hashCode());
- result = prime * result + ((errorAppTag == null) ? 0 : errorAppTag.hashCode());
- result = prime * result + ((errorMessage == null) ? 0 : errorMessage.hashCode());
- result = prime * result + ((max == null) ? 0 : max.hashCode());
- result = prime * result + ((min == null) ? 0 : min.hashCode());
- result = prime * result + ((reference == null) ? 0 : reference.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- final LengthConstraintImpl other = (LengthConstraintImpl) obj;
- if (description == null) {
- if (other.description != null) {
- return false;
- }
- } else if (!description.equals(other.description)) {
- return false;
- }
- if (errorAppTag == null) {
- if (other.errorAppTag != null) {
- return false;
- }
- } else if (!errorAppTag.equals(other.errorAppTag)) {
- return false;
- }
- if (errorMessage == null) {
- if (other.errorMessage != null) {
- return false;
- }
- } else if (!errorMessage.equals(other.errorMessage)) {
- return false;
- }
- if (max != other.max) {
- return false;
- }
- if (min != other.min) {
- return false;
- }
- if (reference == null) {
- if (other.reference != null) {
- return false;
- }
- } else if (!reference.equals(other.reference)) {
- return false;
- }
- return true;
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("LengthConstraintImpl [min=");
- builder.append(min);
- builder.append(", max=");
- builder.append(max);
- builder.append(", description=");
- builder.append(description);
- builder.append(", errorAppTag=");
- builder.append(errorAppTag);
- builder.append(", reference=");
- builder.append(reference);
- builder.append(", errorMessage=");
- builder.append(errorMessage);
- builder.append("]");
- return builder.toString();
- }
+ /**
+ * Creates a {@link LengthConstraint}.
+ *
+ * Creates an instance of Length constraint based on supplied parameters
+ * with additional behaviour:
+ *
+ * <ul>
+ * <li>{@link LengthConstraint#getErrorAppTag()} returns <code>length-out-of-specified-bounds</code>
+ * <li>{@link LengthConstraint#getErrorMessage() returns <code>The argument is out of bounds <<i>min</i>, <i>max</i> ></code>
+ * </ul>
+ *
+ * @see LengthConstraint
+ *
+ * @param min length-restricting lower bound value. The value MUST NOT be negative.
+ * @param max length-restricting upper bound value. The value MUST NOT be negative.
+ * @param description Description associated with constraint.
+ * @param reference Reference associated with constraint.
+ * @return Instance of {@link LengthConstraint}
+ * @deprecated Use {@link #newLengthConstraint(Number, Number, Optional, Optional)} instead.
+ */
+ @Deprecated
+ public static LengthConstraint lengthConstraint(final Number min, final Number max, final String description,
+ final String reference) {
+ return newLengthConstraint(min, max, Optional.fromNullable(description), Optional.fromNullable(reference));
}
- private static final class RangeConstraintImpl implements RangeConstraint {
- private final Number min;
- private final Number max;
-
- private final String description;
- private final String reference;
-
- private final String errorAppTag;
- private final String errorMessage;
-
- public RangeConstraintImpl(Number min, Number max, String description, String reference) {
- super();
- this.min = min;
- this.max = max;
- this.description = description;
- this.reference = reference;
-
- this.errorAppTag = "range-out-of-specified-bounds";
- this.errorMessage = "The argument is out of bounds <" + min + ", " + max + ">";
- }
-
- @Override
- public String getDescription() {
- return description;
- }
-
- @Override
- public String getErrorAppTag() {
- return errorAppTag;
- }
-
- @Override
- public String getErrorMessage() {
- return errorMessage;
- }
-
- @Override
- public String getReference() {
- return reference;
- }
-
- @Override
- public Number getMin() {
- return min;
- }
-
- @Override
- public Number getMax() {
- return max;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((description == null) ? 0 : description.hashCode());
- result = prime * result + ((errorAppTag == null) ? 0 : errorAppTag.hashCode());
- result = prime * result + ((errorMessage == null) ? 0 : errorMessage.hashCode());
- result = prime * result + ((max == null) ? 0 : max.hashCode());
- result = prime * result + ((min == null) ? 0 : min.hashCode());
- result = prime * result + ((reference == null) ? 0 : reference.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- final RangeConstraintImpl other = (RangeConstraintImpl) obj;
- if (description == null) {
- if (other.description != null) {
- return false;
- }
- } else if (!description.equals(other.description)) {
- return false;
- }
- if (errorAppTag == null) {
- if (other.errorAppTag != null) {
- return false;
- }
- } else if (!errorAppTag.equals(other.errorAppTag)) {
- return false;
- }
- if (errorMessage == null) {
- if (other.errorMessage != null) {
- return false;
- }
- } else if (!errorMessage.equals(other.errorMessage)) {
- return false;
- }
- if (max == null) {
- if (other.max != null) {
- return false;
- }
- } else if (!max.equals(other.max)) {
- return false;
- }
- if (min == null) {
- if (other.min != null) {
- return false;
- }
- } else if (!min.equals(other.min)) {
- return false;
- }
- if (reference == null) {
- if (other.reference != null) {
- return false;
- }
- } else if (!reference.equals(other.reference)) {
- return false;
- }
- return true;
- }
-
- @Override
- public String toString() {
- final StringBuilder builder = new StringBuilder();
- builder.append("RangeConstraintImpl [min=");
- builder.append(min);
- builder.append(", max=");
- builder.append(max);
- builder.append(", description=");
- builder.append(description);
- builder.append(", reference=");
- builder.append(reference);
- builder.append(", errorAppTag=");
- builder.append(errorAppTag);
- builder.append(", errorMessage=");
- builder.append(errorMessage);
- builder.append("]");
- return builder.toString();
- }
+ /**
+ * Creates a {@link RangeConstraint}.
+ *
+ * Creates an instance of Range constraint based on supplied parameters
+ * with additional behaviour:
+ *
+ * <ul>
+ * <li>{@link RangeConstraint#getErrorAppTag()} returns <code>range-out-of-specified-bounds</code>
+ * <li>{@link RangeConstraint#getErrorMessage() returns <code>The argument is out of bounds <<i>min</i>, <i>max</i> ></code>
+ * </ul>
+ *
+ *
+ * @see RangeConstraint
+ *
+ * @param min value-restricting lower bound value. The value MUST NOT Be null.
+ * @param max value-restricting upper bound value. The value MUST NOT Be null.
+ * @param description Description associated with constraint.
+ * @param reference Reference associated with constraint.
+ * @return Instance of {@link RangeConstraint}
+ * @deprecated Use {@link #newRangeConstraint(Number, Number, Optional, Optional)} instead.
+ */
+ @Deprecated
+ public static RangeConstraint rangeConstraint(final Number min, final Number max, final String description,
+ final String reference) {
+ return newRangeConstraint(min, max, Optional.fromNullable(description), Optional.fromNullable(reference));
}
- private static final class PatternConstraintImpl implements PatternConstraint {
-
- private final String regex;
- private final String description;
- private final String reference;
-
- private final String errorAppTag;
- private final String errorMessage;
-
- public PatternConstraintImpl(final String regex, final String description, final String reference) {
- super();
- this.regex = regex;
- this.description = description;
- this.reference = reference;
-
- errorAppTag = "invalid-regular-expression";
- // TODO: add erro message
- errorMessage = "";
- }
-
- @Override
- public String getDescription() {
- return description;
- }
-
- @Override
- public String getErrorAppTag() {
- return errorAppTag;
- }
-
- @Override
- public String getErrorMessage() {
- return errorMessage;
- }
-
- @Override
- public String getReference() {
- return reference;
- }
-
- @Override
- public String getRegularExpression() {
- return regex;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((description == null) ? 0 : description.hashCode());
- result = prime * result + ((errorAppTag == null) ? 0 : errorAppTag.hashCode());
- result = prime * result + ((errorMessage == null) ? 0 : errorMessage.hashCode());
- result = prime * result + ((reference == null) ? 0 : reference.hashCode());
- result = prime * result + ((regex == null) ? 0 : regex.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(final Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- final PatternConstraintImpl other = (PatternConstraintImpl) obj;
- if (description == null) {
- if (other.description != null) {
- return false;
- }
- } else if (!description.equals(other.description)) {
- return false;
- }
- if (errorAppTag == null) {
- if (other.errorAppTag != null) {
- return false;
- }
- } else if (!errorAppTag.equals(other.errorAppTag)) {
- return false;
- }
- if (errorMessage == null) {
- if (other.errorMessage != null) {
- return false;
- }
- } else if (!errorMessage.equals(other.errorMessage)) {
- return false;
- }
- if (reference == null) {
- if (other.reference != null) {
- return false;
- }
- } else if (!reference.equals(other.reference)) {
- return false;
- }
- if (regex == null) {
- if (other.regex != null) {
- return false;
- }
- } else if (!regex.equals(other.regex)) {
- return false;
- }
- return true;
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("PatternConstraintImpl [regex=");
- builder.append(regex);
- builder.append(", description=");
- builder.append(description);
- builder.append(", reference=");
- builder.append(reference);
- builder.append(", errorAppTag=");
- builder.append(errorAppTag);
- builder.append(", errorMessage=");
- builder.append(errorMessage);
- builder.append("]");
- return builder.toString();
- }
+ /**
+ * Creates a {@link PatternConstraint}.
+ *
+ * Creates an instance of Range constraint based on supplied parameters
+ * with additional behaviour:
+ *
+ * <ul>
+ * <li>{@link PatternConstraint#getErrorAppTag()} returns <code>invalid-regular-expression</code>
+ * </ul>
+ *
+ *
+ * @see PatternConstraint
+ *
+ * @param pattern Regular expression, MUST NOT
+ * @param description Description associated with constraint.
+ * @param reference Reference associated with constraint.
+ * @return Instance of {@link PatternConstraint}
+ * @deprecated Use {@link #newPatternConstraint(String, Optional, Optional)} Instead.
+ */
+ @Deprecated
+ public static PatternConstraint patternConstraint(final String pattern, final String description,
+ final String reference) {
+ return newPatternConstraint(pattern, Optional.fromNullable(description), Optional.fromNullable(reference));
}
}
import java.util.Collections;
import java.util.Date;
import java.util.List;
+import java.util.Set;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableSet;
+
+/**
+ * Utility methods and constants to work with built-in YANG types
+ *
+ *
+ */
public final class BaseTypes {
private BaseTypes() {
}
public static final URI BASE_TYPES_NAMESPACE = URI.create("urn:ietf:params:xml:ns:yang:1");
+
public static final QName BINARY_QNAME = constructQName("binary");
public static final QName BITS_QNAME = constructQName("bits");
public static final QName BOOLEAN_QNAME = constructQName("boolean");
public static final QName DECIMAL64_QNAME = constructQName("decimal64");
public static final QName EMPTY_QNAME = constructQName("empty");
public static final QName ENUMERATION_QNAME = constructQName("enumeration");
+ public static final QName IDENTITYREF_QNAME = constructQName("identityref");
+ public static final QName INSTANCE_IDENTIFIER_QNAME = constructQName("instance-identifier");
public static final QName INT8_QNAME = constructQName("int8");
public static final QName INT16_QNAME = constructQName("int16");
public static final QName INT32_QNAME = constructQName("int32");
public static final QName UINT16_QNAME = constructQName("uint16");
public static final QName UINT32_QNAME = constructQName("uint32");
public static final QName UINT64_QNAME = constructQName("uint64");
+ public static final QName UNION_QNAME = constructQName("union");
+
+ private static final Set<String> BUILD_IN_TYPES = ImmutableSet.<String> builder().add(BINARY_QNAME.getLocalName()) //
+ .add(BITS_QNAME.getLocalName()) //
+ .add(BOOLEAN_QNAME.getLocalName()) //
+ .add(DECIMAL64_QNAME.getLocalName()) //
+ .add(EMPTY_QNAME.getLocalName()) //
+ .add(ENUMERATION_QNAME.getLocalName()) //
+ .add(IDENTITYREF_QNAME.getLocalName()) //
+ .add(INSTANCE_IDENTIFIER_QNAME.getLocalName()) //
+ .add(INT8_QNAME.getLocalName()) //
+ .add(INT16_QNAME.getLocalName()) //
+ .add(INT32_QNAME.getLocalName()) //
+ .add(INT64_QNAME.getLocalName()) //
+ .add(LEAFREF_QNAME.getLocalName()) //
+ .add(STRING_QNAME.getLocalName()) //
+ .add(UINT8_QNAME.getLocalName()) //
+ .add(UINT16_QNAME.getLocalName()) //
+ .add(UINT32_QNAME.getLocalName()) //
+ .add(UINT64_QNAME.getLocalName()) //
+ .add(UNION_QNAME.getLocalName()) //
+ .build();
/**
* Construct QName for Built-in base Yang type. The namespace for built-in
}
/**
- * Creates Schema Path from Qname.
+ * Creates Schema Path from {@link QName}.
*
* @param typeName
* yang type QName
* @return Schema Path from Qname.
+ * @deprecated Use {@link SchemaPath#create(boolean, QName...)} instead.
*/
+ @Deprecated
public static SchemaPath schemaPath(final QName typeName) {
- List<QName> pathList = Collections.singletonList(typeName);
- return new SchemaPath(pathList, true);
+ return SchemaPath.create(Collections.singletonList(typeName), true);
}
/**
* @param revision
* Revision Date
* @return Schema Path
+ *
+ * @deprecated Use {@link SchemaPath#create(boolean, Iterable)} with QNames
+ * manually constructed.
*/
+ @Deprecated
public static SchemaPath schemaPath(final List<String> actualPath, final URI namespace, final Date revision) {
if (actualPath == null) {
throw new IllegalArgumentException("The actual path List MUST be specified.");
pathList.add(qname);
}
}
- return new SchemaPath(pathList, true);
+ return SchemaPath.create(pathList, true);
+ }
+
+ /**
+ * Returns true if supplied type is representation of built-in YANG type as
+ * per RFC 6020.
+ *
+ * See package documentation for description of base types.
+ *
+ * @param type
+ * @return true if type is built-in YANG Types.
+ */
+ public static boolean isYangBuildInType(final String type) {
+ return BUILD_IN_TYPES.contains(type);
+ }
+
+ /**
+ * Returns default instance of built-in for supplied type
+ *
+ * See package documentation for description of base build-in types
+ * with default instance.
+ *
+ * @param typeName
+ * @return Returns default instance or {@link Optional#absent()} if default
+ * instance does not exists
+ *
+ */
+ public static Optional<TypeDefinition<?>> defaultBaseTypeFor(final String typeName) {
+ return Optional.<TypeDefinition<?>> fromNullable(defaultBaseTypeForImpl(typeName));
+ }
+
+ private static TypeDefinition<?> defaultBaseTypeForImpl(final String typeName) {
+ Preconditions.checkNotNull(typeName, "typeName must not be null.");
+
+ if (typeName.startsWith("int")) {
+ if ("int8".equals(typeName)) {
+ return Int8.getInstance();
+ } else if ("int16".equals(typeName)) {
+ return Int16.getInstance();
+ } else if ("int32".equals(typeName)) {
+ return Int32.getInstance();
+ } else if ("int64".equals(typeName)) {
+ return Int64.getInstance();
+ }
+ } else if (typeName.startsWith("uint")) {
+ if ("uint8".equals(typeName)) {
+ return Uint8.getInstance();
+ } else if ("uint16".equals(typeName)) {
+ return Uint16.getInstance();
+ } else if ("uint32".equals(typeName)) {
+ return Uint32.getInstance();
+ } else if ("uint64".equals(typeName)) {
+ return Uint64.getInstance();
+ }
+ } else if ("string".equals(typeName)) {
+ return StringType.getInstance();
+ } else if ("binary".equals(typeName)) {
+ return BinaryType.getInstance();
+ } else if ("boolean".equals(typeName)) {
+ return BooleanType.getInstance();
+ } else if ("empty".equals(typeName)) {
+ return EmptyType.getInstance();
+ } else if ("instance-identifier".equals(typeName)) {
+ return InstanceIdentifier.getInstance();
+ }
+ return null;
}
+
}
*/
package org.opendaylight.yangtools.yang.model.util;
-import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
+import com.google.common.base.Optional;
+
/**
* The <code>default</code> implementation of Binary Type Definition interface.
*
* @see BinaryTypeDefinition
*/
public final class BinaryType implements BinaryTypeDefinition {
- private static final BinaryType INSTANCE = new BinaryType();
- private final QName name = BaseTypes.constructQName("binary");
- private final SchemaPath path = new SchemaPath(Collections.singletonList(name), true);
private static final String DESCRIPTION = "The binary built-in type represents any binary data, i.e., a sequence of octets.";
private static final String REFERENCE = "https://tools.ietf.org/html/rfc6020#section-9.8";
- private final List<Byte> bytes;
- private final List<LengthConstraint> lengthConstraints;
private static final String UNITS = "";
+ private final static QName QNAME = BaseTypes.BINARY_QNAME;
+
+ private static final BinaryType INSTANCE = new BinaryType();
+
+ private final static SchemaPath PATH = SchemaPath.create(Collections.singletonList(QNAME), true);
+ private final List<Byte> bytes = Collections.emptyList();
+ private final List<LengthConstraint> lengthConstraints;
+
private BinaryType() {
- final List<LengthConstraint> constraints = new ArrayList<LengthConstraint>();
- constraints.add(BaseConstraints.lengthConstraint(0, Long.MAX_VALUE, "", ""));
- this.lengthConstraints = Collections.unmodifiableList(constraints);
- this.bytes = Collections.emptyList();
+ this.lengthConstraints = Collections.singletonList(
+ BaseConstraints.newLengthConstraint(0, Long.MAX_VALUE, Optional.of(""), Optional.of("")));
}
public static BinaryType getInstance() {
*/
@Override
public QName getQName() {
- return name;
+ return QNAME;
}
/*
*/
@Override
public SchemaPath getPath() {
- return path;
+ return PATH;
}
/*
int result = 1;
result = prime * result + ((bytes == null) ? 0 : bytes.hashCode());
result = prime * result + ((lengthConstraints == null) ? 0 : lengthConstraints.hashCode());
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result + ((path == null) ? 0 : path.hashCode());
+ result = prime * result + QNAME.hashCode();
+ result = prime * result + PATH.hashCode();
return result;
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
} else if (!lengthConstraints.equals(other.lengthConstraints)) {
return false;
}
- if (name == null) {
- if (other.name != null) {
- return false;
- }
- } else if (!name.equals(other.name)) {
- return false;
- }
- if (path == null) {
- if (other.path != null) {
- return false;
- }
- } else if (!path.equals(other.path)) {
- return false;
- }
return true;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BinaryType [name=");
- builder.append(name);
- builder.append(", path=");
- builder.append(path);
+ builder.append(QNAME);
builder.append(", description=");
builder.append(DESCRIPTION);
builder.append(", reference=");
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
/**
* The <code>default</code> implementation of Bits Type Definition interface.
*
* @see BitsTypeDefinition
*/
public final class BitsType implements BitsTypeDefinition {
- private final QName name = BaseTypes.constructQName("bits");
+ private final static QName NAME = BaseTypes.BITS_QNAME;
+
private final SchemaPath path;
private final String description = "The bits built-in type represents a bit set. "
+ "That is, a bits value is a set of flags identified by small integer position "
* Instantiates Bits type as empty bits list.
*
* @param path
+ * @deprecated Use static factory method {@link #create(SchemaPath, List)} instead.
*/
+ @Deprecated
public BitsType(final SchemaPath path) {
super();
this.bits = Collections.emptyList();
- this.path = path;
+ this.path = Preconditions.checkNotNull(path,"path must not be null");
}
/**
*
* @param path
* @param bits
+ * @deprecated Use static factory method {@link #create(SchemaPath, List)} instead.
*/
+ @Deprecated
public BitsType(final SchemaPath path, final List<Bit> bits) {
super();
- this.bits = Collections.unmodifiableList(bits);
- this.path = path;
+ this.bits = ImmutableList.copyOf(bits);
+ this.path = Preconditions.checkNotNull(path,"path must not be null");
+ }
+
+ public static BitsType create(final SchemaPath path, final List<Bit> bits) {
+ return new BitsType(path,bits);
}
/*
*/
@Override
public QName getQName() {
- return name;
+ return NAME;
}
/*
int result = 1;
result = prime * result + ((bits == null) ? 0 : bits.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result + ((path == null) ? 0 : path.hashCode());
+ result = prime * result + NAME.hashCode();
+ result = prime * result + path.hashCode();
return result;
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
} else if (!description.equals(other.description)) {
return false;
}
- if (name == null) {
- if (other.name != null) {
- return false;
- }
- } else if (!name.equals(other.name)) {
- return false;
- }
+
if (path == null) {
if (other.path != null) {
return false;
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BitsType [name=");
- builder.append(name);
+ builder.append(NAME);
builder.append(", path=");
builder.append(path);
builder.append(", description=");
*/
public final class BooleanType implements BooleanTypeDefinition {
private static final BooleanType INSTANCE = new BooleanType();
- private static final QName NAME = BaseTypes.constructQName("boolean");
- private static final SchemaPath PATH = new SchemaPath(Collections.singletonList(NAME), true);
+ private static final SchemaPath PATH = SchemaPath.create(Collections.singletonList(BaseTypes.BOOLEAN_QNAME), true);
private static final String DESCRIPTION = "The boolean built-in type represents a boolean value.";
private static final String REFERENCE = "https://tools.ietf.org/html/rfc6020#section-9.5";
private static final String UNITS = "";
private BooleanType() {
}
+ /**
+ * Returns default instance of boolean built-in type.
+ * @return default instance of boolean built-in type.
+ */
public static BooleanType getInstance() {
return INSTANCE;
}
*/
@Override
public QName getQName() {
- return NAME;
+ return BaseTypes.BOOLEAN_QNAME;
}
/*
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BooleanType [name=");
- builder.append(NAME);
+ builder.append(BaseTypes.BOOLEAN_QNAME);
builder.append(", path=");
builder.append(PATH);
builder.append("]");
import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+/**
+ * DataNodeIterator is iterator, which walks down whole YANG DataNodeContainer
+ * and walks all instances of {@link DataSchemaNode} present in subtree.
+ *
+ * Iterator instance is eagerly created, walking happens on initialization.
+ *
+ * Iteration is not ordered.
+ *
+ */
public class DataNodeIterator implements Iterator<DataSchemaNode> {
private final DataNodeContainer container;
traverse(this.container);
}
+ /**
+ * Returns list all containers present in subtree.
+ *
+ * @return Returns list all containers present in subtree.
+ */
public List<ContainerSchemaNode> allContainers() {
return allContainers;
}
+ /**
+ * Returns list all lists present in subtree.
+ *
+ * @return Returns list all containers present in subtree.
+ */
public List<ListSchemaNode> allLists() {
return allLists;
}
+ /**
+ * Returns list all choices present in subtree.
+ *
+ * @return Returns list all containers present in subtree.
+ */
public List<ChoiceNode> allChoices() {
return allChoices;
}
+ /**
+ * Returns list all groupings present in subtree.
+ *
+ * @return Returns list all containers present in subtree.
+ */
public List<GroupingDefinition> allGroupings() {
return allGroupings;
}
+ /**
+ * Returns list all typedefs present in subtree.
+ *
+ * @return Returns list all containers present in subtree.
+ */
public List<TypeDefinition<?>> allTypedefs() {
return allTypedefs;
}
}
- private void traverseModule(DataNodeContainer dataNode) {
+ private void traverseModule(final DataNodeContainer dataNode) {
final Module module;
if (dataNode instanceof Module) {
module = (Module) dataNode;
}
}
- private void traverseGroupings(DataNodeContainer dataNode) {
+ private void traverseGroupings(final DataNodeContainer dataNode) {
final Set<GroupingDefinition> groupings = dataNode.getGroupings();
if (groupings != null) {
for (GroupingDefinition grouping : groupings) {
import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
+import com.google.common.base.Optional;
+
/**
* The <code>default</code> implementation of Decimal Type Definition interface.
*
* @see DecimalTypeDefinition
*/
public final class Decimal64 implements DecimalTypeDefinition {
- private final QName name = BaseTypes.constructQName("decimal64");
+ private static final QName NAME = BaseTypes.DECIMAL64_QNAME;
private final SchemaPath path;
private static final String UNITS = "";
private static final BigDecimal DEFAULT_VALUE = null;
*
* @see DecimalTypeDefinition
* @exception IllegalArgumentException
+ * @deprecated Use static factory {@link #create(SchemaPath, Integer)}.
*/
+ @Deprecated
public Decimal64(final SchemaPath path, final Integer fractionDigits) {
if (!((fractionDigits.intValue() >= 1) && (fractionDigits.intValue() <= MAX_NUMBER_OF_FRACTION_DIGITS))) {
throw new IllegalArgumentException(
this.path = path;
}
+ public static Decimal64 create(final SchemaPath path, final Integer fractionDigits) {
+ return new Decimal64(path, fractionDigits);
+ }
+
/**
* Returns unmodifiable List with default definition of Range Statements.
*
final BigDecimal min = new BigDecimal("-922337203685477580.8");
final BigDecimal max = new BigDecimal("922337203685477580.7");
final String rangeDescription = "Integer values between " + min + " and " + max + ", inclusively.";
- rangeStmts.add(BaseConstraints.rangeConstraint(min, max, rangeDescription,
- "https://tools.ietf.org/html/rfc6020#section-9.2.4"));
+ rangeStmts.add(BaseConstraints.newRangeConstraint(min, max, Optional.of(rangeDescription),
+ Optional.of("https://tools.ietf.org/html/rfc6020#section-9.2.4")));
return Collections.unmodifiableList(rangeStmts);
}
@Override
public QName getQName() {
- return name;
+ return NAME;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
- result = prime * result + ((name == null) ? 0 : name.hashCode());
+ result = prime * result + ((NAME == null) ? 0 : NAME.hashCode());
result = prime * result + ((path == null) ? 0 : path.hashCode());
return result;
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
return false;
}
Decimal64 other = (Decimal64) obj;
- if (name == null) {
- if (other.name != null) {
- return false;
- }
- } else if (!name.equals(other.name)) {
- return false;
- }
if (path == null) {
if (other.path != null) {
return false;
@Override
public String toString() {
- return Decimal64.class.getSimpleName() + "[qname=" + name + ", fractionDigits=" + fractionDigits + "]";
+ return Decimal64.class.getSimpleName() + "[qname=" + NAME + ", fractionDigits=" + fractionDigits + "]";
}
}
import java.util.Collections;
import java.util.List;
+import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.Status;
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
-public final class EmptyType implements EmptyTypeDefinition {
- private static EmptyType instance;
- private static final QName NAME = BaseTypes.constructQName("empty");
- private static final SchemaPath PATH = new SchemaPath(Collections.singletonList(NAME), true);
+public final class EmptyType implements EmptyTypeDefinition, Immutable {
+ private static final EmptyType INSTANCE = new EmptyType();
+ private static final QName NAME = BaseTypes.EMPTY_QNAME;
+ private static final SchemaPath PATH = SchemaPath.create(Collections.singletonList(NAME), true);
private static final String DESCRIPTION = "The empty built-in type represents a leaf that does not have any value, it conveys information by its presence or absence.";
private static final String REFERENCE = "https://tools.ietf.org/html/rfc6020#page-131";
}
public static EmptyType getInstance() {
- if (instance == null) {
- instance = new EmptyType();
- }
- return instance;
+ return INSTANCE;
}
@Override
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
/**
private final EnumPair defaultEnum;
private final List<EnumPair> enums;
+
+ /**
+ * Constructs EnumerationType
+ *
+ * @param path
+ * @param enums
+ * @deprecated Use {@link #create(SchemaPath, List, Optional)} instead.
+ */
+ @Deprecated
public EnumerationType(final SchemaPath path, final List<EnumPair> enums) {
- super();
- this.path = path;
- this.enums = ImmutableList.copyOf(enums);
- this.defaultEnum = null;
+ this(path,enums,Optional.<EnumPair>absent());
}
+ /**
+ * Constructs EnumerationType
+ *
+ * @param path
+ * @param defaultEnum
+ * @param enums
+ * @deprecated Use {@link #create(SchemaPath, List, Optional)} instead.
+ */
+ @Deprecated
public EnumerationType(final SchemaPath path, final EnumPair defaultEnum, final List<EnumPair> enums) {
- super();
- this.path = path;
- this.defaultEnum = defaultEnum;
- this.enums = ImmutableList.copyOf(enums);
+ this(path,enums,Optional.fromNullable(defaultEnum));
+ }
+
+ private EnumerationType(final SchemaPath path, final List<EnumPair> enums, final Optional<EnumPair> defaultEnum) {
+ this.path = Preconditions.checkNotNull(path,"path must not be null");
+ this.enums = ImmutableList.copyOf(Preconditions.checkNotNull(enums, "enums must not be null."));
+ if(defaultEnum.isPresent()) {
+ Preconditions.checkArgument(enums.contains(defaultEnum.get()),"defaultEnum must be contained in defined enumerations.");
+ this.defaultEnum = defaultEnum.get();
+ } else {
+ this.defaultEnum = null;
+ }
+ }
+
+ /**
+ *
+ * Constructs new enumeration
+ *
+ * @param path Schema Path to definition point of this enumeration
+ * @param enums List of defined enumeration values
+ * @param defaultValue {@link Optional#of(Object)} of default value, {@link Optional#absent()} if no default value is defined.
+ * If defaultValue is set, it must be present in provided list of enumerations.
+ *
+ */
+ public static EnumerationType create(final SchemaPath path, final List<EnumPair> enums, final Optional<EnumPair> defaultValue) {
+ return new EnumerationType(path, enums, defaultValue);
}
/*
import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+/**
+ * Extended Type represents YANG type derived from other type.
+ *
+ * Extended type object is decorator on top of existing {@link TypeDefinition}
+ * which represents original type, and extended type
+ * may define additional constraints, modify description or reference
+ * of parent type or provide new type capture for specific use-cases.
+ *
+ */
public class ExtendedType implements TypeDefinition<TypeDefinition<?>> {
private final QName typeName;
private List<PatternConstraint> patterns = Collections.emptyList();
private Integer fractionDigits = null;
- private Status status;
- private String units;
- private Object defaultValue;
- private boolean addedByUses;
+ private final Status status;
+ private final String units;
+ private final Object defaultValue;
+ private final boolean addedByUses;
+
+ /**
+ *
+ * Creates Builder for extended / derived type.
+ *
+ * @param typeName QName of derived type
+ * @param baseType Base type of derived type
+ * @param description Description of type
+ * @param reference Reference of Type
+ * @param path Schema path to type definition.
+ */
+ public static final Builder builder(final QName typeName,final TypeDefinition<?> baseType,final Optional<String> description,final Optional<String> reference,final SchemaPath path) {
+ return new Builder(typeName, baseType, description.or(""), reference.or(""), path);
+ }
public static class Builder {
private final QName typeName;
private List<PatternConstraint> patterns = Collections.emptyList();
private Integer fractionDigits = null;
+ /**
+ *
+ * @param actualPath
+ * @param namespace
+ * @param revision
+ * @param typeName
+ * @param baseType
+ * @param description
+ * @param reference
+ *
+ * @deprecated Use {@link ExtendedType#builder(QName, TypeDefinition, Optional, Optional, SchemaPath) instead.
+ */
+ @Deprecated
public Builder(final List<String> actualPath, final URI namespace,
final Date revision, final QName typeName,
- TypeDefinition<?> baseType, final String description,
+ final TypeDefinition<?> baseType, final String description,
final String reference) {
- this.typeName = typeName;
- this.baseType = baseType;
- this.path = BaseTypes.schemaPath(actualPath, namespace, revision);
- this.description = description;
- this.reference = reference;
+ this(typeName,baseType,description,reference,BaseTypes.schemaPath(actualPath, namespace, revision));
}
- public Builder(final QName typeName, TypeDefinition<?> baseType,
+ /**
+ *
+ * Creates Builder for extended / derived type.
+ *
+ * @param typeName QName of derived type
+ * @param baseType Base type of derived type
+ * @param description Description of type
+ * @param reference Reference of Type
+ * @param path Schema path to type definition.
+ *
+ * @deprecated Use {@link ExtendedType#builder(QName, TypeDefinition, Optional, Optional, SchemaPath) instead.
+ */
+ @Deprecated
+ public Builder(final QName typeName, final TypeDefinition<?> baseType,
final String description, final String reference,
- SchemaPath path) {
- this.typeName = typeName;
- this.baseType = baseType;
- this.path = path;
+ final SchemaPath path) {
+ this.typeName = Preconditions.checkNotNull(typeName, "type name must not be null.");
+ this.baseType = Preconditions.checkNotNull(baseType, "base type must not be null");
+ this.path = Preconditions.checkNotNull(path, "path must not be null.");
this.description = description;
this.reference = reference;
}
- public Builder status(Status status) {
+ public Builder status(final Status status) {
this.status = status;
return this;
}
- public Builder units(String units) {
+ public Builder units(final String units) {
this.units = units;
return this;
}
}
}
- private ExtendedType(Builder builder) {
+ private ExtendedType(final Builder builder) {
this.typeName = builder.typeName;
this.baseType = builder.baseType;
this.path = builder.path;
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(final Object o) {
if (this == o) {
return true;
}
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
+import com.google.common.base.Preconditions;
+
/**
* The <code>default</code> implementation of Identityref Type Definition
* interface.
* @see IdentityrefTypeDefinition
*/
public final class IdentityrefType implements IdentityrefTypeDefinition {
- private final QName name = BaseTypes.constructQName("identityref");
+ private static final QName NAME = BaseTypes.IDENTITYREF_QNAME;
private final SchemaPath path;
private static final String DESCRIPTION = "The identityref type is used to reference an existing identity.";
private static final String REFERENCE = "https://tools.ietf.org/html/rfc6020#section-9.10";
private final IdentitySchemaNode identity;
private static final String UNITS = "";
- public IdentityrefType(IdentitySchemaNode identity, SchemaPath schemaPath) {
- this.identity = identity;
- this.path = schemaPath;
+ /**
+ * Constructs new {@link IdentityrefTypeDefinition} definition.
+ *
+ * @param identity
+ * @param schemaPath
+ */
+ @Deprecated
+ public IdentityrefType(final IdentitySchemaNode identity, final SchemaPath schemaPath) {
+ this(schemaPath,identity);
+ }
+
+ private IdentityrefType(final SchemaPath path, final IdentitySchemaNode baseIdentity) {
+ this.path = Preconditions.checkNotNull(path, "Path must be specified");
+ this.identity = Preconditions.checkNotNull(baseIdentity,"baseIdentity must be specified.");
+ }
+
+ /**
+ *
+ * Constructs new {@link IdentityrefTypeDefinition} definition.
+ *
+ * @param path Path to the definition.
+ * @param baseIdentity Base Identity, all derived identities are valid arguments for instance of this type.
+ * @return New identityref definition.
+ */
+ public static IdentityrefType create(final SchemaPath path, final IdentitySchemaNode baseIdentity) {
+ return new IdentityrefType(path, baseIdentity);
}
@Override
@Override
public QName getQName() {
- return name;
+ return NAME;
}
@Override
import java.util.Collections;
import java.util.List;
+import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
* The <code>default</code> implementation of Instance Identifier Type
* Definition interface.
*
+ * Instance Identifier has only two possible variants - one with
+ * {@link #requireInstance()} which returns true, other one
+ * returns false.
+ *
* @see InstanceIdentifierTypeDefinition
- * @deprecated Depracated, use {@link org.opendaylight.yangtools.yang.data.api.InstanceIdentifier} instead
+ *
*/
-@Deprecated
-public final class InstanceIdentifier implements InstanceIdentifierTypeDefinition {
- private static final QName NAME = BaseTypes.constructQName("instance-identifier");
- private static final SchemaPath PATH = new SchemaPath(Collections.singletonList(NAME), true);
+public final class InstanceIdentifier implements InstanceIdentifierTypeDefinition, Immutable {
+
+ private static final QName NAME = BaseTypes.INSTANCE_IDENTIFIER_QNAME;
+ private static final SchemaPath PATH = SchemaPath.create(Collections.singletonList(NAME), true);
private static final String DESCRIPTION = "The instance-identifier built-in type is used to "
+ "uniquely identify a particular instance node in the data tree.";
private static final String REFERENCE = "https://tools.ietf.org/html/rfc6020#section-9.13";
- private final RevisionAwareXPath xpath;
private static final String UNITS = "";
- private boolean requireInstance = true;
+ private final Boolean requireInstance;
- private static final int HASH_BOOLEAN_TRUE = 1231;
- private static final int HASH_BOOLEAN_FALSE = 1237;
+ private static final InstanceIdentifier INSTANCE_WITH_REQUIRED_TRUE = new InstanceIdentifier(true);
+ private static final InstanceIdentifier INSTANCE_WITH_REQUIRED_FALSE = new InstanceIdentifier(false);
+ /**
+ * Constructs new instance identifier.
+ *
+ * @param xpath
+ * @deprecated Use {@link #getInstance()} for default one, since Instance Identifier does not have xpath.
+ */
+ @Deprecated
public InstanceIdentifier(final RevisionAwareXPath xpath) {
- this.xpath = xpath;
+ requireInstance = true;
}
+ /**
+ * Constructs new instance identifier.
+ *
+ * @param xpath
+ * @param requireInstance if instance of data is required
+ * @deprecated Use {@link #create(boolean)}, since Instance Identifier does not have xpath.
+ */
+ @Deprecated
public InstanceIdentifier(final RevisionAwareXPath xpath, final boolean requireInstance) {
- this.xpath = xpath;
this.requireInstance = requireInstance;
}
+ private InstanceIdentifier(final boolean requiredInstance) {
+ this.requireInstance = requiredInstance;
+ }
+
+ public static InstanceIdentifier getInstance() {
+ return INSTANCE_WITH_REQUIRED_TRUE;
+ }
+
+ public static InstanceIdentifier create(final boolean requireInstance) {
+ return requireInstance ? INSTANCE_WITH_REQUIRED_TRUE : INSTANCE_WITH_REQUIRED_FALSE;
+ }
+
/*
* (non-Javadoc)
*
*/
@Override
public Object getDefaultValue() {
- return xpath;
+ return null;
}
/*
* InstanceIdentifierTypeDefinition# getPathStatement()
*/
@Override
+ @Deprecated
public RevisionAwareXPath getPathStatement() {
- return xpath;
+ return null;
}
/*
public int hashCode() {
final int prime = 31;
int result = 1;
- result = prime * result + (requireInstance ? HASH_BOOLEAN_TRUE : HASH_BOOLEAN_FALSE);
- result = prime * result + ((xpath == null) ? 0 : xpath.hashCode());
+ result = prime * result + requireInstance.hashCode();
return result;
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
return false;
}
InstanceIdentifier other = (InstanceIdentifier) obj;
- if (requireInstance != other.requireInstance) {
- return false;
- }
- if (xpath == null) {
- if (other.xpath != null) {
- return false;
- }
- } else if (!xpath.equals(other.xpath)) {
- return false;
- }
- return true;
+ return requireInstance.equals(other.requireInstance);
}
+
+
}
*/
package org.opendaylight.yangtools.yang.model.util;
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.concepts.Immutable;
/**
* Implementation of Yang int16 built-in type. <br>
*
* @see AbstractSignedInteger
*/
-public final class Int16 extends AbstractSignedInteger {
- private static Int16 instance;
- private static final QName NAME = BaseTypes.constructQName("int16");
+public final class Int16 extends AbstractSignedInteger implements Immutable {
private static final String DESCRIPTION = "int16 represents integer values between -32768 and 32767, inclusively.";
+ private static final Int16 INSTANCE = new Int16();
+
private Int16() {
- super(NAME, DESCRIPTION, Short.MIN_VALUE, Short.MAX_VALUE, "");
+ super(BaseTypes.INT16_QNAME, DESCRIPTION, Short.MIN_VALUE, Short.MAX_VALUE, "");
}
+ /**
+ * Returns default instance of int16 type.
+ * @return default instance of int16 type.
+ */
public static Int16 getInstance() {
- if (instance == null) {
- instance = new Int16();
- }
- return instance;
+ return INSTANCE;
}
@Override
@Override
public String toString() {
- return "type " + NAME;
+ return "type " + BaseTypes.INT16_QNAME;
}
}
*/
package org.opendaylight.yangtools.yang.model.util;
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.concepts.Immutable;
/**
* Implementation of Yang int32 built-in type. <br>
* @see AbstractSignedInteger
*
*/
-public final class Int32 extends AbstractSignedInteger {
- private static Int32 instance;
- private static final QName NAME = BaseTypes.constructQName("int32");
+public final class Int32 extends AbstractSignedInteger implements Immutable {
private static final String DESCRIPTION = "int32 represents integer values between -2147483648 and 2147483647, inclusively.";
+
+ private static final Int32 INSTANCE = new Int32();
+
private Int32() {
- super(Int32.NAME, Int32.DESCRIPTION, Integer.MIN_VALUE, Integer.MAX_VALUE, "");
+ super(BaseTypes.INT32_QNAME, Int32.DESCRIPTION, Integer.MIN_VALUE, Integer.MAX_VALUE, "");
}
+ /**
+ * Returns default instance of int32 type.
+ * @return default instance of int32 type.
+ */
public static Int32 getInstance() {
- if (instance == null) {
- instance = new Int32();
- }
- return instance;
+ return INSTANCE;
}
@Override
@Override
public String toString() {
- return "type " + NAME;
+ return "type " + BaseTypes.INT32_QNAME;
}
+
}
*/
package org.opendaylight.yangtools.yang.model.util;
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.concepts.Immutable;
/**
* Implementation of Yang int64 built-in type. <br>
* type is {@link Long}.
*
*/
-public final class Int64 extends AbstractSignedInteger {
- private static Int64 instance;
- private static final QName NAME = BaseTypes.constructQName("int64");
+public final class Int64 extends AbstractSignedInteger implements Immutable {
private static final String DESCRIPTION = "int64 represents integer values between -9223372036854775808 and 9223372036854775807, inclusively.";
private Int64() {
- super(NAME, DESCRIPTION, Long.MIN_VALUE, Long.MAX_VALUE, "");
+ super(BaseTypes.INT64_QNAME, DESCRIPTION, Long.MIN_VALUE, Long.MAX_VALUE, "");
}
+
+ private static final Int64 INSTANCE = new Int64();
+
+ /**
+ * Returns default instance of int64 type.
+ * @return default instance of int64 type.
+ */
public static Int64 getInstance() {
- if (instance == null) {
- instance = new Int64();
- }
- return instance;
+ return INSTANCE;
}
@Override
@Override
public String toString() {
- return "type " + NAME;
+ return "type " + BaseTypes.INT64_QNAME;
}
-
}
*/
package org.opendaylight.yangtools.yang.model.util;
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.concepts.Immutable;
/**
* Implementation of Yang int8 built-in type. <br>
*
* @see AbstractSignedInteger
*/
-public final class Int8 extends AbstractSignedInteger {
- private static Int8 instance;
- private static final QName NAME = BaseTypes.constructQName("int8");
+public final class Int8 extends AbstractSignedInteger implements Immutable {
private static final String DESCRIPTION = "represents integer values between -128 and 127, inclusively.";
private Int8() {
- super(NAME, DESCRIPTION, Byte.MIN_VALUE, Byte.MAX_VALUE, "");
+ super(BaseTypes.INT8_QNAME, DESCRIPTION, Byte.MIN_VALUE, Byte.MAX_VALUE, "");
}
+ private static final Int8 INSTANCE = new Int8();
+
+ /**
+ * Returns default instance of int8 type.
+ * @return default instance of int8 type.
+ */
public static Int8 getInstance() {
- if (instance == null) {
- instance = new Int8();
- }
- return instance;
+ return INSTANCE;
}
@Override
@Override
public String toString() {
- return "type " + NAME;
+ return "type " + BaseTypes.INT8_QNAME;
}
}
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
+import com.google.common.base.Preconditions;
+
/**
* The <code>default</code> implementation of Instance Leafref Type Definition
* interface.
private static final String REF = "https://tools.ietf.org/html/rfc6020#section-9.9";
private final RevisionAwareXPath xpath;
+ private final SchemaPath path;
+ @Deprecated
public Leafref(final RevisionAwareXPath xpath) {
- this.xpath = xpath;
+ this(PATH,xpath);
+
+ }
+
+ private Leafref(final SchemaPath path, final RevisionAwareXPath target) {
+ this.path = Preconditions.checkNotNull(path,"path must be specified");
+ this.xpath = Preconditions.checkNotNull(target,"target must not be null.");
+ }
+
+ public static Leafref create(final SchemaPath path,final RevisionAwareXPath target) {
+ return new Leafref(path,target);
}
@Override
@Override
public SchemaPath getPath() {
- return PATH;
+ return path;
}
@Override
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.model.util;
+
+import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+
+/**
+ * {@link Immutable} implementation of {@link LengthConstraint}.
+ *
+ * Length constraint based on supplied parameters with additional behaviour:
+ *
+ * <ul>
+ * <li>{@link LengthConstraint#getErrorAppTag()} returns
+ * <code>length-out-of-specified-bounds</code>
+ * <li>{@link LengthConstraint#getErrorMessage() returns <code>The argument is
+ * out of bounds <<i>min</i>, <i>max</i> ></code>
+ * </ul
+ */
+final class LengthConstraintImpl implements LengthConstraint, Immutable {
+
+ private final Number min;
+ private final Number max;
+
+ private final String description;
+ private final String reference;
+
+ private final String errorAppTag;
+ private final String errorMessage;
+
+ LengthConstraintImpl(final Number min, final Number max, final Optional<String> description,
+ final Optional<String> reference) {
+ super();
+ this.min = Preconditions.checkNotNull(min, "min must not be null.");
+ this.max = Preconditions.checkNotNull(max, "max must not be null");
+ this.description = description.orNull();
+ this.reference = reference.orNull();
+
+ this.errorAppTag = "length-out-of-specified-bounds";
+ this.errorMessage = "The argument is out of bounds <" + min + ", " + max + ">";
+ }
+
+ @Override
+ public String getDescription() {
+ return description;
+ }
+
+ @Override
+ public String getErrorAppTag() {
+ return errorAppTag;
+ }
+
+ @Override
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ @Override
+ public String getReference() {
+ return reference;
+ }
+
+ @Override
+ public Number getMin() {
+ return min;
+ }
+
+ @Override
+ public Number getMax() {
+ return max;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((description == null) ? 0 : description.hashCode());
+ result = prime * result + errorAppTag.hashCode();
+ result = prime * result + errorMessage.hashCode();
+ result = prime * result + max.hashCode();
+ result = prime * result + min.hashCode();
+ result = prime * result + ((reference == null) ? 0 : reference.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ final LengthConstraintImpl other = (LengthConstraintImpl) obj;
+ if (description == null) {
+ if (other.description != null) {
+ return false;
+ }
+ } else if (!description.equals(other.description)) {
+ return false;
+ }
+ if (errorAppTag == null) {
+ if (other.errorAppTag != null) {
+ return false;
+ }
+ } else if (!errorAppTag.equals(other.errorAppTag)) {
+ return false;
+ }
+ if (errorMessage == null) {
+ if (other.errorMessage != null) {
+ return false;
+ }
+ } else if (!errorMessage.equals(other.errorMessage)) {
+ return false;
+ }
+ if (max != other.max) {
+ return false;
+ }
+ if (min != other.min) {
+ return false;
+ }
+ if (reference == null) {
+ if (other.reference != null) {
+ return false;
+ }
+ } else if (!reference.equals(other.reference)) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("LengthConstraintImpl [min=");
+ builder.append(min);
+ builder.append(", max=");
+ builder.append(max);
+ builder.append(", description=");
+ builder.append(description);
+ builder.append(", errorAppTag=");
+ builder.append(errorAppTag);
+ builder.append(", reference=");
+ builder.append(reference);
+ builder.append(", errorMessage=");
+ builder.append(errorMessage);
+ builder.append("]");
+ return builder.toString();
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.model.util;
+
+import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+
+/**
+ * {@link Immutable} implementation of {@link PatternConstraint}
+ *
+ * Creates an instance of Range constraint based on supplied parameters with
+ * additional behaviour:
+ *
+ * <ul>
+ * <li>{@link PatternConstraint#getErrorAppTag()} returns
+ * <code>invalid-regular-expression</code>
+ * </ul>
+ *
+ */
+final class PatternConstraintImpl implements PatternConstraint, Immutable {
+
+ private final String regex;
+ private final String description;
+ private final String reference;
+
+ private final String errorAppTag;
+ private final String errorMessage;
+
+ public PatternConstraintImpl(final String regex, final Optional<String> description,
+ final Optional<String> reference) {
+ super();
+ this.regex = Preconditions.checkNotNull(regex, "regex must not be null.");
+ this.description = description.orNull();
+ this.reference = reference.orNull();
+
+ // FIXME: Lookup better suitable error tag.
+ errorAppTag = "invalid-regular-expression";
+ // TODO: add erro message
+ errorMessage = "";
+ }
+
+ @Override
+ public String getDescription() {
+ return description;
+ }
+
+ @Override
+ public String getErrorAppTag() {
+ return errorAppTag;
+ }
+
+ @Override
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ @Override
+ public String getReference() {
+ return reference;
+ }
+
+ @Override
+ public String getRegularExpression() {
+ return regex;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((description == null) ? 0 : description.hashCode());
+ result = prime * result + ((errorAppTag == null) ? 0 : errorAppTag.hashCode());
+ result = prime * result + ((errorMessage == null) ? 0 : errorMessage.hashCode());
+ result = prime * result + ((reference == null) ? 0 : reference.hashCode());
+ result = prime * result + regex.hashCode();
+ return result;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ final PatternConstraintImpl other = (PatternConstraintImpl) obj;
+ if (description == null) {
+ if (other.description != null) {
+ return false;
+ }
+ } else if (!description.equals(other.description)) {
+ return false;
+ }
+ if (errorAppTag == null) {
+ if (other.errorAppTag != null) {
+ return false;
+ }
+ } else if (!errorAppTag.equals(other.errorAppTag)) {
+ return false;
+ }
+ if (errorMessage == null) {
+ if (other.errorMessage != null) {
+ return false;
+ }
+ } else if (!errorMessage.equals(other.errorMessage)) {
+ return false;
+ }
+ if (reference == null) {
+ if (other.reference != null) {
+ return false;
+ }
+ } else if (!reference.equals(other.reference)) {
+ return false;
+ }
+ if (regex == null) {
+ if (other.regex != null) {
+ return false;
+ }
+ } else if (!regex.equals(other.regex)) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("PatternConstraintImpl [regex=");
+ builder.append(regex);
+ builder.append(", description=");
+ builder.append(description);
+ builder.append(", reference=");
+ builder.append(reference);
+ builder.append(", errorAppTag=");
+ builder.append(errorAppTag);
+ builder.append(", errorMessage=");
+ builder.append(errorMessage);
+ builder.append("]");
+ return builder.toString();
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.model.util;
+
+import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
+import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+
+/**
+ * {@link Immutable} implementation of {@link LengthConstraint}.
+ *
+ * Range constraint based on supplied parameters with additional behaviour:
+ *
+ * <ul>
+ * <li>{@link RangeConstraint#getErrorAppTag()} returns
+ * <code>range-out-of-specified-bounds</code>
+ * <li>{@link RangeConstraint#getErrorMessage() returns <code>The argument is
+ * out of bounds <<i>min</i>, <i>max</i> ></code>
+ * </ul>
+ */
+final class RangeConstraintImpl implements RangeConstraint, Immutable {
+ private final Number min;
+ private final Number max;
+
+ private final String description;
+ private final String reference;
+
+ private final String errorAppTag;
+ private final String errorMessage;
+
+ RangeConstraintImpl(final Number min, final Number max, final Optional<String> description,
+ final Optional<String> reference) {
+ super();
+ this.min = Preconditions.checkNotNull(min, "min must not be null.");
+ this.max = Preconditions.checkNotNull(max, "max must not be null.");
+ this.description = description.orNull();
+ this.reference = reference.orNull();
+
+ this.errorAppTag = "range-out-of-specified-bounds";
+ this.errorMessage = "The argument is out of bounds <" + min + ", " + max + ">";
+ }
+
+ @Override
+ public String getDescription() {
+ return description;
+ }
+
+ @Override
+ public String getErrorAppTag() {
+ return errorAppTag;
+ }
+
+ @Override
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ @Override
+ public String getReference() {
+ return reference;
+ }
+
+ @Override
+ public Number getMin() {
+ return min;
+ }
+
+ @Override
+ public Number getMax() {
+ return max;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((description == null) ? 0 : description.hashCode());
+ result = prime * result + errorAppTag.hashCode();
+ result = prime * result + errorMessage.hashCode();
+ result = prime * result + max.hashCode();
+ result = prime * result + min.hashCode();
+ result = prime * result + ((reference == null) ? 0 : reference.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ final RangeConstraintImpl other = (RangeConstraintImpl) obj;
+ if (description == null) {
+ if (other.description != null) {
+ return false;
+ }
+ } else if (!description.equals(other.description)) {
+ return false;
+ }
+ if (max == null) {
+ if (other.max != null) {
+ return false;
+ }
+ } else if (!max.equals(other.max)) {
+ return false;
+ }
+ if (min == null) {
+ if (other.min != null) {
+ return false;
+ }
+ } else if (!min.equals(other.min)) {
+ return false;
+ }
+ if (reference == null) {
+ if (other.reference != null) {
+ return false;
+ }
+ } else if (!reference.equals(other.reference)) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append("RangeConstraintImpl [min=");
+ builder.append(min);
+ builder.append(", max=");
+ builder.append(max);
+ builder.append(", description=");
+ builder.append(description);
+ builder.append(", reference=");
+ builder.append(reference);
+ builder.append(", errorAppTag=");
+ builder.append(errorAppTag);
+ builder.append(", errorMessage=");
+ builder.append(errorMessage);
+ builder.append("]");
+ return builder.toString();
+ }
+}
\ No newline at end of file
import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
/**
- * The <code>default</code> implementation of Instance Rewision Aware XPath
+ * The <code>helper</code> implementation of Instance Rewision Aware XPath
* interface.
- *
+ *
* @see RevisionAwareXPath
*/
public class RevisionAwareXPathImpl implements RevisionAwareXPath {
private static final int HASH_BOOLEAN_TRUE = 1231;
private static final int HASH_BOOLEAN_FALSE = 1237;
- public RevisionAwareXPathImpl(String xpath, boolean absolute) {
+ public RevisionAwareXPathImpl(final String xpath, final boolean absolute) {
this.xpath = xpath;
this.absolute = absolute;
}
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
List<QName> names = sp.getPath();
List<QName> newNames = new ArrayList<>(names);
newNames.remove(newNames.size() - 1);
- SchemaPath newSp = new SchemaPath(newNames, sp.isAbsolute());
+ SchemaPath newSp = SchemaPath.create(newNames, sp.isAbsolute());
parent = findDataSchemaNode(ctx, newSp);
do {
if (nodeNewNames.isEmpty()) {
parent = getParentModule((SchemaNode) parent, ctx);
} else {
- SchemaPath nodeNewSp = new SchemaPath(nodeNewNames, nodeSp.isAbsolute());
+ SchemaPath nodeNewSp = SchemaPath.create(nodeNewNames, nodeSp.isAbsolute());
parent = findDataSchemaNode(ctx, nodeNewSp);
}
} else {
List<QName> names = sp.getPath();
List<QName> newNames = new ArrayList<>(names);
newNames.remove(newNames.size() - 1);
- SchemaPath newSp = new SchemaPath(newNames, sp.isAbsolute());
+ SchemaPath newSp = SchemaPath.create(newNames, sp.isAbsolute());
parent = findDataSchemaNode(ctx, newSp);
if (parent instanceof AugmentationTarget) {
tmpPath.add(currentName);
*/
package org.opendaylight.yangtools.yang.model.util;
-import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.Status;
import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
+import com.google.common.base.Optional;
+
/**
* The <code>default</code> implementation of String Type Definition interface.
*
* @see StringTypeDefinition
*/
-public final class StringType implements StringTypeDefinition {
- private static final StringType INSTANCE = new StringType();
- private final QName name = BaseTypes.constructQName("string");
- private final SchemaPath path = new SchemaPath(Collections.singletonList(name), true);
+public final class StringType implements StringTypeDefinition, Immutable {
+ private static final QName NAME = BaseTypes.STRING_QNAME;
+ private static final SchemaPath PATH = SchemaPath.create(Collections.singletonList(NAME), true);
private static final String DEFAULT_VALUE = "";
private static final String DESCRIPTION = "";
private static final String REFERENCE = "";
private final List<PatternConstraint> patterns;
private static final String UNITS = "";
+ private static final StringType INSTANCE = new StringType();
+
/**
* Default Constructor.
*/
private StringType() {
- final List<LengthConstraint> constraints = new ArrayList<LengthConstraint>();
- constraints.add(BaseConstraints.lengthConstraint(0, Integer.MAX_VALUE, "", ""));
- lengthStatements = Collections.unmodifiableList(constraints);
+ lengthStatements = Collections.singletonList(BaseConstraints.newLengthConstraint(0, Integer.MAX_VALUE, Optional.of(""), Optional.of("")));
patterns = Collections.emptyList();
}
*/
@Override
public QName getQName() {
- return name;
+ return NAME;
}
/*
*/
@Override
public SchemaPath getPath() {
- return path;
+ return PATH;
}
/*
final int prime = 31;
int result = 1;
result = prime * result + ((lengthStatements == null) ? 0 : lengthStatements.hashCode());
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result + ((path == null) ? 0 : path.hashCode());
+ result = prime * result + NAME.hashCode();
+ result = prime * result + PATH.hashCode();
result = prime * result + ((patterns == null) ? 0 : patterns.hashCode());
return result;
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
} else if (!lengthStatements.equals(other.lengthStatements)) {
return false;
}
- if (name == null) {
- if (other.name != null) {
- return false;
- }
- } else if (!name.equals(other.name)) {
- return false;
- }
- if (path == null) {
- if (other.path != null) {
- return false;
- }
- } else if (!path.getPath().equals(other.path.getPath())) {
- return false;
- }
if (patterns == null) {
if (other.patterns != null) {
return false;
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("StringType [name=");
- builder.append(name);
+ builder.append(NAME);
builder.append(", path=");
- builder.append(path);
+ builder.append(PATH);
builder.append(", defaultValue=");
builder.append(DEFAULT_VALUE);
builder.append(", description=");
*/
package org.opendaylight.yangtools.yang.model.util;
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.concepts.Immutable;
/**
* Implementation of Yang uint16 built-in type. <br>
* counterpart of Yang uint16 built-in type is {@link Integer}.
*
*/
-public final class Uint16 extends AbstractUnsignedInteger {
+public final class Uint16 extends AbstractUnsignedInteger implements Immutable {
public static final int MAX_VALUE = 65535;
- private static Uint16 instance;
- private static final QName NAME = BaseTypes.constructQName("uint16");
private static final String DESCRIPTION = "uint16 represents integer values between 0 and 65535, inclusively.";
+ private static Uint16 INSTANCE = new Uint16();
+
private Uint16() {
- super(NAME, DESCRIPTION, MAX_VALUE, "");
+ super(BaseTypes.UINT16_QNAME, DESCRIPTION, MAX_VALUE, "");
}
public static Uint16 getInstance() {
- if (instance == null) {
- instance = new Uint16();
- }
- return instance;
+ return INSTANCE;
}
@Override
@Override
public String toString() {
- return "type " + NAME;
+ return "type " + BaseTypes.UINT16_QNAME;
}
}
*/
package org.opendaylight.yangtools.yang.model.util;
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.concepts.Immutable;
/**
* Implementation of Yang uint32 built-in type. <br>
* uint32 represents integer values between 0 and 4294967295, inclusively.
*
*/
-public final class Uint32 extends AbstractUnsignedInteger {
+public final class Uint32 extends AbstractUnsignedInteger implements Immutable {
public static final long MAX_VALUE = 4294967295L;
- private static Uint32 instance;
- private static final QName NAME = BaseTypes.constructQName("uint32");
private static final String DESCRIPTION = "uint32 represents integer values between 0 and 4294967295, inclusively.";
+ private static final Uint32 INSTANCE = new Uint32();
+
+
private Uint32() {
- super(NAME, DESCRIPTION, MAX_VALUE, "");
+ super(BaseTypes.UINT32_QNAME, DESCRIPTION, MAX_VALUE, "");
}
public static Uint32 getInstance() {
- if (instance == null) {
- instance = new Uint32();
- }
- return instance;
+ return INSTANCE;
}
@Override
@Override
public String toString() {
- return "type " + NAME;
+ return "type " + BaseTypes.UINT32_QNAME;
}
}
import java.math.BigInteger;
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.concepts.Immutable;
/**
* Implementation of Yang uint64 built-in type. <br>
* {@link BigInteger}.
*
*/
-public final class Uint64 extends AbstractUnsignedInteger {
+public final class Uint64 extends AbstractUnsignedInteger implements Immutable {
public static final BigInteger MAX_VALUE = new BigInteger("18446744073709551615");
- private static Uint64 instance;
- private static final QName NAME = BaseTypes.constructQName("uint64");
private static final String DESCRIPTION = "uint64 represents integer values between 0 and 18446744073709551615, inclusively.";
+ private static final Uint64 INSTANCE = new Uint64();
+
private Uint64() {
- super(NAME, DESCRIPTION, MAX_VALUE, "");
+ super(BaseTypes.UINT64_QNAME, DESCRIPTION, MAX_VALUE, "");
}
public static Uint64 getInstance() {
- if (instance == null) {
- instance = new Uint64();
- }
- return instance;
+ return INSTANCE;
}
@Override
@Override
public String toString() {
- return "type " + NAME;
+ return "type " + BaseTypes.UINT64_QNAME;
}
}
*/
package org.opendaylight.yangtools.yang.model.util;
-import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.concepts.Immutable;
/**
* Implementation of Yang uint8 built-in type. <br>
*
* @see AbstractUnsignedInteger
*/
-public final class Uint8 extends AbstractUnsignedInteger {
+public final class Uint8 extends AbstractUnsignedInteger implements Immutable {
public static final int MAX_VALUE = 255;
- private static Uint8 instance;
- private static final QName NAME = BaseTypes.constructQName("uint8");
private static final String DESCRIPTION = "uint8 represents integer values between 0 and 255, inclusively.";
+ private static final Uint8 INSTANCE = new Uint8();
+
private Uint8() {
- super(NAME, DESCRIPTION, MAX_VALUE, "");
+ super(BaseTypes.UINT8_QNAME, DESCRIPTION, MAX_VALUE, "");
}
public static Uint8 getInstance() {
- if (instance == null) {
- instance = new Uint8();
- }
- return instance;
+ return INSTANCE;
}
@Override
@Override
public String toString() {
- return "type " + NAME;
+ return "type " + BaseTypes.UINT8_QNAME;
}
}
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
public final class UnionType implements UnionTypeDefinition {
- private final QName name = BaseTypes.constructQName("union");
- private final SchemaPath path = BaseTypes.schemaPath(name);
+ private final SchemaPath path = SchemaPath.create(Collections.singletonList(BaseTypes.UNION_QNAME),true);
private static final String DESCRIPTION = "The union built-in type represents a value that corresponds to one of its member types.";
private static final String REFERENCE = "https://tools.ietf.org/html/rfc6020#section-9.12";
private final List<TypeDefinition<?>> types;
- public UnionType(List<TypeDefinition<?>> types) {
- if (types == null) {
- throw new IllegalArgumentException("When the type is 'union', the 'type' statement MUST be present.");
- }
- this.types = types;
+ @Deprecated
+ public UnionType(final List<TypeDefinition<?>> types) {
+ Preconditions.checkNotNull(types,"When the type is 'union', the 'type' statement MUST be present.");
+ this.types = ImmutableList.copyOf(types);
+ }
+
+ public static UnionType create(final List<TypeDefinition<?>> types) {
+ return new UnionType(types);
}
@Override
@Override
public QName getQName() {
- return name;
+ return BaseTypes.UNION_QNAME;
}
@Override
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("type ");
- builder.append(name);
+ builder.append(BaseTypes.UNION_QNAME);
builder.append(" (types=[");
for (TypeDefinition<?> td : types) {
builder.append(", " + td.getQName().getLocalName());
import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
import org.opendaylight.yangtools.yang.model.api.type.UnknownTypeDefinition;
+/**
+ * Utility implementation of unknown type definition.
+ *
+ * Unknown type definition is derived type, for
+ * which base built-in type is not yet known. This types
+ * are possible during parsing and resolving of YANG model
+ * without all requisites allready processed.
+ *
+ *
+ */
public final class UnknownType implements UnknownTypeDefinition {
private final QName name;
this.path = BaseTypes.schemaPath(name);
}
- public Builder description(String description) {
+ public Builder description(final String description) {
this.description = description;
return this;
}
- public Builder reference(String reference) {
+ public Builder reference(final String reference) {
this.reference = reference;
return this;
}
return this;
}
- public Builder status(Status status) {
+ public Builder status(final Status status) {
this.status = status;
return this;
}
- public Builder units(String units) {
+ public Builder units(final String units) {
this.units = units;
return this;
}
}
}
- private UnknownType(Builder builder) {
+ private UnknownType(final Builder builder) {
this.name = builder.name;
this.path = builder.path;
this.description = builder.description;
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
*/
package org.opendaylight.yangtools.yang.model.util;
-import java.util.HashSet;
-import java.util.Set;
-
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+/**
+ * Utility class which provides various helper methods for working with YANG
+ * built-in types.
+ *
+ * @deprecated Use {@link BaseTypes} instead.
+ */
+@Deprecated
public final class YangTypesConverter {
- private static final Set<String> BASE_YANG_TYPES = new HashSet<String>();
-
/**
* It isn't desirable to create the instances of this class
*/
private YangTypesConverter() {
}
- static {
- BASE_YANG_TYPES.add("binary");
- BASE_YANG_TYPES.add("bits");
- BASE_YANG_TYPES.add("boolean");
- BASE_YANG_TYPES.add("decimal64");
- BASE_YANG_TYPES.add("empty");
- BASE_YANG_TYPES.add("enumeration");
- BASE_YANG_TYPES.add("identityref");
- BASE_YANG_TYPES.add("instance-identifier");
- BASE_YANG_TYPES.add("int8");
- BASE_YANG_TYPES.add("int16");
- BASE_YANG_TYPES.add("int32");
- BASE_YANG_TYPES.add("int64");
- BASE_YANG_TYPES.add("leafref");
- BASE_YANG_TYPES.add("string");
- BASE_YANG_TYPES.add("uint8");
- BASE_YANG_TYPES.add("uint16");
- BASE_YANG_TYPES.add("uint32");
- BASE_YANG_TYPES.add("uint64");
- BASE_YANG_TYPES.add("union");
- }
-
- public static boolean isBaseYangType(String type) {
- return BASE_YANG_TYPES.contains(type);
+ @Deprecated
+ public static boolean isBaseYangType(final String type) {
+ return BaseTypes.isYangBuildInType(type);
}
- public static TypeDefinition<?> javaTypeForBaseYangType(String typeName) {
- TypeDefinition<?> type = null;
-
- if (typeName.startsWith("int")) {
- if ("int8".equals(typeName)) {
- type = Int8.getInstance();
- } else if ("int16".equals(typeName)) {
- type = Int16.getInstance();
- } else if ("int32".equals(typeName)) {
- type = Int32.getInstance();
- } else if ("int64".equals(typeName)) {
- type = Int64.getInstance();
- }
- } else if (typeName.startsWith("uint")) {
- if ("uint8".equals(typeName)) {
- type = Uint8.getInstance();
- } else if ("uint16".equals(typeName)) {
- type = Uint16.getInstance();
- } else if ("uint32".equals(typeName)) {
- type = Uint32.getInstance();
- } else if ("uint64".equals(typeName)) {
- type = Uint64.getInstance();
- }
- } else if ("string".equals(typeName)) {
- type = StringType.getInstance();
- } else if ("binary".equals(typeName)) {
- type = BinaryType.getInstance();
- } else if ("boolean".equals(typeName)) {
- type = BooleanType.getInstance();
- } else if ("empty".equals(typeName)) {
- type = EmptyType.getInstance();
- } else if ("instance-identifier".equals(typeName)) {
- // FIXME
- type = new InstanceIdentifier(null, true);
- }
-
- return type;
+ /**
+ *
+ * Returns default instance of built-in type for supplied string.
+ *
+ * @param typeName
+ * @return default instance of built-in type for supplied string or null, if
+ * default instance does not exist.
+ *
+ * @deprecated Use {@link BaseTypes#defaultBaseTypeFor(String)} instead.
+ */
+ @Deprecated
+ public static TypeDefinition<?> javaTypeForBaseYangType(final String typeName) {
+ return BaseTypes.defaultBaseTypeFor(typeName).orNull();
}
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+/**
+ * Utility classes and implementations for concepts defined in yang-model-api.
+ *
+ *
+ * <h2>Base Types</h2>
+ *
+ * YANG specification defines several base types, for which YANG model does not
+ * exists, but have same properties as derived types. This package provides
+ * implementation of {@link org.opendaylight.yangtools.yang.model.api.TypeDefinition}
+ * interface and it's subinterfaces which represent YANG base types and
+ * types derived from them.
+ * <p>
+ * YANG Specification implicitly defines two types of base types - ones with default version,
+ * and ones which needs to be derived.
+ *
+ * <h3>Base built-in types with default instance and semantics</h3>
+ *
+ * <dl>
+ * <dt>empty</dt>
+ * <dd>A leaf that does not have any value - {@link org.opendaylight.yangtools.yang.model.util.EmptyType}</dd>
+ * <dt>binary</dt>
+ * <dd>Any binary data - {@link org.opendaylight.yangtools.yang.model.util.BinaryType}
+ * <dt>boolean</dt>
+ * <dd>"true" or "false" - {@link org.opendaylight.yangtools.yang.model.util.BinaryType}</dd>
+ * <dt>int8</dt>
+ * <dd>8-bit signed integer - {@link org.opendaylight.yangtools.yang.model.util.Int8}</dd>
+ * <dt>int16</dt>
+ * <dd>16-bit signed integer - {@link org.opendaylight.yangtools.yang.model.util.Int16}</dd>
+ * <dt>int32</dt>
+ * <dd>32-bit signed integer - {@link org.opendaylight.yangtools.yang.model.util.Int32}</dd>
+ * <dt>int64</dt>
+ * <dd>64-bit signed integer - {@link org.opendaylight.yangtools.yang.model.util.Int64}</dd>
+ * <dt>uint8</dt>
+ * <dd>8-bit unsigned integer -{@link org.opendaylight.yangtools.yang.model.util.Uint8}</dd>
+ * <dt>uint16</dt>
+ * <dd>16-bit unsigned integer - {@link org.opendaylight.yangtools.yang.model.util.Int16}</dd>
+ * <dt>uint32</dt>
+ * <dd>32-bit unsigned integer - {@link org.opendaylight.yangtools.yang.model.util.Int32}</dd>
+ * <dt>uint64</dt>
+ * <dd>64-bit unsigned integer -{@link org.opendaylight.yangtools.yang.model.util.Int64}</dd>
+ * <dt>instance-identifier</dt>
+ * <dd>References a data tree node - {@link org.opendaylight.yangtools.yang.model.util.InstanceIdentifier}</dd>
+ * <dt>string</dt>
+ * <dd>{@link org.opendaylight.yangtools.yang.model.util.StringType}</dd>
+ * </dl>
+ *
+ * Common trait of base types with default instance is, that there is no requirement
+ * for user input in YANG schema to further modify this types.
+ * <p>
+ * The implementation classes for these base types contains static method <code>getInstance()</code>
+ * which provides reusable {@link org.opendaylight.yangtools.concepts.Immutable} instance of type.
+ *
+ * <h3>Base built-in types without default instance</h3>
+ *
+ * <dl>
+ * <dt>bits</dt>
+ * <dd>A set of bits or flags - {@link org.opendaylight.yangtools.yang.model.util.BitsType}</dd>
+ * <dt>decimal64</dt>
+ * <dd>64-bit signed decimal number - {@link org.opendaylight.yangtools.yang.model.util.Decimal64}</dd>
+ * <dt>enumeration</dt>
+ * <dd>Enumerated strings - {@link org.opendaylight.yangtools.yang.model.util.EnumerationType}</dd>
+ * <dt>union</dt>
+ * <dd>Choice of member types - {@link org.opendaylight.yangtools.yang.model.util.UnionType}</dd>
+ * <dt>identity-ref</dt>
+ * <dd>A reference to an abstract identity - {@link org.opendaylight.yangtools.yang.model.util.IdentityrefType}</dd>
+ * <dt>leafref</dt>
+ * <dd>A reference to a leaf instance - {@link org.opendaylight.yangtools.yang.model.util.Leafref}</dd>
+ * </dl>
+ *
+ * Common trait of these base types without default instance is, that they require
+ * user input in YANG schema to create instance of this types, and may have infinity number of
+ * possible permutations.
+ * <p>
+ * The implementations have static factory method <code>create(SchemaPath,...)</code>
+ * which provides {@link org.opendaylight.yangtools.concepts.Immutable} instance of type.
+ *
+ */
+package org.opendaylight.yangtools.yang.model.util;
\ No newline at end of file
package org.opendaylight.yangtools.yang.model.util.repo;
import org.opendaylight.yangtools.concepts.Delegator;
+
+import com.google.common.annotations.Beta;
import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
-import static com.google.common.base.Preconditions.*;
+/**
+ *
+ * Abstract caching schema provider with support of multiple context
+ * per backing {@link SchemaSourceProvider}.
+ *
+ * @param <I> Input Schema Source Representation
+ * @param <O> Output Schema Source Representation
+ */
public abstract class AbstractCachingSchemaSourceProvider<I, O> implements AdvancedSchemaSourceProvider<O>,
Delegator<AdvancedSchemaSourceProvider<I>> {
- public class CompatibilitySchemaSourceProviderInstance implements SchemaSourceProvider<O> {
-
- @Override
- public Optional<O> getSchemaSource(String moduleName, Optional<String> revision) {
- // TODO Auto-generated method stub
- return null;
- }
-
- }
-
private final AdvancedSchemaSourceProvider<I> defaultDelegate;
- protected AbstractCachingSchemaSourceProvider(AdvancedSchemaSourceProvider<I> delegate) {
+ /**
+ * Construct caching schema source provider with supplied delegate.
+ *
+ * Default delegate is is used to retrieve schema source when cache does not
+ * contain requested sources.
+ *
+ * @param delegate SchemaSourceProvided used to look up and retrieve schema source
+ * when cache does not contain requested sources.
+ */
+ protected AbstractCachingSchemaSourceProvider(final AdvancedSchemaSourceProvider<I> delegate) {
this.defaultDelegate = delegate;
}
@Override
- public Optional<O> getSchemaSource(String moduleName, Optional<String> revision) {
- checkNotNull(moduleName, "Module name should not be null.");
- checkNotNull(revision, "Revision should not be null");
+ public Optional<O> getSchemaSource(final String moduleName, final Optional<String> revision) {
+ Preconditions.checkNotNull(moduleName, "Module name should not be null.");
+ Preconditions.checkNotNull(revision, "Revision should not be null");
return getSchemaSource(SourceIdentifier.create(moduleName, revision));
}
-
+
@Override
- public Optional<O> getSchemaSource(SourceIdentifier sourceIdentifier) {
+ public Optional<O> getSchemaSource(final SourceIdentifier sourceIdentifier) {
return getSchemaSourceImpl(sourceIdentifier, defaultDelegate);
}
- protected final Optional<O> getSchemaSourceImpl(SourceIdentifier identifier,
- AdvancedSchemaSourceProvider<I> delegate) {
- checkNotNull(identifier, "Source identifier name should not be null.");
+ /**
+ * Actual implementation of schema source retrieval.
+ *
+ * <ul>
+ * <li>look up cached schema source via {@link #getCachedSchemaSource(SourceIdentifier)}
+ * <li>If source was found in cache, returns source to client code.
+ * <li>If source was not found in cache, Look up schema source in supplied <code>delegate</code>
+ * <li>Updates cache with schema from delegate by {@link #cacheSchemaSource(SourceIdentifier, Optional)}
+ * <li>Result is returned to client code.
+ * </ul>
+ *
+ * @param identifier Source identifier
+ * @param delegate Delegate to lookup if there is a miss.
+ * @return Optional of schema source, present if source was found. Absent otherwise.
+ */
+ protected final Optional<O> getSchemaSourceImpl(final SourceIdentifier identifier,
+ final AdvancedSchemaSourceProvider<I> delegate) {
+ Preconditions.checkNotNull(identifier, "Source identifier name should not be null.");
Optional<O> cached = getCachedSchemaSource(identifier);
if (cached.isPresent()) {
return cacheSchemaSource(identifier, live);
}
- abstract protected Optional<O> cacheSchemaSource(SourceIdentifier identifier, Optional<I> stream);
-
+ /**
+ * Caches supplied result and returns cached result which should be returned to client.
+ *
+ * <p>
+ * Implementations of cache are required to cache schema source if possible.
+ * They are not required to cache {@link Optional#absent()}.
+ *
+ * Implementations are required to transform source representation if <code>O</code> and <code>I</code>
+ * are different.
+ *
+ * This method SHOULD NOT fail and should recover from Runtime exceptions
+ * by not caching source and only transforming it.
+ *
+ * @param identifier Source Identifier for which schema SHOULD be cached
+ * @param input Optional of schema source, representing one returned from delegate.
+ * @return Optional of schema source, representing result returned from this cache.
+ */
+ abstract protected Optional<O> cacheSchemaSource(SourceIdentifier identifier, Optional<I> input);
+
+ /**
+ * Returns cached schema source of {@link Optional#absent()} if source is not present in cache.
+ *
+ * <p>
+ * Implementations of cache MUST return cached schema source, if it is present in cache,
+ * otherwise source will be requested from deleate and then cache will be updated
+ * via {@link #cacheSchemaSource(SourceIdentifier, Optional)}.
+ *
+ * @param identifier Source Identifier for which schema should be retrieved.
+ * @return Cached schema source.
+ */
abstract protected Optional<O> getCachedSchemaSource(SourceIdentifier identifier);
+ @Override
public AdvancedSchemaSourceProvider<I> getDelegate() {
return defaultDelegate;
}
- public SchemaSourceProvider<O> createInstanceFor(SchemaSourceProvider<I> delegate) {
- checkNotNull(delegate, "Delegate should not be null");
+ /**
+ * Creates an lightweight instance of source provider, which uses this cache for caching
+ * and supplied additional delegate for lookup of not cached sources.
+ * <p>
+ *
+ * @param delegate Backing {@link SchemaSourceProvider} which should be used for lookup
+ * for sources not present in schema.
+ * @return new instance of {@link SchemaSourceProvider} which first lookup in cache
+ * and then in delegate.
+ *
+ */
+ @Beta
+ public SchemaSourceProvider<O> createInstanceFor(final SchemaSourceProvider<I> delegate) {
return new SchemaSourceProviderInstance(SchemaSourceProviders.toAdvancedSchemaSourceProvider(delegate));
-
+
}
+ /**
+ *
+ * Lightweight instance of source provider, which is associated with parent
+ * {@link AbstractCachingSchemaSourceProvider}, but uses
+ * different delegate for retrieving not cached sources.
+ *
+ */
+ @Beta
private class SchemaSourceProviderInstance implements //
- AdvancedSchemaSourceProvider<O>,
+ AdvancedSchemaSourceProvider<O>,
Delegator<AdvancedSchemaSourceProvider<I>> {
private final AdvancedSchemaSourceProvider<I> delegate;
- protected SchemaSourceProviderInstance(AdvancedSchemaSourceProvider<I> delegate) {
+ protected SchemaSourceProviderInstance(final AdvancedSchemaSourceProvider<I> delegate) {
super();
- this.delegate = delegate;
+ this.delegate = Preconditions.checkNotNull(delegate, "Delegate should not be null");;
}
@Override
- public Optional<O> getSchemaSource(String moduleName, Optional<String> revision) {
+ public Optional<O> getSchemaSource(final String moduleName, final Optional<String> revision) {
return getSchemaSource(SourceIdentifier.create(moduleName, revision));
}
}
@Override
- public Optional<O> getSchemaSource(SourceIdentifier sourceIdentifier) {
+ public Optional<O> getSchemaSource(final SourceIdentifier sourceIdentifier) {
return getSchemaSourceImpl(sourceIdentifier, getDelegate());
}
}
import com.google.common.base.Optional;
-public interface AdvancedSchemaSourceProvider<F> extends SchemaSourceProvider<F> {
+/**
+ * Provider of representation of YANG schema sources.
+ *
+ * <p>
+ * {@link AdvancedSchemaSourceProvider} is extension of
+ * {@link SchemaSourceProvider} which did not have object concept of source
+ * identifier, and introduces {@link SourceIdentifier} (which contains schema
+ * name and revision) as identifier of sources.
+ *
+ * <p>
+ * <b>Schema Source representation</b>
+ * <p>
+ * Representation of schema source. Representation of schema source could exists
+ * in various formats (Java types), depending on stage of processing, but
+ * representation MUST BE still result of processing of only single unit of schema
+ * source (file, input stream). E.g.:
+ * <ul>
+ * <li>{@link java.lang.String} - textual representation of source code
+ * <li>{@link java.io.InputStream} - input stream containing source code
+ * <li>{@link com.google.common.io.ByteSource} - source for input streams
+ * containing source code
+ * <li>Parsed AST - abstract syntax tree, which is result of a parser, but still
+ * it is not linked against other schemas.
+ *
+ * <p>
+ * Conversion between representations should be done via implementations of
+ * {@link SchemaSourceTransformation}.
+ *
+ * @param <T>
+ * Schema source representation type provided by this implementation
+ */
+public interface AdvancedSchemaSourceProvider<T> extends SchemaSourceProvider<T> {
- Optional<F> getSchemaSource(SourceIdentifier sourceIdentifier);
+ /**
+ * Returns representation source for supplied YANG source identifier.
+ *
+ * Returned representation of schema source must be immutable, must not
+ * change during runtime if {@link SourceIdentifier} has specified both
+ * {@link SourceIdentifier#getName()} and
+ * {@link SourceIdentifier#getRevision()}
+ *
+ * @param sourceIdentifier
+ * source identifier.
+ * @return source representation if supplied YANG module is available
+ * {@link Optional#absent()} otherwise.
+ */
+ Optional<T> getSchemaSource(SourceIdentifier sourceIdentifier);
}
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
-public class FilesystemSchemaCachingProvider<I> extends AbstractCachingSchemaSourceProvider<I, InputStream> {
+/**
+ * Filesystem-based schema caching source provider
+ *
+ * This schema source provider caches all YANG modules loaded from backing
+ * schema source providers (registered via
+ * {@link #createInstanceFor(SchemaSourceProvider)} to supplied folder.
+ *
+ * @param <I>
+ * Input format in which schema source is represented.
+ *
+ */
+public final class FilesystemSchemaCachingProvider<I> extends AbstractCachingSchemaSourceProvider<I, InputStream> {
private static final Logger LOG = LoggerFactory.getLogger(FilesystemSchemaCachingProvider.class);
private final File storageDirectory;
- private final Function<I, String> transformationFunction;
+ private final SchemaSourceTransformation<I, String> transformationFunction;
+
+ /**
+ *
+ * Construct filesystem caching schema source provider.
+ *
+ *
+ * @param delegate
+ * Default delegate to lookup for missed entries in cache.
+ * @param directory
+ * Directory where YANG files should be cached.
+ * @param transformationFunction
+ * Transformation function which translates from input in format
+ * <code>I</code> to InputStream.
+ * @throws IllegalArgumentException
+ * If supplied directory does not exists or is not directory.
+ */
+ public FilesystemSchemaCachingProvider(final AdvancedSchemaSourceProvider<I> delegate, final File directory,
+ final SchemaSourceTransformation<I, String> transformationFunction) {
+ super(delegate);
+ Preconditions.checkNotNull(directory, "directory must not be null.");
+ Preconditions.checkArgument(directory.exists(), "directory must be directory.");
+ Preconditions.checkArgument(directory.isDirectory(), "directory must be directory.");
+ this.storageDirectory = directory;
+ this.transformationFunction = Preconditions.checkNotNull(transformationFunction,
+ "transformationFunction must not be null.");
+ }
+ /**
+ *
+ * Construct filesystem caching schema source provider.
+ *
+ *
+ * @param delegate
+ * Default delegate to lookup for missed entries in cache.
+ * @param directory
+ * Directory where YANG files should be cached.
+ * @param transformationFunction
+ * Transformation function which translates from input in format
+ * <code>I</code> to InputStream.
+ * @throws IllegalArgumentException
+ * If supplied directory does not exists or is not directory.
+ * @deprecated Use
+ * {@link #FilesystemSchemaCachingProvider(AdvancedSchemaSourceProvider, File, SchemaSourceTransformation)}
+ * with
+ * {@link SchemaSourceProviders#schemaSourceTransformationFrom(Function)}
+ * instead.
+ */
+ @Deprecated
public FilesystemSchemaCachingProvider(final AdvancedSchemaSourceProvider<I> delegate, final File directory,
final Function<I, String> transformationFunction) {
super(delegate);
+ Preconditions.checkNotNull(directory, "directory must not be null.");
+ Preconditions.checkArgument(directory.exists(), "directory must be directory.");
+ Preconditions.checkArgument(directory.isDirectory(), "directory must be directory.");
this.storageDirectory = directory;
- this.transformationFunction = transformationFunction;
+ this.transformationFunction = SchemaSourceProviders.schemaSourceTransformationFrom(transformationFunction);
}
@Override
- protected synchronized Optional<InputStream> cacheSchemaSource(final SourceIdentifier identifier, final Optional<I> source) {
+ protected synchronized Optional<InputStream> cacheSchemaSource(final SourceIdentifier identifier,
+ final Optional<I> source) {
File schemaFile = toFile(identifier);
try {
if (source.isPresent() && schemaFile.createNewFile()) {
writer.write(transformToString(source.get()));
writer.flush();
} catch (IOException e) {
-
+ LOG.warn("Could not chache source for {}. Source: ",identifier,source.get(),e);
}
}
} catch (IOException e) {
-
+ LOG.warn("Could not create cache file for {}. File: ",identifier,schemaFile,e);
}
return transformToStream(source);
}
private Optional<InputStream> transformToStream(final Optional<I> source) {
if (source.isPresent()) {
- return Optional.<InputStream> of(
- new ByteArrayInputStream(transformToString(source.get()).getBytes(Charsets.UTF_8)));
+ return Optional.<InputStream> of(new ByteArrayInputStream(transformToString(source.get()).getBytes(
+ Charsets.UTF_8)));
}
return Optional.absent();
}
private String transformToString(final I input) {
- return transformationFunction.apply(input);
+ return transformationFunction.transform(input);
}
@Override
private File findFileWithNewestRev(final SourceIdentifier identifier) {
File[] files = storageDirectory.listFiles(new FilenameFilter() {
final String regex = identifier.getName() + "(\\.yang|@\\d\\d\\d\\d-\\d\\d-\\d\\d.yang)";
+
@Override
public boolean accept(final File dir, final String name) {
if (name.matches(regex)) {
return file;
}
- private static final Function<String, String> NOOP_TRANSFORMATION = new Function<String, String>() {
- @Override
- public String apply(final String input) {
- return input;
- }
- };
-
public static FilesystemSchemaCachingProvider<String> createFromStringSourceProvider(
final SchemaSourceProvider<String> liveProvider, final File directory) {
Preconditions.checkNotNull(liveProvider);
return new FilesystemSchemaCachingProvider<String>(
SchemaSourceProviders.toAdvancedSchemaSourceProvider(liveProvider),//
directory, //
- NOOP_TRANSFORMATION);
+ SchemaSourceProviders.<String>identityTransformation());
}
}
package org.opendaylight.yangtools.yang.model.util.repo;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextHolder;
+
+/**
+ * Represent Schema Service.
+ *
+ *
+ * @deprecated Replaced by {@link SchemaContextHolder}, which provides
+ * component-local view for actual {@link SchemaContext}.
+ */
+@Deprecated
public interface SchemaService {
-
SchemaContext getSchemaContext();
}
import com.google.common.base.Optional;
+/**
+ * Provider of text stream representation of YANG Modules
+ *
+ * Provider is holder / user implemented service, which
+ * may be able to retrieve representation of YANG sources
+ * for other components.
+ *
+ * @param <F> Format in which YANG source is represented.
+ */
public interface SchemaSourceProvider<F> {
+ /**
+ * Returns source for supplied YANG module identifier and revision.
+ *
+ * @param moduleName module name
+ * @param revision revision of module
+ * @return source representation if supplied YANG module is available
+ * {@link Optional#absent()} otherwise.
+ * @deprecated Use {@link AdvancedSchemaSourceProvider#getSchemaSource(SourceIdentifier)}
+ * instead.
+ */
+ @Deprecated
Optional<F> getSchemaSource(String moduleName, Optional<String> revision);
}
*/
package org.opendaylight.yangtools.yang.model.util.repo;
+import java.io.ByteArrayInputStream;
import java.io.InputStream;
-import java.io.StringBufferInputStream;
import org.opendaylight.yangtools.concepts.Delegator;
+import com.google.common.base.Charsets;
+import com.google.common.base.Function;
import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
-public class SchemaSourceProviders {
+/**
+ *
+ * Utility functions for {@link SchemaSourceProvider}
+ *
+ */
+public final class SchemaSourceProviders {
@SuppressWarnings("rawtypes")
private static final SchemaSourceProvider NOOP_PROVIDER = new AdvancedSchemaSourceProvider() {
@Override
- public Optional getSchemaSource(String moduleName, Optional revision) {
+ public Optional getSchemaSource(final String moduleName, final Optional revision) {
return Optional.absent();
}
@Override
- public Optional getSchemaSource(SourceIdentifier sourceIdentifier) {
+ public Optional getSchemaSource(final SourceIdentifier sourceIdentifier) {
return Optional.absent();
}
};
+ @SuppressWarnings("rawtypes")
+ private static final SchemaSourceTransformation IDENTITY_TRANFORMATION = new IdentityTransformation();
+
+ private static final StringToInputStreamTransformation STRING_TO_INPUTSTREAM_TRANSFORMATION = new StringToInputStreamTransformation();
+
+ private SchemaSourceProviders() {
+ throw new UnsupportedOperationException("Utility class.");
+ }
+
+ /**
+ * Returns a noop schema source provider.
+ *
+ * Noop schema provider returns {@link Optional#absent()} for each call to
+ * query schema source.
+ *
+ * @return
+ */
@SuppressWarnings("unchecked")
public static <T> SchemaSourceProvider<T> noopProvider() {
- return (SchemaSourceProvider<T>) NOOP_PROVIDER;
+ return NOOP_PROVIDER;
}
+ /**
+ *
+ * Returns delegating schema source provider which returns InputStream from
+ * supplied String based schema source provider.
+ *
+ * @param delegate
+ * @return
+ */
public static SchemaSourceProvider<InputStream> inputStreamProviderfromStringProvider(
- AdvancedSchemaSourceProvider<String> delegate) {
- return new StringToInputStreamSchemaSourceProvider(delegate);
+ final AdvancedSchemaSourceProvider<String> delegate) {
+ return TransformingSourceProvider.create(delegate, STRING_TO_INPUTSTREAM_TRANSFORMATION);
}
- public static <O> AdvancedSchemaSourceProvider<O> toAdvancedSchemaSourceProvider(SchemaSourceProvider<O> schemaSourceProvider) {
+ /**
+ * Returns identity implementation of SchemaSourceTransformation
+ *
+ * Identity implementation of SchemaSourceTransformation is useful
+ * for usecases where Input and Output of SchemaSourceTransformation
+ * are identitcal, and you want to reuse input as an output.
+ *
+ * This implementation is really simple <code>return input;</code>.
+ *
+ * @return
+ */
+ @SuppressWarnings("unchecked")
+ public static <I> SchemaSourceTransformation<I, I> identityTransformation() {
+ return IDENTITY_TRANFORMATION;
+ }
+
+ public static <I, O> SchemaSourceTransformation<I, O> schemaSourceTransformationFrom(
+ final Function<I, O> transformation) {
+ return new FunctionBasedSchemaSourceTransformation<I, O>(transformation);
+ }
+
+ /**
+ *
+ * Casts {@link SchemaSourceProvider} to
+ * {@link AdvancedSchemaSourceProvider} or wraps it with utility
+ * implementation if supplied delegate does not implement
+ * {@link AdvancedSchemaSourceProvider}.
+ *
+ * @param schemaSourceProvider
+ */
+ public static <O> AdvancedSchemaSourceProvider<O> toAdvancedSchemaSourceProvider(
+ final SchemaSourceProvider<O> schemaSourceProvider) {
if (schemaSourceProvider instanceof AdvancedSchemaSourceProvider<?>) {
return (AdvancedSchemaSourceProvider<O>) schemaSourceProvider;
}
return new SchemaSourceCompatibilityWrapper<O>(schemaSourceProvider);
}
- private final static class StringToInputStreamSchemaSourceProvider implements //
- AdvancedSchemaSourceProvider<InputStream>, Delegator<AdvancedSchemaSourceProvider<String>> {
+ private static final class FunctionBasedSchemaSourceTransformation<I, O> implements
+ SchemaSourceTransformation<I, O> {
- private AdvancedSchemaSourceProvider<String> delegate;
- public StringToInputStreamSchemaSourceProvider(AdvancedSchemaSourceProvider<String> delegate) {
- this.delegate = delegate;
- }
+ private final Function<I, O> delegate;
- @Override
- public AdvancedSchemaSourceProvider<String> getDelegate() {
- return delegate;
+ protected FunctionBasedSchemaSourceTransformation(final Function<I, O> delegate) {
+ super();
+ this.delegate = Preconditions.checkNotNull(delegate, "delegate MUST NOT be null.");
}
@Override
- public Optional<InputStream> getSchemaSource(SourceIdentifier sourceIdentifier) {
- Optional<String> potentialSource = getDelegate().getSchemaSource(sourceIdentifier);
- if (potentialSource.isPresent()) {
- String stringSource = potentialSource.get();
- @SuppressWarnings("deprecation")
- StringBufferInputStream stringInputStream = new StringBufferInputStream(stringSource);
- return Optional.<InputStream> of(stringInputStream);
- }
- return Optional.absent();
+ public O transform(final I input) {
+ return delegate.apply(input);
}
@Override
- public Optional<InputStream> getSchemaSource(String moduleName, Optional<String> revision) {
- return getSchemaSource(SourceIdentifier.create(moduleName, revision));
+ public String toString() {
+ return "FunctionBasedSchemaSourceTransformation [delegate=" + delegate + "]";
}
}
private final SchemaSourceProvider<O> delegate;
- public SchemaSourceCompatibilityWrapper(SchemaSourceProvider<O> delegate) {
+ public SchemaSourceCompatibilityWrapper(final SchemaSourceProvider<O> delegate) {
this.delegate = delegate;
}
public SchemaSourceProvider<O> getDelegate() {
return delegate;
}
-
+
+
+ /*
+ * Deprecation warnings are suppresed, since this implementation
+ * needs to invoke deprecated method in order to provide
+ * implementation of non-deprecated APIs using legacy ones.
+ *
+ * (non-Javadoc)
+ * @see org.opendaylight.yangtools.yang.model.util.repo.AdvancedSchemaSourceProvider#getSchemaSource(org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier)
+ */
+ @SuppressWarnings("deprecation")
@Override
- public Optional<O> getSchemaSource(SourceIdentifier sourceIdentifier) {
-
+ public Optional<O> getSchemaSource(final SourceIdentifier sourceIdentifier) {
+
final String moduleName = sourceIdentifier.getName();
Optional<String> revision = Optional.fromNullable(sourceIdentifier.getRevision());
return delegate.getSchemaSource(moduleName, revision);
}
-
+
+ /*
+ * Deprecation warnings are suppresed, since this implementation
+ * needs to invoke deprecated method in order to provide
+ * implementation of non-deprecated APIs using legacy ones.
+ *
+ * (non-Javadoc)
+ * @see org.opendaylight.yangtools.yang.model.util.repo.AdvancedSchemaSourceProvider#getSchemaSource(org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier)
+ */
@Override
- public Optional<O> getSchemaSource(String moduleName, Optional<String> revision) {
+ @SuppressWarnings("deprecation")
+ public Optional<O> getSchemaSource(final String moduleName, final Optional<String> revision) {
return delegate.getSchemaSource(moduleName, revision);
}
}
+ @SuppressWarnings("rawtypes")
+ private static class IdentityTransformation implements SchemaSourceTransformation {
+
+ @Override
+ public Object transform(final Object input) {
+ return input;
+ }
+ }
+
+ private static class StringToInputStreamTransformation implements SchemaSourceTransformation<String, InputStream> {
+
+ @Override
+ public InputStream transform(final String input) {
+ return new ByteArrayInputStream(input.getBytes(Charsets.UTF_8));
+ }
+
+ }
+
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/eplv10.html
+ */
+package org.opendaylight.yangtools.yang.model.util.repo;
+
+import com.google.common.annotations.Beta;
+
+/**
+ *
+ * Schema Source Transformation which transforms from one schema source
+ * representation to another.
+ *
+ * <p>
+ * <b>Representation of Schema Source</b>
+ * <p>
+ * Schema source may be represented by
+ * various Java Types, which depends on provider and/or consumer.
+ * <p>
+ * E.g example of possible representations:
+ * <ul>
+ * <li>{@link String}
+ * <li>{@link java.io.InputStream}
+ * <li>{@link com.google.common.io.ByteSource}
+ * </ul>
+ *
+ * FIXME: <b>Beta:</b> Consider allowing transformations, which may
+ * fail to produce Output, this will require introduction of
+ * checked exception.
+ *
+ * @param <I> Input schema source representation
+ * @param <O> Output schema source representation
+ */
+@Beta
+public interface SchemaSourceTransformation<I, O> {
+
+ /**
+ *
+ * Transforms supplied schema source in format <code>I</code> to schema
+ * source in format <code>O</code>.
+ *
+ * <ul>
+ * <li>Its execution does not cause any observable side effects.
+ * <li>If the contents of a,b are semantically same (e.g. contents of InputStream),
+ * output representations MUST BE also semantically equals.
+ * </ul>
+ *
+ * Implementations of transformation SHOULD NOT fail to
+ * transform valid non-null input to output representation.
+ *
+ *
+ * FIXME: <b>Beta:</b> Consider lowering condition for safe transformation
+ * and introduce checked exception for cases when transformation may fail.
+ *
+ * @param input Not null input which should be transformed
+ * @return Representation of input in <code>O</code> format.
+ * @throws NullPointerException if input is null.
+ *
+ */
+ @Beta
+ O transform(I input);
+}
*/
package org.opendaylight.yangtools.yang.model.util.repo;
+import org.opendaylight.yangtools.concepts.Immutable;
+
import com.google.common.base.Optional;
-public final class SourceIdentifier {
+/**
+ *
+ * YANG Schema source identifier
+ *
+ * Simple transfer object represents identifier of source for YANG schema (module or submodule),
+ * which consists of
+ * <ul>
+ * <li>YANG schema name ({@link #getName()}
+ * <li>Module revision (optional) ({link {@link #getRevision()})
+ * </ul>
+ *
+ * Source identifier is designated to be carry only necessary information
+ * to look-up YANG model source and to be used by {@link AdvancedSchemaSourceProvider}
+ * and similar.
+ *
+ * <b>Note:</b>On source retrieval layer it is impossible to distinguish
+ * between YANG module and/or submodule unless source is present.
+ *
+ * <p>
+ * (For further reference see: http://tools.ietf.org/html/rfc6020#section-5.2 and
+ * http://tools.ietf.org/html/rfc6022#section-3.1 ).
+ *
+ *
+ */
+public final class SourceIdentifier implements Immutable {
private final String name;
private final String revision;
+ /**
+ *
+ * Creates new YANG Schema source identifier.
+ *
+ * @param name Name of schema
+ * @param formattedRevision Revision of source in format YYYY-mm-dd
+ */
public SourceIdentifier(final String name, final Optional<String> formattedRevision) {
super();
this.name = name;
this.revision = formattedRevision.orNull();
}
+ /**
+ * Returns model name
+ *
+ * @return model name
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * Returns revision of source or null if revision was not supplied.
+ *
+ * @return revision of source or null if revision was not supplied.
+ */
+ public String getRevision() {
+ return revision;
+ }
+
@Override
public int hashCode() {
final int prime = 31;
return true;
}
- public String getName() {
- return name;
- }
-
- public String getRevision() {
- return revision;
- }
-
public static SourceIdentifier create(final String moduleName, final Optional<String> revision) {
return new SourceIdentifier(moduleName, revision);
}
+ /**
+ * Returns filename for this YANG module as specified in RFC 6020.
+ *
+ * Returns filename in format
+ * <code>name ['@' revision] '.yang'</code>
+ * <p>
+ * Where revision is date in format YYYY-mm-dd.
+ * <p>
+ * See
+ * http://tools.ietf.org/html/rfc6020#section-5.2
+ *
+ * @return Filename for this source identifier.
+ */
public String toYangFilename() {
return toYangFileName(name, Optional.fromNullable(revision));
}
return "SourceIdentifier [name=" + name + "@" + revision + "]";
}
+ /**
+ * Returns filename for this YANG module as specified in RFC 6020.
+ *
+ * Returns filename in format
+ * <code>moduleName ['@' revision] '.yang'</code>
+ *
+ * Where Where revision-date is in format YYYY-mm-dd.
+ *
+ * <p>
+ * See
+ * http://tools.ietf.org/html/rfc6020#section-5.2
+ *
+ * @return Filename for this source identifier.
+ */
public static final String toYangFileName(final String moduleName, final Optional<String> revision) {
StringBuilder filename = new StringBuilder(moduleName);
if (revision.isPresent()) {
--- /dev/null
+package org.opendaylight.yangtools.yang.model.util.repo;
+
+import org.opendaylight.yangtools.concepts.Delegator;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+
+/**
+ *
+ * Utility Source Provider implementation which uses delegate to retrieve
+ * sources and transformation function to convert sources to different
+ * representation.
+ *
+ *
+ * @param <I>
+ * Representation of schema sources used by delegate
+ * @param <O>
+ * Representation of schema sources exposed by this provider
+ */
+public final class TransformingSourceProvider<I, O> implements //
+ AdvancedSchemaSourceProvider<O>, Delegator<AdvancedSchemaSourceProvider<I>> {
+
+ private final AdvancedSchemaSourceProvider<I> delegate;
+ private final SchemaSourceTransformation<I, O> transformation;
+
+ /**
+ * Creates instance of transforming schema source provider which uses
+ * supplied delegate to retrieve sources and transformation to change
+ * sources to different representation.
+ *
+ * @param delegate
+ * Delegate which provides sources.
+ * @param transformation
+ * Transformation function which converts sources
+ * @return Instance of TransformingSourceProvider
+ * @throws NullPointerException
+ * if any of arguments is null.
+ */
+ public static final <I, O> TransformingSourceProvider<I, O> create(final AdvancedSchemaSourceProvider<I> delegate,
+ final SchemaSourceTransformation<I, O> transformation) {
+ return new TransformingSourceProvider<>(delegate, transformation);
+ }
+
+ private TransformingSourceProvider(final AdvancedSchemaSourceProvider<I> delegate,
+ final SchemaSourceTransformation<I, O> transformation) {
+ this.delegate = Preconditions.checkNotNull(delegate, "delegate must not be null");
+ this.transformation = Preconditions.checkNotNull(transformation, "transformation must not be null");
+ }
+
+ @Override
+ public AdvancedSchemaSourceProvider<I> getDelegate() {
+ return delegate;
+ }
+
+ @Override
+ public Optional<O> getSchemaSource(final SourceIdentifier sourceIdentifier) {
+ Optional<I> potentialSource = getDelegate().getSchemaSource(sourceIdentifier);
+ if (potentialSource.isPresent()) {
+ I inputSource = potentialSource.get();
+ return Optional.<O> of(transformation.transform(inputSource));
+ }
+ return Optional.absent();
+ }
+
+ @Override
+ public Optional<O> getSchemaSource(final String moduleName, final Optional<String> revision) {
+ return getSchemaSource(SourceIdentifier.create(moduleName, revision));
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/eplv10.html
+ */
+/**
+ * This package introduces concepts, generic interfaces and implementations for
+ * creating and working with YANG Schema source repositories and working with them.
+ *
+ * <h2>Concepts</h2>
+ * <dl>
+ * <dt>Schema Source</dt>
+ * <dd>Source of YANG Schema, which is not processed, not resolved against other schemas
+ * and from contents of <i>Schema Source</i> in combination with other Schema sources
+ * it is possible to create resolved YANG Schema context.
+ * </dd>
+ * <dt>{@link org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier}</dt>
+ * <dd>Identifier of Schema Source. Identifier is not tied with source or representation.</dd>
+ * <dt>Schema Source Representation</dt>
+ * <dd>Representation of schema source. Representation of schema source could exists in various
+ * formats (Java types), depending on stage of processing, but representation MUST BE
+ * still result of processing only single unit of schema source (e.g. file, input stream). E.g.:
+ * <ul>
+ * <li>{@link java.lang.String} - textual representation of source code
+ * <li>{@link InputStream} - input stream containing source code
+ * <li>{@link com.google.common.io.ByteSource} - source for input streams containing source code
+ * <li>Parsed AST - abstract syntax tree, which is result of a parser, but still it is not linked
+ * against other schemas.
+ * </ul>
+ * </dd>
+ * <dt>{@link org.opendaylight.yangtools.yang.model.util.repo.AdvancedSchemaSourceProvider}</dt>
+ * <dd>
+ * Service which provides query API to obtain <i>Schema Source Representation</i> associated
+ * with {@link org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier}.
+ * </dd>
+ * <dt>{@link org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceTransformation}</dt>
+ * <dd>
+ * Function (service) which provides transformation from one <i>Schema Source Representation</i>
+ * type to another.
+ * </dd>
+ * </dl>
+ *
+ *
+ */
+package org.opendaylight.yangtools.yang.model.util.repo;
\ No newline at end of file
*/
package org.opendaylight.yangtools.yang.model.parser.api;
-import com.google.common.io.ByteSource;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
+
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import com.google.common.io.ByteSource;
+
/**
* Parse yang models and convert data to SchemaContext.
*
* only module parsed from yangFile and modules which yangFile needs
* as dependencies.
*/
- SchemaContext parseFile(final File yangFile, final File dependenciesDirectory) throws IOException;
+ SchemaContext parseFile(final File yangFile, final File dependenciesDirectory) throws IOException, YangSyntaxErrorException;
/**
* Parse one or more Yang model files and return the definitions of Yang
* SchemaContext containing already parsed yang models
* @return parsed data as SchemaContext
*/
- SchemaContext parseFiles(final Collection<File> yangFiles, final SchemaContext context) throws IOException;
+ SchemaContext parseFiles(final Collection<File> yangFiles, final SchemaContext context) throws IOException, YangSyntaxErrorException;
/**
* Parse one or more Yang model streams and return the definitions of Yang
* yang streams to parse
* @return parsed data as SchemaContext
*/
- SchemaContext parseSources(final Collection<ByteSource> sources) throws IOException;
+ SchemaContext parseSources(final Collection<ByteSource> sources) throws IOException, YangSyntaxErrorException;
/**
* Parse one or more Yang model streams and return the definitions of Yang
* SchemaContext containing already parsed yang models
* @return parsed data as SchemaContext
*/
- SchemaContext parseSources(final Collection<ByteSource> sources, final SchemaContext context) throws IOException;
+ SchemaContext parseSources(final Collection<ByteSource> sources, final SchemaContext context) throws IOException, YangSyntaxErrorException;
}
*/
package org.opendaylight.yangtools.yang.model.parser.api;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.type.UnknownTypeDefinition;
-
import java.io.File;
import java.io.InputStream;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.type.UnknownTypeDefinition;
+
/**
* Yang Model Parser interface is designed for parsing yang models and convert
* the information to Data Schema Tree.
*
*/
-// refactor methods returning input streams, after introducing
+// FIXME: refactor methods returning input streams, after introducing (?)
public interface YangModelParser {
/**
/**
* Equivalent to {@link #parseYangModels(List)} that returns parsed modules
- * mapped to IputStreams from which they were parsed.
+ * mapped to InputStreams from which they were parsed.
*
* @param yangModelStreams
* yang streams to parse
--- /dev/null
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/eplv10.html
+ */
+package org.opendaylight.yangtools.yang.model.parser.api;
+
+import com.google.common.base.Preconditions;
+
+public class YangSyntaxErrorException extends Exception {
+ private static final long serialVersionUID = 1L;
+ private final String module;
+ private final int line;
+ private final int charPositionInLine;
+
+ public YangSyntaxErrorException(final String module, final int line, final int charPositionInLine,
+ final String message) {
+ this(module, line, charPositionInLine, message, null);
+ }
+
+ public YangSyntaxErrorException(final String module, final int line, final int charPositionInLine,
+ final String message, final Throwable cause) {
+ super(Preconditions.checkNotNull(message), cause);
+ this.module = module;
+ this.line = line;
+ this.charPositionInLine = charPositionInLine;
+ }
+
+ public String getModule() {
+ return module;
+ }
+
+ public int getLine() {
+ return line;
+ }
+
+ public int getCharPositionInLine() {
+ return charPositionInLine;
+ }
+
+ public String getFormattedMessage() {
+ final StringBuilder sb = new StringBuilder(getMessage());
+ if (module != null) {
+ sb.append(" in module ");
+ sb.append(module);
+ }
+ if (line != 0) {
+ sb.append(" on line ");
+ sb.append(line);
+ if (charPositionInLine != 0) {
+ sb.append(" character ");
+ sb.append(charPositionInLine);
+ }
+ }
+ return sb.toString();
+ }
+
+ @Override
+ public String toString() {
+ return this.getClass().getName() + ": " + getFormattedMessage();
+ }
+}
for (QName name : parsedPath) {
newPath.add(new QName(mb.getNamespace(), mb.getRevision(), name.getPrefix(), name.getLocalName()));
}
- instance.targetPath = new SchemaPath(newPath, false);
+ instance.targetPath = SchemaPath.create(newPath, false);
} else {
instance.targetPath = targetNodeSchemaPath;
}
}
@Override
- public void setStatus(Status status) {
+ public void setStatus(final Status status) {
this.status = Preconditions.checkNotNull(status, "status cannot be null");
}
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
+
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
private String belongsTo;
private ModuleBuilder parent;
- public ModuleBuilder getParent() {
+ @Override
+ public ModuleBuilder getParent() {
return parent;
}
- public void setParent(ModuleBuilder parent) {
+ public void setParent(final ModuleBuilder parent) {
this.parent = parent;
}
super(name, 0, null);
this.name = name;
this.sourcePath = sourcePath;
- schemaPath = new SchemaPath(Collections.<QName> emptyList(), true);
+ schemaPath = SchemaPath.create(Collections.<QName> emptyList(), true);
this.submodule = submodule;
instance = new ModuleImpl(name, sourcePath);
actualPath.push(this);
}
- public ModuleBuilder(Module base) {
+ public ModuleBuilder(final Module base) {
super(base.getName(), 0, null);
this.name = base.getName();
this.sourcePath = base.getModuleSourcePath();
- schemaPath = new SchemaPath(Collections.<QName> emptyList(), true);
+ schemaPath = SchemaPath.create(Collections.<QName> emptyList(), true);
submodule = false;
instance = new ModuleImpl(base.getName(), base.getModuleSourcePath());
instance.setYangVersion(base.getYangVersion());
}
@Override
- public void setParent(Builder parent) {
+ public void setParent(final Builder parent) {
throw new YangParseException(name, 0, "Can not set parent to module");
}
return belongsTo;
}
- public void setBelongsTo(String belongsTo) {
+ public void setBelongsTo(final String belongsTo) {
this.belongsTo = belongsTo;
}
}
@Override
- public void addUsesNode(UsesNodeBuilder usesBuilder) {
+ public void addUsesNode(final UsesNodeBuilder usesBuilder) {
addedUsesNodes.add(usesBuilder);
allUsesNodes.add(usesBuilder);
}
return outputBuilder;
}
- public void addNotification(NotificationDefinition notification) {
+ public void addNotification(final NotificationDefinition notification) {
notifications.add(notification);
}
}
@Override
- public void addTypedef(TypeDefinitionBuilder typedefBuilder) {
+ public void addTypedef(final TypeDefinitionBuilder typedefBuilder) {
String nodeName = typedefBuilder.getQName().getLocalName();
for (TypeDefinitionBuilder tdb : addedTypedefs) {
if (tdb.getQName().getLocalName().equals(nodeName)) {
return "module " + name;
}
- public void setSource(String source) {
+ public void setSource(final String source) {
this.source = source;
}
private final List<UnknownSchemaNode> unknownNodes = new ArrayList<>();
private String source;
- private ModuleImpl(String name, String sourcePath) {
+ private ModuleImpl(final String name, final String sourcePath) {
this.name = name;
this.sourcePath = sourcePath;
}
return namespace;
}
- private void setNamespace(URI namespace) {
+ private void setNamespace(final URI namespace) {
this.namespace = namespace;
}
return revision;
}
- private void setRevision(Date revision) {
+ private void setRevision(final Date revision) {
this.revision = revision;
}
return prefix;
}
- private void setPrefix(String prefix) {
+ private void setPrefix(final String prefix) {
this.prefix = prefix;
}
return yangVersion;
}
- private void setYangVersion(String yangVersion) {
+ private void setYangVersion(final String yangVersion) {
this.yangVersion = yangVersion;
}
return description;
}
- private void setDescription(String description) {
+ private void setDescription(final String description) {
this.description = description;
}
return reference;
}
- private void setReference(String reference) {
+ private void setReference(final String reference) {
this.reference = reference;
}
return organization;
}
- private void setOrganization(String organization) {
+ private void setOrganization(final String organization) {
this.organization = organization;
}
return contact;
}
- private void setContact(String contact) {
+ private void setContact(final String contact) {
this.contact = contact;
}
return imports;
}
- private void setImports(Set<ModuleImport> imports) {
+ private void setImports(final Set<ModuleImport> imports) {
if (imports != null) {
this.imports.addAll(imports);
}
return features;
}
- private void setFeatures(Set<FeatureDefinition> features) {
+ private void setFeatures(final Set<FeatureDefinition> features) {
if (features != null) {
this.features.addAll(features);
}
return typeDefinitions;
}
- private void setTypeDefinitions(Set<TypeDefinition<?>> typeDefinitions) {
+ private void setTypeDefinitions(final Set<TypeDefinition<?>> typeDefinitions) {
if (typeDefinitions != null) {
this.typeDefinitions.addAll(typeDefinitions);
}
return notifications;
}
- private void setNotifications(Set<NotificationDefinition> notifications) {
+ private void setNotifications(final Set<NotificationDefinition> notifications) {
if (notifications != null) {
this.notifications.addAll(notifications);
}
return augmentations;
}
- private void setAugmentations(Set<AugmentationSchema> augmentations) {
+ private void setAugmentations(final Set<AugmentationSchema> augmentations) {
if (augmentations != null) {
this.augmentations.addAll(augmentations);
}
return rpcs;
}
- private void setRpcs(Set<RpcDefinition> rpcs) {
+ private void setRpcs(final Set<RpcDefinition> rpcs) {
if (rpcs != null) {
this.rpcs.addAll(rpcs);
}
return deviations;
}
- private void setDeviations(Set<Deviation> deviations) {
+ private void setDeviations(final Set<Deviation> deviations) {
if (deviations != null) {
this.deviations.addAll(deviations);
}
return Collections.unmodifiableSet(childNodes);
}
- private void addChildNodes(Set<DataSchemaNode> childNodes) {
+ private void addChildNodes(final Set<DataSchemaNode> childNodes) {
if (childNodes != null) {
this.childNodes.addAll(childNodes);
}
return groupings;
}
- private void setGroupings(Set<GroupingDefinition> groupings) {
+ private void setGroupings(final Set<GroupingDefinition> groupings) {
if (groupings != null) {
this.groupings.addAll(groupings);
}
return uses;
}
- private void setUses(Set<UsesNode> uses) {
+ private void setUses(final Set<UsesNode> uses) {
if (uses != null) {
this.uses.addAll(uses);
}
}
@Override
- public DataSchemaNode getDataChildByName(QName name) {
+ public DataSchemaNode getDataChildByName(final QName name) {
return getChildNode(childNodes, name);
}
@Override
- public DataSchemaNode getDataChildByName(String name) {
+ public DataSchemaNode getDataChildByName(final String name) {
return getChildNode(childNodes, name);
}
- void setSource(String source){
+ void setSource(final String source){
this.source = source;
}
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
*/
package org.opendaylight.yangtools.yang.parser.builder.impl;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.*;
-import org.opendaylight.yangtools.yang.model.api.type.*;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.Status;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
+import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
+import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
import org.opendaylight.yangtools.yang.model.util.BaseTypes;
import org.opendaylight.yangtools.yang.model.util.UnionType;
import org.opendaylight.yangtools.yang.parser.builder.api.AbstractTypeAwareBuilder;
}
@Override
- public void setQName(QName qname) {
+ public void setQName(final QName qname) {
throw new UnsupportedOperationException("Can not set qname to union type");
}
@Override
public UnionType build() {
if (!isBuilt) {
- instance = new UnionType(types);
for (TypeDefinitionBuilder tdb : typedefs) {
types.add(tdb.build());
}
+ instance = new UnionType(types);
isBuilt = true;
}
return instance;
}
@Override
- public void setPath(SchemaPath path) {
+ public void setPath(final SchemaPath path) {
throw new YangParseException(moduleName, line, "Can not set path to " + NAME);
}
}
@Override
- public void setRanges(List<RangeConstraint> ranges) {
+ public void setRanges(final List<RangeConstraint> ranges) {
throw new YangParseException(moduleName, line, "Can not set ranges to " + NAME);
}
}
@Override
- public void setLengths(List<LengthConstraint> lengths) {
+ public void setLengths(final List<LengthConstraint> lengths) {
throw new YangParseException(moduleName, line, "Can not set lengths to " + NAME);
}
}
@Override
- public void setPatterns(List<PatternConstraint> patterns) {
+ public void setPatterns(final List<PatternConstraint> patterns) {
throw new YangParseException(moduleName, line, "Can not set patterns to " + NAME);
}
}
@Override
- public void setFractionDigits(Integer fractionDigits) {
+ public void setFractionDigits(final Integer fractionDigits) {
throw new YangParseException(moduleName, line, "Can not set fraction digits to " + NAME);
}
}
@Override
- public void setDefaultValue(Object defaultValue) {
+ public void setDefaultValue(final Object defaultValue) {
throw new YangParseException(moduleName, line, "Can not set default value to " + NAME);
}
}
@Override
- public void setUnits(String units) {
+ public void setUnits(final String units) {
throw new YangParseException(moduleName, line, "Can not set units to " + NAME);
}
*/
package org.opendaylight.yangtools.yang.parser.impl;
-import com.google.common.base.Optional;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
import org.opendaylight.yangtools.yang.model.api.UsesNode;
import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
+import com.google.common.base.Optional;
+import com.google.common.base.Supplier;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSetMultimap;
+import com.google.common.collect.Multimaps;
+import com.google.common.collect.SetMultimap;
final class SchemaContextImpl implements SchemaContext {
- private final Set<Module> modules;
+ private static final Supplier<HashSet<Module>> URI_SET_SUPPLIER = new Supplier<HashSet<Module>>() {
+ @Override
+ public HashSet<Module> get() {
+ return new HashSet<>();
+ }
+ };
+
private final Map<ModuleIdentifier, String> identifiersToSources;
+ private final SetMultimap<URI, Module> namespaceToModules;
+ private final Set<Module> modules;
- SchemaContextImpl(final Set<Module> modules, Map<ModuleIdentifier, String> identifiersToSources) {
- this.modules = modules;
+ SchemaContextImpl(final Set<Module> modules, final Map<ModuleIdentifier, String> identifiersToSources) {
this.identifiersToSources = identifiersToSources;
+
+ /*
+ * Instead of doing this on each invocation of getModules(), pre-compute
+ * it once and keep it around -- better than the set we got in.
+ */
+ this.modules = ImmutableSet.copyOf(ModuleDependencySort.sort(modules.toArray(new Module[modules.size()])));
+
+ /*
+ * The most common lookup is from Namespace->Module. Invest some quality time in
+ * building that up.
+ */
+ final SetMultimap<URI, Module> multimap = Multimaps.newSetMultimap(
+ new TreeMap<URI, Collection<Module>>(), URI_SET_SUPPLIER);
+ for (Module m : modules) {
+ multimap.put(m.getNamespace(), m);
+ }
+
+ namespaceToModules = ImmutableSetMultimap.copyOf(multimap);
}
@Override
@Override
public Set<Module> getModules() {
- List<Module> sorted = ModuleDependencySort.sort(modules.toArray(new Module[modules.size()]));
- return new LinkedHashSet<Module>(sorted);
+ return modules;
}
@Override
@Override
public Set<Module> findModuleByNamespace(final URI namespace) {
- final Set<Module> ret = new HashSet<Module>();
- if (namespace != null) {
- for (final Module module : modules) {
- if (module.getNamespace().equals(namespace)) {
- ret.add(module);
- }
- }
- }
- return ret;
+ final Set<Module> ret = namespaceToModules.get(namespace);
+ return ret == null ? Collections.<Module>emptySet() : ret;
}
@Override
- public Module findModuleByNamespaceAndRevision(URI namespace, Date revision) {
- if (namespace != null) {
- Set<Module> modules = findModuleByNamespace(namespace);
-
- if (revision == null) {
- TreeMap<Date, Module> map = new TreeMap<Date, Module>();
- for (Module module : modules) {
- map.put(module.getRevision(), module);
- }
- if (map.isEmpty()) {
- return null;
- }
- return map.lastEntry().getValue();
- } else {
- for (Module module : modules) {
- if (module.getRevision().equals(revision)) {
- return(module);
- }
+ public Module findModuleByNamespaceAndRevision(final URI namespace, final Date revision) {
+ if (namespace == null) {
+ return null;
+ }
+ final Set<Module> modules = findModuleByNamespace(namespace);
+ if (modules.isEmpty()) {
+ return null;
+ }
+
+ if (revision == null) {
+ // FIXME: The ordering of modules in Multimap could just guarantee this...
+ TreeMap<Date, Module> map = new TreeMap<Date, Module>();
+ for (Module module : modules) {
+ map.put(module.getRevision(), module);
+ }
+ if (map.isEmpty()) {
+ return null;
+ }
+ return map.lastEntry().getValue();
+ } else {
+ for (Module module : modules) {
+ if (module.getRevision().equals(revision)) {
+ return(module);
}
}
}
}
@Override
- public DataSchemaNode getDataChildByName(QName name) {
+ public DataSchemaNode getDataChildByName(final QName name) {
DataSchemaNode result = null;
for (Module module : modules) {
result = module.getDataChildByName(name);
}
@Override
- public DataSchemaNode getDataChildByName(String name) {
+ public DataSchemaNode getDataChildByName(final String name) {
DataSchemaNode result = null;
for (Module module : modules) {
result = module.getDataChildByName(name);
}
@Override
- public Optional<String> getModuleSource(ModuleIdentifier moduleIdentifier) {
+ public Optional<String> getModuleSource(final ModuleIdentifier moduleIdentifier) {
String maybeSource = identifiersToSources.get(moduleIdentifier);
return Optional.fromNullable(maybeSource);
}
*/
package org.opendaylight.yangtools.yang.parser.impl;
+import java.util.ArrayList;
+import java.util.List;
+
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
-import org.opendaylight.yangtools.yang.parser.util.YangParseException;
-
-import java.util.ArrayList;
-import java.util.List;
+import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
final class YangErrorListener extends BaseErrorListener {
- private final List<Exception> exceptions = new ArrayList<>();
+ private static final Logger LOG = LoggerFactory.getLogger(YangErrorListener.class);
+ private final List<YangSyntaxErrorException> exceptions = new ArrayList<>();
@Override
- public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine,
- String msg, RecognitionException e) {
- String module = getModuleName(recognizer);
- exceptions.add(new YangParseException(module, line, msg));
+ public void syntaxError(final Recognizer<?, ?> recognizer, final Object offendingSymbol, final int line,
+ final int charPositionInLine, final String msg, final RecognitionException e) {
+ LOG.debug("Syntax error at {}:{}: {}", line, charPositionInLine, msg, e);
+
+ final String module = getModuleName(recognizer);
+ exceptions.add(new YangSyntaxErrorException(module, line, charPositionInLine, msg, e));
}
- private String getModuleName(Recognizer<?, ?> recognizer) {
- String result;
- if (recognizer instanceof Parser) {
- try {
- Parser parser = (Parser) recognizer;
- String model = parser.getInputStream().getTokenSource().getInputStream().toString();
- model = model.substring(0, model.indexOf("\n"));
- model = model.substring(model.indexOf("module") + 6);
- model = model.substring(0, model.indexOf("{"));
- model = model.trim();
- result = model;
- } catch (Exception e) {
- result = "";
- }
- } else {
- result = "";
+ private static String getModuleName(final Recognizer<?, ?> recognizer) {
+ if (!(recognizer instanceof Parser)) {
+ return null;
+ }
+
+ final Parser parser = (Parser) recognizer;
+ try {
+ String model = parser.getInputStream().getTokenSource().getInputStream().toString();
+ model = model.substring(0, model.indexOf("\n"));
+ model = model.substring(model.indexOf("module") + 6);
+ model = model.substring(0, model.indexOf("{"));
+ model = model.trim();
+ return model;
+ } catch (Exception e) {
+ LOG.debug("Failed to extract module name from parser {}", parser, e);
+ return null;
}
- return result;
}
- public void validate() {
- if (!exceptions.isEmpty()) {
- StringBuilder sb = new StringBuilder();
- for (Exception e : exceptions) {
- sb.append("\n");
- sb.append(e.getMessage());
+ public void validate() throws YangSyntaxErrorException {
+ if (exceptions.isEmpty()) {
+ return;
+ }
+
+ // Single exception: just throw it
+ if (exceptions.size() == 1) {
+ throw exceptions.get(0);
+ }
+
+ final StringBuilder sb = new StringBuilder();
+ String module = null;
+ boolean first = true;
+ for (YangSyntaxErrorException e : exceptions) {
+ if (module == null) {
+ module = e.getModule();
}
- throw new YangParseException(sb.toString());
+ if (first) {
+ first = false;
+ } else {
+ sb.append('\n');
+ }
+
+ sb.append(e.getFormattedMessage());
}
- }
+ throw new YangSyntaxErrorException(module, 0, 0, sb.toString());
+ }
}
import static org.opendaylight.yangtools.yang.parser.util.TypeUtils.resolveTypeUnionWithContext;
import static org.opendaylight.yangtools.yang.parser.util.TypeUtils.resolveTypeWithContext;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.HashBiMap;
-import com.google.common.io.ByteSource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
+
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
+import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationSchemaBuilder;
import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationTargetBuilder;
import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.HashBiMap;
+import com.google.common.io.ByteSource;
+
public final class YangParserImpl implements YangContextParser {
private static final Logger LOG = LoggerFactory.getLogger(YangParserImpl.class);
private static final String FAIL_DEVIATION_TARGET = "Failed to find deviation target.";
@Override
+ @Deprecated
public Set<Module> parseYangModels(final File yangFile, final File directory) {
try {
return parseFile(yangFile, directory).getModules();
- } catch (IOException e) {
+ } catch (IOException | YangSyntaxErrorException e) {
throw new YangParseException("Failed to parse yang data", e);
}
}
@Override
- public SchemaContext parseFile(final File yangFile, final File directory) throws IOException {
+ public SchemaContext parseFile(final File yangFile, final File directory) throws IOException, YangSyntaxErrorException {
Preconditions.checkState(yangFile.exists(), yangFile + " does not exists");
Preconditions.checkState(directory.exists(), directory + " does not exists");
Preconditions.checkState(directory.isDirectory(), directory + " is not a directory");
}
@Override
+ @Deprecated
public Set<Module> parseYangModels(final List<File> yangFiles) {
return parseFiles(yangFiles).getModules();
}
}
@Override
+ @Deprecated
public Set<Module> parseYangModels(final List<File> yangFiles, final SchemaContext context) {
try {
return parseFiles(yangFiles, context).getModules();
- } catch (IOException e) {
+ } catch (IOException | YangSyntaxErrorException e) {
throw new YangParseException("Failed to parse yang data", e);
}
}
@Override
- public SchemaContext parseFiles(final Collection<File> yangFiles, final SchemaContext context) throws IOException {
+ public SchemaContext parseFiles(final Collection<File> yangFiles, final SchemaContext context) throws IOException, YangSyntaxErrorException {
if (yangFiles == null) {
return resolveSchemaContext(Collections.<Module> emptySet());
}
}
@Override
+ @Deprecated
public Set<Module> parseYangModelsFromStreams(final List<InputStream> yangModelStreams) {
- Collection<ByteSource> sources = ParserUtils.streamsToByteSources(yangModelStreams);
try {
+ Collection<ByteSource> sources = ParserUtils.streamsToByteSources(yangModelStreams);
return parseSources(sources).getModules();
- } catch (IOException e) {
+ } catch (IOException | YangSyntaxErrorException e) {
throw new YangParseException("Failed to parse yang data", e);
}
}
@Override
- public SchemaContext parseSources(Collection<ByteSource> sources) throws IOException {
+ public SchemaContext parseSources(final Collection<ByteSource> sources) throws IOException, YangSyntaxErrorException {
Collection<Module> unsorted = parseYangModelSources(sources).values();
Set<Module> sorted = new LinkedHashSet<>(
ModuleDependencySort.sort(unsorted.toArray(new Module[unsorted.size()])));
}
@Override
- public Set<Module> parseYangModelsFromStreams(final List<InputStream> yangModelStreams, SchemaContext context) {
- Collection<ByteSource> sources = ParserUtils.streamsToByteSources(yangModelStreams);
+ @Deprecated
+ public Set<Module> parseYangModelsFromStreams(final List<InputStream> yangModelStreams, final SchemaContext context) {
try {
+ Collection<ByteSource> sources = ParserUtils.streamsToByteSources(yangModelStreams);
return parseSources(sources, context).getModules();
- } catch (IOException e) {
+ } catch (IOException | YangSyntaxErrorException e) {
throw new YangParseException("Failed to parse yang data", e);
}
}
@Override
- public SchemaContext parseSources(Collection<ByteSource> sources, SchemaContext context) throws IOException {
+ public SchemaContext parseSources(final Collection<ByteSource> sources, final SchemaContext context) throws IOException, YangSyntaxErrorException {
if (sources == null) {
return resolveSchemaContext(Collections.<Module> emptySet());
}
}
@Override
- public Map<File, Module> parseYangModelsMapped(Collection<File> yangFiles) {
+ public Map<File, Module> parseYangModelsMapped(final Collection<File> yangFiles) {
if (yangFiles == null || yangFiles.isEmpty()) {
return Collections.emptyMap();
}
Map<ByteSource, Module> byteSourceToModule;
try {
byteSourceToModule = parseYangModelSources(byteSourceToFile.keySet());
- } catch (IOException e) {
+ } catch (IOException | YangSyntaxErrorException e) {
throw new YangParseException("Failed to parse yang data", e);
}
Map<File, Module> result = new LinkedHashMap<>();
Map<ByteSource, Module> sourceToModule;
try {
sourceToModule = parseYangModelSources(sourceToStream.keySet());
- } catch (IOException e) {
+ } catch (IOException | YangSyntaxErrorException e) {
throw new YangParseException("Failed to parse yang data", e);
}
Map<InputStream, Module> result = new LinkedHashMap<>();
return new SchemaContextImpl(modules, identifiersToSources);
}
- private Map<ByteSource, Module> parseYangModelSources(final Collection<ByteSource> sources) throws IOException {
+ private Map<ByteSource, Module> parseYangModelSources(final Collection<ByteSource> sources) throws IOException, YangSyntaxErrorException {
if (sources == null || sources.isEmpty()) {
return Collections.emptyMap();
}
* collection of streams to parse
* @return map, where key is source stream and value is module builder
* parsed from stream
+ * @throws YangSyntaxErrorException
*/
- private Map<ByteSource, ModuleBuilder> resolveSources(Collection<ByteSource> streams) throws IOException {
+ private Map<ByteSource, ModuleBuilder> resolveSources(final Collection<ByteSource> streams) throws IOException, YangSyntaxErrorException {
Map<ByteSource, ModuleBuilder> builders = parseSourcesToBuilders(streams);
Map<ByteSource, ModuleBuilder> result = resolveSubmodules(builders);
return result;
}
- private Map<ByteSource, ModuleBuilder> parseSourcesToBuilders(Collection<ByteSource> sources) throws IOException {
+ private Map<ByteSource, ModuleBuilder> parseSourcesToBuilders(final Collection<ByteSource> sources) throws IOException, YangSyntaxErrorException {
final ParseTreeWalker walker = new ParseTreeWalker();
final Map<ByteSource, ParseTree> sourceToTree = parseYangSources(sources);
final Map<ByteSource, ModuleBuilder> sourceToBuilder = new LinkedHashMap<>();
sourceToBuilder.put(source, moduleBuilder);
}
+ ParserUtils.setSourceToBuilder(sourceToBuilder);
return sourceToBuilder;
}
- private Map<ByteSource, ModuleBuilder> resolveSubmodules(Map<ByteSource, ModuleBuilder> builders) {
+ private Map<ByteSource, ModuleBuilder> resolveSubmodules(final Map<ByteSource, ModuleBuilder> builders) {
Map<ByteSource, ModuleBuilder> modules = new HashMap<>();
Set<ModuleBuilder> submodules = new HashSet<>();
for (Map.Entry<ByteSource, ModuleBuilder> entry : builders.entrySet()) {
* collection of builders containing modules and submodules
* @return collection of module builders
*/
- private Collection<ModuleBuilder> resolveSubmodules(Collection<ModuleBuilder> builders) {
+ private Collection<ModuleBuilder> resolveSubmodules(final Collection<ModuleBuilder> builders) {
Collection<ModuleBuilder> modules = new HashSet<>();
Set<ModuleBuilder> submodules = new HashSet<>();
for (ModuleBuilder moduleBuilder : builders) {
return modules;
}
- private void addSubmoduleToModule(ModuleBuilder submodule, ModuleBuilder module) {
+ private void addSubmoduleToModule(final ModuleBuilder submodule, final ModuleBuilder module) {
submodule.setParent(module);
module.getDirtyNodes().addAll(submodule.getDirtyNodes());
module.getModuleImports().addAll(submodule.getModuleImports());
}
private Map<String, TreeMap<Date, ModuleBuilder>> resolveModuleBuilders(
- final Collection<ByteSource> yangFileStreams, final SchemaContext context) throws IOException {
+ final Collection<ByteSource> yangFileStreams, final SchemaContext context) throws IOException, YangSyntaxErrorException {
Map<ByteSource, ModuleBuilder> parsedBuilders = resolveSources(yangFileStreams);
ModuleBuilder[] builders = new ModuleBuilder[parsedBuilders.size()];
parsedBuilders.values().toArray(builders);
* modules to order
* @return modules ordered by name and revision
*/
- private LinkedHashMap<String, TreeMap<Date, ModuleBuilder>> orderModules(List<ModuleBuilder> modules) {
+ private LinkedHashMap<String, TreeMap<Date, ModuleBuilder>> orderModules(final List<ModuleBuilder> modules) {
final LinkedHashMap<String, TreeMap<Date, ModuleBuilder>> result = new LinkedHashMap<>();
for (final ModuleBuilder builder : modules) {
if (builder == null) {
* @param filtered
* collection to fill up
*/
- private void filterImports(ModuleBuilder main, Collection<ModuleBuilder> other, Collection<ModuleBuilder> filtered) {
+ private void filterImports(final ModuleBuilder main, final Collection<ModuleBuilder> other, final Collection<ModuleBuilder> filtered) {
Set<ModuleImport> imports = main.getModuleImports();
// if this is submodule, add parent to filtered and pick its imports
}
}
- private Map<ByteSource, ParseTree> parseYangSources(final Collection<ByteSource> sources) throws IOException {
+ private Map<ByteSource, ParseTree> parseYangSources(final Collection<ByteSource> sources) throws IOException, YangSyntaxErrorException {
final Map<ByteSource, ParseTree> trees = new HashMap<>();
for (ByteSource source : sources) {
trees.put(source, parseYangSource(source));
return trees;
}
- private ParseTree parseYangSource(final ByteSource source) throws IOException {
- ParseTree result = null;
- InputStream stream = null;
- try {
- stream = source.openStream();
+ private YangContext parseYangSource(final ByteSource source) throws IOException, YangSyntaxErrorException {
+ try (InputStream stream = source.openStream()) {
final ANTLRInputStream input = new ANTLRInputStream(stream);
final YangLexer lexer = new YangLexer(input);
final CommonTokenStream tokens = new CommonTokenStream(lexer);
final YangParser parser = new YangParser(tokens);
parser.removeErrorListeners();
- YangErrorListener errorListener = new YangErrorListener();
+
+ final YangErrorListener errorListener = new YangErrorListener();
parser.addErrorListener(errorListener);
- result = parser.yang();
+
+ final YangContext result = parser.yang();
errorListener.validate();
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- LOG.warn("Failed to close stream {}", stream);
- }
- }
- }
- return result;
+
+ return result;
+ }
}
public static YangContext parseStreamWithoutErrorListeners(final InputStream yangStream) {
}
private void resolveDirtyNodesWithContext(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
- final ModuleBuilder module, SchemaContext context) {
+ final ModuleBuilder module, final SchemaContext context) {
final Set<TypeAwareBuilder> dirtyNodes = module.getDirtyNodes();
if (!dirtyNodes.isEmpty()) {
for (TypeAwareBuilder nodeToResolve : dirtyNodes) {
* SchemaContext containing already resolved modules
*/
private void resolveAugmentsTargetPath(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
- SchemaContext context) {
+ final SchemaContext context) {
// collect augments from all loaded modules
final List<AugmentationSchemaBuilder> allAugments = new ArrayList<>();
for (Map.Entry<String, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
newPath.add(new QName(ns, rev, localPrefix, qn.getLocalName()));
}
}
- augment.setTargetNodeSchemaPath(new SchemaPath(newPath, true));
+ augment.setTargetNodeSchemaPath(SchemaPath.create(newPath, true));
for (DataSchemaNodeBuilder childNode : augment.getChildNodeBuilders()) {
correctPathForAugmentNodes(childNode, augment.getTargetNodeSchemaPath());
* @param parentPath
* schema path of parent node
*/
- private void correctPathForAugmentNodes(DataSchemaNodeBuilder node, SchemaPath parentPath) {
- SchemaPath newPath = ParserUtils.createSchemaPath(parentPath, node.getQName());
+ private void correctPathForAugmentNodes(final DataSchemaNodeBuilder node, final SchemaPath parentPath) {
+ SchemaPath newPath = parentPath.createChild(node.getQName());
node.setPath(newPath);
if (node instanceof DataNodeContainerBuilder) {
for (DataSchemaNodeBuilder child : ((DataNodeContainerBuilder) node).getChildNodeBuilders()) {
* @param augments
* augments to check
*/
- private void checkAugmentMandatoryNodes(Collection<AugmentationSchemaBuilder> augments) {
+ private void checkAugmentMandatoryNodes(final Collection<AugmentationSchemaBuilder> augments) {
for (AugmentationSchemaBuilder augment : augments) {
String augmentPrefix = augment.getTargetPath().getPath().get(0).getPrefix();
ModuleBuilder module = ParserUtils.getParentModule(augment);
* @param context
* SchemaContext containing already resolved modules
*/
- private void resolveUses(UsesNodeBuilder usesNode,
+ private void resolveUses(final UsesNodeBuilder usesNode,
final Map<String, TreeMap<Date, ModuleBuilder>> modules, final SchemaContext context) {
if (!usesNode.isResolved()) {
DataNodeContainerBuilder parent = usesNode.getParent();
* @param context
* SchemaContext containing already resolved modules
*/
- private void resolveUsesWithContext(UsesNodeBuilder usesNode) {
+ private void resolveUsesWithContext(final UsesNodeBuilder usesNode) {
final int line = usesNode.getLine();
DataNodeContainerBuilder parent = usesNode.getParent();
ModuleBuilder module = ParserUtils.getParentModule(parent);
*/
package org.opendaylight.yangtools.yang.parser.impl;
-import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.*;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.checkMissingBody;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.createActualSchemaPath;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.createListKey;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.getConfig;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.getIdentityrefBase;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseConstraints;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseDefault;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseRefine;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseSchemaNodeArgs;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseStatus;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseTypeWithBody;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseUnits;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseUnknownTypeWithBody;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseUserOrdered;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.parseYinValue;
+import static org.opendaylight.yangtools.yang.parser.util.ParserListenerUtils.stringFromNode;
+import com.google.common.base.Strings;
import java.net.URI;
-import java.text.*;
-import java.util.*;
-
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+import java.util.Stack;
import org.antlr.v4.runtime.tree.ParseTree;
-import org.opendaylight.yangtools.antlrv4.code.gen.*;
+import org.opendaylight.yangtools.antlrv4.code.gen.YangParser;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Argument_stmtContext;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Base_stmtContext;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Contact_stmtContext;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Units_stmtContext;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.When_stmtContext;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yang_version_stmtContext;
+import org.opendaylight.yangtools.antlrv4.code.gen.YangParserBaseListener;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
import org.opendaylight.yangtools.yang.model.util.BaseTypes;
import org.opendaylight.yangtools.yang.model.util.YangTypesConverter;
-import org.opendaylight.yangtools.yang.parser.builder.api.*;
-import org.opendaylight.yangtools.yang.parser.builder.impl.*;
+import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationSchemaBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
+import org.opendaylight.yangtools.yang.parser.builder.api.GroupingBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.api.TypeDefinitionBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.api.UsesNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.AnyXmlBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceCaseBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.DeviationBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.ExtensionBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.FeatureBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.IdentitySchemaNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.LeafListSchemaNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.ListSchemaNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.NotificationBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.RpcDefinitionBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.UnionTypeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.UnknownSchemaNodeBuilder;
import org.opendaylight.yangtools.yang.parser.util.RefineHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.base.Strings;
-
public final class YangParserListenerImpl extends YangParserBaseListener {
private static final Logger LOGGER = LoggerFactory.getLogger(YangParserListenerImpl.class);
private static final String AUGMENT_STR = "augment";
@Override
public void enterModule_stmt(YangParser.Module_stmtContext ctx) {
moduleName = stringFromNode(ctx);
- LOGGER.debug("entering module " + moduleName);
+ LOGGER.trace("entering module " + moduleName);
enterLog("module", moduleName, 0);
actualPath.push(new Stack<QName>());
@Override public void enterSubmodule_stmt(YangParser.Submodule_stmtContext ctx) {
moduleName = stringFromNode(ctx);
- LOGGER.debug("entering submodule " + moduleName);
+ LOGGER.trace("entering submodule " + moduleName);
enterLog("submodule", moduleName, 0);
actualPath.push(new Stack<QName>());
}
currentSourceContext = context;
} catch (Exception e) {
- LOG.error("Could not create schema context for {} ",context.getValidSources());
+ LOG.error("Could not create schema context for {} ", context.getValidSources(), e);
}
return Optional.absent();
}
import java.io.InputStream;
import java.util.Collections;
-import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
-import java.util.Map.Entry;
import java.util.Set;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.util.repo.AdvancedSchemaSourceProvider;
import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProvider;
-import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProviders;
import org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier;
import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
private final ImmutableMultimap<SourceIdentifier, ModuleImport> missingDependencies;
private AdvancedSchemaSourceProvider<InputStream> sourceProvider;
- private YangSourceContext(ImmutableSet<SourceIdentifier> validSourcesSet,
- ImmutableSet<SourceIdentifier> missingSourcesSet,
- ImmutableMultimap<SourceIdentifier, ModuleImport> missingDependenciesMap,
- AdvancedSchemaSourceProvider<InputStream> sourceProvicer) {
+ YangSourceContext(final ImmutableSet<SourceIdentifier> validSourcesSet,
+ final ImmutableSet<SourceIdentifier> missingSourcesSet,
+ final ImmutableMultimap<SourceIdentifier, ModuleImport> missingDependenciesMap,
+ final AdvancedSchemaSourceProvider<InputStream> sourceProvicer) {
validSources = validSourcesSet;
missingSources = missingSourcesSet;
missingDependencies = missingDependenciesMap;
}
@Override
- public Optional<InputStream> getSchemaSource(String moduleName, Optional<String> revision) {
+ public Optional<InputStream> getSchemaSource(final String moduleName, final Optional<String> revision) {
return getSchemaSource(SourceIdentifier.create(moduleName, revision));
}
@Override
- public Optional<InputStream> getSchemaSource(SourceIdentifier sourceIdentifier) {
+ public Optional<InputStream> getSchemaSource(final SourceIdentifier sourceIdentifier) {
if (validSources.contains(sourceIdentifier)) {
return getDelegateChecked().getSchemaSource(sourceIdentifier);
}
}
}
- public static final YangSourceContext createFrom(Iterable<QName> capabilities,
- SchemaSourceProvider<InputStream> schemaSourceProvider) {
+ public static final YangSourceContext createFrom(final Iterable<QName> capabilities,
+ final SchemaSourceProvider<InputStream> schemaSourceProvider) {
YangSourceContextResolver resolver = new YangSourceFromCapabilitiesResolver(capabilities, schemaSourceProvider);
return resolver.resolveContext();
}
- public static final YangSourceContext createFrom(Map<SourceIdentifier, YangModelDependencyInfo> moduleDependencies) {
+ public static final YangSourceContext createFrom(final Map<SourceIdentifier, YangModelDependencyInfo> moduleDependencies) {
YangSourceContextResolver resolver = new YangSourceFromDependencyInfoResolver(moduleDependencies);
return resolver.resolveContext();
}
- public static final SchemaContext toSchemaContext(YangSourceContext context) {
+ public static final SchemaContext toSchemaContext(final YangSourceContext context) {
List<InputStream> inputStreams = getValidInputStreams(context);
YangParserImpl parser = new YangParserImpl();
Set<Module> models = parser.parseYangModelsFromStreams(inputStreams);
return parser.resolveSchemaContext(models);
}
- public static List<InputStream> getValidInputStreams(YangSourceContext context) {
+ public static List<InputStream> getValidInputStreams(final YangSourceContext context) {
return getValidInputStreams(context, context.sourceProvider);
}
- public static List<InputStream> getValidInputStreams(YangSourceContext context,
- AdvancedSchemaSourceProvider<InputStream> provider) {
+ public static List<InputStream> getValidInputStreams(final YangSourceContext context,
+ final AdvancedSchemaSourceProvider<InputStream> provider) {
final HashSet<SourceIdentifier> sourcesToLoad = new HashSet<>();
sourcesToLoad.addAll(context.getValidSources());
for (SourceIdentifier source : context.getValidSources()) {
}
return ret.build();
}
-
- public static abstract class YangSourceContextResolver {
-
- private static final Logger LOG = LoggerFactory.getLogger(YangSourceContextResolver.class);
-
- private final AdvancedSchemaSourceProvider<InputStream> sourceProvider;
-
- public AdvancedSchemaSourceProvider<InputStream> getSourceProvider() {
- return sourceProvider;
- }
-
- private final HashMap<SourceIdentifier, ResolutionState> alreadyProcessed = new HashMap<>();
-
- private final ImmutableSet.Builder<SourceIdentifier> missingSources = ImmutableSet.builder();
-
- private ImmutableMultimap.Builder<SourceIdentifier, ModuleImport> missingDependencies = ImmutableMultimap
- .builder();
-
- private final ImmutableSet.Builder<SourceIdentifier> validSources = ImmutableSet.builder();
-
- public YangSourceContextResolver() {
- sourceProvider = null;
- }
-
- public YangSourceContextResolver(AdvancedSchemaSourceProvider<InputStream> sourceProvicer) {
- super();
- this.sourceProvider = sourceProvicer;
- }
-
- public abstract YangSourceContext resolveContext();
-
- public ResolutionState resolveSource(String name, Optional<String> formattedRevision) {
- return resolveSource(new SourceIdentifier(name, formattedRevision));
- }
-
- public ResolutionState resolveSource(SourceIdentifier identifier) {
-
- if (alreadyProcessed.containsKey(identifier)) {
- return alreadyProcessed.get(identifier);
- }
- LOG.trace("Resolving source:Â {}", identifier);
- ResolutionState potentialState = ResolutionState.EVERYTHING_OK;
- try {
- Optional<YangModelDependencyInfo> potentialInfo = getDependencyInfo(identifier);
- if (potentialInfo.isPresent()) {
- YangModelDependencyInfo info = potentialInfo.get();
- checkValidSource(identifier, info);
- for (ModuleImport dependency : info.getDependencies()) {
- LOG.trace("Source: {} Resolving dependency: {}", identifier, dependency);
- ResolutionState dependencyState = resolveDependency(dependency);
- if (dependencyState != ResolutionState.EVERYTHING_OK) {
- potentialState = ResolutionState.MISSING_DEPENDENCY;
- missingDependencies.put(identifier, dependency);
- }
- }
- } else {
- missingSources.add(identifier);
- return ResolutionState.MISSING_SOURCE;
- }
- } catch (Exception e) {
- potentialState = ResolutionState.OTHER_ERROR;
- }
- updateResolutionState(identifier, potentialState);
- return potentialState;
- }
-
- public abstract Optional<YangModelDependencyInfo> getDependencyInfo(SourceIdentifier identifier);
-
- private boolean checkValidSource(SourceIdentifier identifier, YangModelDependencyInfo info) {
- if (!identifier.getName().equals(info.getName())) {
- LOG.warn("Incorrect model returned. Identifier name was: {}, source contained: {}",
- identifier.getName(), info.getName());
- throw new IllegalStateException("Incorrect source was returned");
- }
- return true;
- }
-
- private void updateResolutionState(SourceIdentifier identifier, ResolutionState potentialState) {
- alreadyProcessed.put(identifier, potentialState);
- switch (potentialState) {
- case MISSING_SOURCE:
- missingSources.add(identifier);
- break;
- case EVERYTHING_OK:
- validSources.add(identifier);
- break;
- default:
- break;
- }
- }
-
- private ResolutionState resolveDependency(ModuleImport dependency) {
- String name = dependency.getModuleName();
- Optional<String> formattedRevision = Optional
- .fromNullable(QName.formattedRevision(dependency.getRevision()));
- return resolveSource(new SourceIdentifier(name, formattedRevision));
- }
-
- protected YangSourceContext createSourceContext() {
-
- ImmutableSet<SourceIdentifier> missingSourcesSet = missingSources.build();
- ImmutableMultimap<SourceIdentifier, ModuleImport> missingDependenciesMap = missingDependencies.build();
- ImmutableSet<SourceIdentifier> validSourcesSet = validSources.build();
-
- return new YangSourceContext(validSourcesSet, missingSourcesSet, missingDependenciesMap, sourceProvider);
-
- }
- }
-
- private enum ResolutionState {
- MISSING_SOURCE, MISSING_DEPENDENCY, OTHER_ERROR, EVERYTHING_OK
- }
-
- public static final class YangSourceFromCapabilitiesResolver extends YangSourceContextResolver {
-
- private Iterable<QName> capabilities;
-
- public YangSourceFromCapabilitiesResolver(Iterable<QName> capabilities,
- SchemaSourceProvider<InputStream> schemaSourceProvider) {
- super(SchemaSourceProviders.toAdvancedSchemaSourceProvider(schemaSourceProvider));
- this.capabilities = capabilities;
- }
-
- @Override
- public YangSourceContext resolveContext() {
- for (QName capability : capabilities) {
- resolveCapability(capability);
- }
- return createSourceContext();
- }
-
- private void resolveCapability(QName capability) {
- super.resolveSource(capability.getLocalName(), Optional.fromNullable(capability.getFormattedRevision()));
- }
-
- @Override
- public Optional<YangModelDependencyInfo> getDependencyInfo(SourceIdentifier identifier) {
- Optional<InputStream> source = getSchemaSource(identifier);
- if (source.isPresent()) {
- return Optional.of(YangModelDependencyInfo.fromInputStream(source.get()));
- }
- return Optional.absent();
- }
-
- private Optional<InputStream> getSchemaSource(SourceIdentifier identifier) {
- return getSourceProvider().getSchemaSource(identifier.getName(),
- Optional.fromNullable(identifier.getRevision()));
- }
-
- }
-
- public static final class YangSourceFromDependencyInfoResolver extends YangSourceContextResolver {
-
- private final Map<SourceIdentifier, YangModelDependencyInfo> dependencyInfo;
-
- public YangSourceFromDependencyInfoResolver(Map<SourceIdentifier, YangModelDependencyInfo> moduleDependencies) {
- dependencyInfo = ImmutableMap.copyOf(moduleDependencies);
- }
-
- @Override
- public Optional<YangModelDependencyInfo> getDependencyInfo(SourceIdentifier identifier) {
- if (identifier.getRevision() != null) {
- return Optional.fromNullable(dependencyInfo.get(identifier));
- }
- YangModelDependencyInfo potential = dependencyInfo.get(identifier);
- if (potential == null) {
- for (Entry<SourceIdentifier, YangModelDependencyInfo> newPotential : dependencyInfo.entrySet()) {
- String newPotentialName = newPotential.getKey().getName();
-
- if (newPotentialName.equals(identifier.getName())) {
- String newPotentialRevision = newPotential.getKey().getRevision();
- if (potential == null || 1 == newPotentialRevision.compareTo(potential.getFormattedRevision())) {
- potential = newPotential.getValue();
- }
- }
- }
- }
- return Optional.fromNullable(potential);
- }
-
- @Override
- public YangSourceContext resolveContext() {
- for (SourceIdentifier source : dependencyInfo.keySet()) {
- resolveSource(source);
- }
- return createSourceContext();
- }
- }
-
}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/eplv10.html
+ */
+package org.opendaylight.yangtools.yang.parser.impl.util;
+
+import java.io.InputStream;
+import java.util.HashMap;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.ModuleImport;
+import org.opendaylight.yangtools.yang.model.util.repo.AdvancedSchemaSourceProvider;
+import org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableMultimap;
+import com.google.common.collect.ImmutableSet;
+
+public abstract class YangSourceContextResolver {
+
+ enum ResolutionState {
+ MISSING_SOURCE,
+ MISSING_DEPENDENCY,
+ OTHER_ERROR,
+ EVERYTHING_OK,
+ }
+
+ private static final Logger LOG = LoggerFactory.getLogger(YangSourceContextResolver.class);
+ private final HashMap<SourceIdentifier, YangSourceContextResolver.ResolutionState> alreadyProcessed = new HashMap<>();
+ private final ImmutableSet.Builder<SourceIdentifier> missingSources = ImmutableSet.builder();
+ private final ImmutableMultimap.Builder<SourceIdentifier, ModuleImport> missingDependencies =
+ ImmutableMultimap.builder();
+ private final ImmutableSet.Builder<SourceIdentifier> validSources = ImmutableSet.builder();
+ private final AdvancedSchemaSourceProvider<InputStream> sourceProvider;
+
+ public YangSourceContextResolver() {
+ sourceProvider = null;
+ }
+
+ public YangSourceContextResolver(final AdvancedSchemaSourceProvider<InputStream> sourceProvicer) {
+ super();
+ this.sourceProvider = sourceProvicer;
+ }
+
+ public abstract YangSourceContext resolveContext();
+ public abstract Optional<YangModelDependencyInfo> getDependencyInfo(SourceIdentifier identifier);
+
+ public AdvancedSchemaSourceProvider<InputStream> getSourceProvider() {
+ return sourceProvider;
+ }
+
+ public YangSourceContextResolver.ResolutionState resolveSource(final String name, final Optional<String> formattedRevision) {
+ return resolveSource(new SourceIdentifier(name, formattedRevision));
+ }
+
+ public YangSourceContextResolver.ResolutionState resolveSource(final SourceIdentifier identifier) {
+
+ if (alreadyProcessed.containsKey(identifier)) {
+ return alreadyProcessed.get(identifier);
+ }
+ LOG.trace("Resolving source:Â {}", identifier);
+ YangSourceContextResolver.ResolutionState potentialState = YangSourceContextResolver.ResolutionState.EVERYTHING_OK;
+ try {
+ Optional<YangModelDependencyInfo> potentialInfo = getDependencyInfo(identifier);
+ if (potentialInfo.isPresent()) {
+ YangModelDependencyInfo info = potentialInfo.get();
+ checkValidSource(identifier, info);
+ for (ModuleImport dependency : info.getDependencies()) {
+ LOG.trace("Source: {} Resolving dependency: {}", identifier, dependency);
+ YangSourceContextResolver.ResolutionState dependencyState = resolveDependency(dependency);
+ if (dependencyState != YangSourceContextResolver.ResolutionState.EVERYTHING_OK) {
+ potentialState = YangSourceContextResolver.ResolutionState.MISSING_DEPENDENCY;
+ missingDependencies.put(identifier, dependency);
+ }
+ }
+ } else {
+ missingSources.add(identifier);
+ return YangSourceContextResolver.ResolutionState.MISSING_SOURCE;
+ }
+ } catch (Exception e) {
+ potentialState = YangSourceContextResolver.ResolutionState.OTHER_ERROR;
+ }
+ updateResolutionState(identifier, potentialState);
+ return potentialState;
+ }
+
+ private boolean checkValidSource(final SourceIdentifier identifier, final YangModelDependencyInfo info) {
+ if (!identifier.getName().equals(info.getName())) {
+ LOG.warn("Incorrect model returned. Identifier name was: {}, source contained: {}",
+ identifier.getName(), info.getName());
+ throw new IllegalStateException("Incorrect source was returned");
+ }
+ return true;
+ }
+
+ private void updateResolutionState(final SourceIdentifier identifier, final YangSourceContextResolver.ResolutionState potentialState) {
+ alreadyProcessed.put(identifier, potentialState);
+ switch (potentialState) {
+ case MISSING_SOURCE:
+ missingSources.add(identifier);
+ break;
+ case EVERYTHING_OK:
+ validSources.add(identifier);
+ break;
+ default:
+ break;
+ }
+ }
+
+ private YangSourceContextResolver.ResolutionState resolveDependency(final ModuleImport dependency) {
+ String name = dependency.getModuleName();
+ Optional<String> formattedRevision = Optional
+ .fromNullable(QName.formattedRevision(dependency.getRevision()));
+ return resolveSource(new SourceIdentifier(name, formattedRevision));
+ }
+
+ protected YangSourceContext createSourceContext() {
+ ImmutableSet<SourceIdentifier> missingSourcesSet = missingSources.build();
+ ImmutableMultimap<SourceIdentifier, ModuleImport> missingDependenciesMap = missingDependencies.build();
+ ImmutableSet<SourceIdentifier> validSourcesSet = validSources.build();
+ return new YangSourceContext(validSourcesSet, missingSourcesSet, missingDependenciesMap, sourceProvider);
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/eplv10.html
+ */
+package org.opendaylight.yangtools.yang.parser.impl.util;
+
+import java.io.InputStream;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProvider;
+import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProviders;
+import org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier;
+
+import com.google.common.base.Optional;
+
+public final class YangSourceFromCapabilitiesResolver extends YangSourceContextResolver {
+
+ private final Iterable<QName> capabilities;
+
+ public YangSourceFromCapabilitiesResolver(final Iterable<QName> capabilities,
+ final SchemaSourceProvider<InputStream> schemaSourceProvider) {
+ super(SchemaSourceProviders.toAdvancedSchemaSourceProvider(schemaSourceProvider));
+ this.capabilities = capabilities;
+ }
+
+ @Override
+ public YangSourceContext resolveContext() {
+ for (QName capability : capabilities) {
+ resolveCapability(capability);
+ }
+ return createSourceContext();
+ }
+
+ private void resolveCapability(final QName capability) {
+ super.resolveSource(capability.getLocalName(), Optional.fromNullable(capability.getFormattedRevision()));
+ }
+
+ @Override
+ public Optional<YangModelDependencyInfo> getDependencyInfo(final SourceIdentifier identifier) {
+ Optional<InputStream> source = getSchemaSource(identifier);
+ if (source.isPresent()) {
+ return Optional.of(YangModelDependencyInfo.fromInputStream(source.get()));
+ }
+ return Optional.absent();
+ }
+
+ private Optional<InputStream> getSchemaSource(final SourceIdentifier identifier) {
+ return getSourceProvider().getSchemaSource(identifier.getName(),
+ Optional.fromNullable(identifier.getRevision()));
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/eplv10.html
+ */
+package org.opendaylight.yangtools.yang.parser.impl.util;
+
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.opendaylight.yangtools.yang.model.util.repo.SourceIdentifier;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableMap;
+
+public final class YangSourceFromDependencyInfoResolver extends YangSourceContextResolver {
+
+ private final Map<SourceIdentifier, YangModelDependencyInfo> dependencyInfo;
+
+ public YangSourceFromDependencyInfoResolver(final Map<SourceIdentifier, YangModelDependencyInfo> moduleDependencies) {
+ dependencyInfo = ImmutableMap.copyOf(moduleDependencies);
+ }
+
+ @Override
+ public Optional<YangModelDependencyInfo> getDependencyInfo(final SourceIdentifier identifier) {
+ if (identifier.getRevision() != null) {
+ return Optional.fromNullable(dependencyInfo.get(identifier));
+ }
+ YangModelDependencyInfo potential = dependencyInfo.get(identifier);
+ if (potential == null) {
+ for (Entry<SourceIdentifier, YangModelDependencyInfo> newPotential : dependencyInfo.entrySet()) {
+ String newPotentialName = newPotential.getKey().getName();
+
+ if (newPotentialName.equals(identifier.getName())) {
+ String newPotentialRevision = newPotential.getKey().getRevision();
+ if (potential == null || 1 == newPotentialRevision.compareTo(potential.getFormattedRevision())) {
+ potential = newPotential.getValue();
+ }
+ }
+ }
+ }
+ return Optional.fromNullable(potential);
+ }
+
+ @Override
+ public YangSourceContext resolveContext() {
+ for (SourceIdentifier source : dependencyInfo.keySet()) {
+ resolveSource(source);
+ }
+ return createSourceContext();
+ }
+}
}
}
- SchemaPath newSchemaPath = new SchemaPath(newPath, true);
+ SchemaPath newSchemaPath = SchemaPath.create(newPath, true);
return new DataBean(newQName, newSchemaPath);
}
*/
package org.opendaylight.yangtools.yang.parser.util;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Function;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
import java.net.URI;
-import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
+import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.ModuleImport;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Function;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-
/**
* Creates a module dependency graph from provided {@link ModuleBuilder}s and
* provides a {@link #sort(ModuleBuilder...)} method. It is topological sort and
private ModuleDependencySort() {
}
+ /**
+ * Extracts {@link ModuleBuilder} from a {@link ModuleNodeImpl}.
+ */
+ private static final Function<Node, ModuleBuilder> NODE_TO_MODULEBUILDER = new Function<Node, ModuleBuilder>() {
+ @Override
+ public ModuleBuilder apply(final Node input) {
+ // Cast to ModuleBuilder from Node and return
+ return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
+ }
+ };
+
/**
* Topological sort of module builder dependency graph.
*
* @return Sorted list of Module builders. Modules can be further processed
* in returned order.
*/
- public static List<ModuleBuilder> sort(ModuleBuilder... builders) {
+ public static List<ModuleBuilder> sort(final ModuleBuilder... builders) {
List<Node> sorted = sortInternal(Arrays.asList(builders));
- // Cast to ModuleBuilder from Node and return
- return Lists.transform(sorted, new Function<Node, ModuleBuilder>() {
-
- @Override
- public ModuleBuilder apply(Node input) {
- return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
- }
- });
+ return Lists.transform(sorted, NODE_TO_MODULEBUILDER);
}
- public static List<ModuleBuilder> sort(Collection<ModuleBuilder> builders) {
+ public static List<ModuleBuilder> sort(final Collection<ModuleBuilder> builders) {
ModuleBuilder[] array = new ModuleBuilder[builders.size()];
builders.toArray(array);
return sort(array);
}
- public static List<ModuleBuilder> sortWithContext(SchemaContext context, ModuleBuilder... builders) {
+ public static List<ModuleBuilder> sortWithContext(final SchemaContext context, final ModuleBuilder... builders) {
List<Object> modules = new ArrayList<Object>();
Collections.addAll(modules, builders);
modules.addAll(context.getModules());
return Lists.transform(sorted, new Function<Node, ModuleBuilder>() {
@Override
- public ModuleBuilder apply(Node input) {
+ public ModuleBuilder apply(final Node input) {
if (((ModuleNodeImpl) input).getReference() instanceof ModuleBuilder) {
return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
} else {
* @return Sorted list of Modules. Modules can be further processed in
* returned order.
*/
- public static List<Module> sort(Module... modules) {
+ public static List<Module> sort(final Module... modules) {
List<Node> sorted = sortInternal(Arrays.asList(modules));
// Cast to Module from Node and return
return Lists.transform(sorted, new Function<Node, Module>() {
@Override
- public Module apply(Node input) {
+ public Module apply(final Node input) {
return (Module) ((ModuleNodeImpl) input).getReference();
}
});
}
- private static List<Node> sortInternal(List<?> modules) {
+ private static List<Node> sortInternal(final List<?> modules) {
Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = createModuleGraph(modules);
Set<Node> nodes = Sets.newHashSet();
}
@VisibleForTesting
- static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(List<?> builders) {
+ static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(final List<?> builders) {
Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = Maps.newHashMap();
processModules(moduleGraph, builders);
/**
* Extract module:revision from module builders
*/
- private static void processDependencies(Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, List<?> builders) {
+ private static void processDependencies(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, final List<?> builders) {
Map<URI, Object> allNS = new HashMap<>();
// Create edges in graph
/**
* Get imported module by its name and revision from moduleGraph
*/
- private static ModuleNodeImpl getModuleByNameAndRevision(Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
- String fromName, Date fromRevision, String toName, Date toRevision) {
+ private static ModuleNodeImpl getModuleByNameAndRevision(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
+ final String fromName, final Date fromRevision, final String toName, final Date toRevision) {
ModuleNodeImpl to = null;
if (moduleGraph.get(toName) == null || !moduleGraph.get(toName).containsKey(toRevision)) {
if (moduleGraph.get(toName) != null && !moduleGraph.get(toName).isEmpty()
&& toRevision.equals(DEFAULT_REVISION)) {
to = moduleGraph.get(toName).values().iterator().next();
- LOGGER.debug(String
+ LOGGER.trace(String
.format("Import:%s:%s by module:%s:%s does not specify revision, using:%s:%s for module dependency sort",
toName, formatRevDate(toRevision), fromName, formatRevDate(fromRevision), to.getName(),
formatRevDate(to.getRevision())));
return to;
}
- private static void ex(String message) {
+ private static void ex(final String message) {
throw new YangValidationException(message);
}
* Extract dependencies from module builders or modules to fill dependency
* graph
*/
- private static void processModules(Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, List<?> builders) {
+ private static void processModules(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, final List<?> builders) {
// Process nodes
for (Object mb : builders) {
}
}
- private static String formatRevDate(Date rev) {
- return rev.equals(DEFAULT_REVISION) ? "default" : new SimpleDateFormat("yyyy-MM-dd").format(rev);
+ private static String formatRevDate(final Date rev) {
+ return rev.equals(DEFAULT_REVISION) ? "default" : SimpleDateFormatUtil.getRevisionFormat().format(rev);
}
@VisibleForTesting
private final Date revision;
private final Object originalObject;
- public ModuleNodeImpl(String name, Date revision, Object builder) {
+ public ModuleNodeImpl(final String name, final Date revision, final Object builder) {
this.name = name;
this.revision = revision;
this.originalObject = builder;
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
package org.opendaylight.yangtools.yang.parser.util;
-import org.apache.commons.io.IOUtils;
-
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
+import org.apache.commons.io.IOUtils;
public class NamedByteArrayInputStream extends ByteArrayInputStream implements NamedInputStream {
private final String toString;
- private NamedByteArrayInputStream(byte[] buf, String toString) {
+ public NamedByteArrayInputStream(byte[] buf, String toString) {
super(buf);
this.toString = toString;
}
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
-import org.opendaylight.yangtools.antlrv4.code.gen.*;
+import org.opendaylight.yangtools.antlrv4.code.gen.YangParser;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Argument_stmtContext;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Base_stmtContext;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Bit_stmtContext;
return result;
}
- public static String stringFromStringContext(StringContext context) {
+ public static String stringFromStringContext(final StringContext context) {
StringBuilder str = new StringBuilder();
for (TerminalNode stringNode : context.STRING()) {
String result = stringNode.getText();
* @return SchemaPath object
*/
public static SchemaPath createActualSchemaPath(final Stack<QName> actualPath) {
- final List<QName> path = new ArrayList<>(actualPath);
- return new SchemaPath(path, true);
+ return SchemaPath.create(actualPath, true);
}
/**
private String description;
private String reference;
private Status status;
- private List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
+ private final List<UnknownSchemaNode> unknownNodes = Collections.emptyList();
private String name;
private Integer value;
}
@Override
- public boolean equals(Object obj) {
+ public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
* @return 'fraction-digits' value if present in given context, null
* otherwise
*/
- private static Integer getFractionDigits(Type_body_stmtsContext ctx, String moduleName) {
+ private static Integer getFractionDigits(final Type_body_stmtsContext ctx, final String moduleName) {
Integer result = null;
for (int i = 0; i < ctx.getChildCount(); i++) {
ParseTree dec64specChild = ctx.getChild(i);
* name of current module
* @return fraction-digits value as Integer
*/
- private static Integer parseFractionDigits(Decimal64_specificationContext ctx, String moduleName) {
+ private static Integer parseFractionDigits(final Decimal64_specificationContext ctx, final String moduleName) {
Integer result = null;
for (int i = 0; i < ctx.getChildCount(); i++) {
ParseTree fdChild = ctx.getChild(i);
* current module name
* @return List of Bit objects created from this context
*/
- private static List<BitsTypeDefinition.Bit> getBits(Type_body_stmtsContext ctx, Stack<QName> actualPath,
- String moduleName) {
+ private static List<BitsTypeDefinition.Bit> getBits(final Type_body_stmtsContext ctx, final Stack<QName> actualPath,
+ final String moduleName) {
final List<BitsTypeDefinition.Bit> bits = new ArrayList<>();
for (int j = 0; j < ctx.getChildCount(); j++) {
ParseTree bitsSpecChild = ctx.getChild(j);
* current module name
* @return Bit object parsed from this context
*/
- private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx, long highestPosition,
- Stack<QName> actualPath, final String moduleName) {
+ private static BitsTypeDefinition.Bit parseBit(final Bit_stmtContext ctx, final long highestPosition,
+ final Stack<QName> actualPath, final String moduleName) {
String name = stringFromNode(ctx);
Long position = null;
* Ordered_by_stmtContext
* @return true, if ordered-by contains value 'user', false otherwise
*/
- public static boolean parseUserOrdered(Ordered_by_stmtContext ctx) {
+ public static boolean parseUserOrdered(final Ordered_by_stmtContext ctx) {
boolean result = false;
for (int j = 0; j < ctx.getChildCount(); j++) {
ParseTree orderArg = ctx.getChild(j);
return result;
}
- private static boolean getParentConfig(Builder node) {
+ private static boolean getParentConfig(final Builder node) {
Builder parent = node.getParent();
boolean config = false;
List<QName> path = new ArrayList<>(actualPath);
path.add(new QName(namespace, revision, prefix, typeName));
- SchemaPath schemaPath = new SchemaPath(path, true);
+ SchemaPath schemaPath = SchemaPath.create(path, true);
QName qname = schemaPath.getPath().get(schemaPath.getPath().size() - 1);
ExtendedType.Builder typeBuilder = new ExtendedType.Builder(qname, baseType, "", "", schemaPath);
return typeBuilder.build();
}
- private static SchemaPath createTypePath(Stack<QName> actual, String typeName) {
+ private static SchemaPath createTypePath(final Stack<QName> actual, final String typeName) {
QName last = actual.peek();
QName typeQName = new QName(last.getNamespace(), last.getRevision(), last.getPrefix(), typeName);
List<QName> path = new ArrayList<>(actual);
path.add(typeQName);
- return new SchemaPath(path, true);
+ return SchemaPath.create(path, true);
}
- private static SchemaPath createBaseTypePath(Stack<QName> actual, String typeName) {
+ private static SchemaPath createBaseTypePath(final Stack<QName> actual, final String typeName) {
List<QName> path = new ArrayList<>(actual);
path.add(BaseTypes.constructQName(typeName));
- return new SchemaPath(path, true);
+ return SchemaPath.create(path, true);
}
- private static SchemaPath createExtendedBaseTypePath(Stack<QName> actual, URI namespace, Date revision,
- String prefix, String typeName) {
+ private static SchemaPath createExtendedBaseTypePath(final Stack<QName> actual, final URI namespace, final Date revision,
+ final String prefix, final String typeName) {
QName extTypeName = new QName(namespace, revision, prefix, typeName);
QName baseTypeName = BaseTypes.constructQName(typeName);
List<QName> path = new ArrayList<>(actual);
path.add(extTypeName);
path.add(baseTypeName);
- return new SchemaPath(path, true);
+ return SchemaPath.create(path, true);
}
/**
* type body
* @return identityref base value as String
*/
- public static String getIdentityrefBase(Type_body_stmtsContext ctx) {
+ public static String getIdentityrefBase(final Type_body_stmtsContext ctx) {
String result = null;
outer: for (int i = 0; i < ctx.getChildCount(); i++) {
ParseTree child = ctx.getChild(i);
* type body context
* @return require-instance value
*/
- private static boolean isRequireInstance(Type_body_stmtsContext ctx) {
+ private static boolean isRequireInstance(final Type_body_stmtsContext ctx) {
for (int i = 0; i < ctx.getChildCount(); i++) {
ParseTree child = ctx.getChild(i);
if (child instanceof Instance_identifier_specificationContext) {
* type body context
* @return leafref path as String
*/
- private static String parseLeafrefPath(Type_body_stmtsContext ctx) {
+ private static String parseLeafrefPath(final Type_body_stmtsContext ctx) {
for (int i = 0; i < ctx.getChildCount(); i++) {
ParseTree child = ctx.getChild(i);
if (child instanceof Leafref_specificationContext) {
}
}
- private static Integer parseMinElements(Min_elements_stmtContext ctx, String moduleName) {
+ private static Integer parseMinElements(final Min_elements_stmtContext ctx, final String moduleName) {
Integer result = null;
try {
for (int i = 0; i < ctx.getChildCount(); i++) {
}
}
- private static Integer parseMaxElements(Max_elements_stmtContext ctx, String moduleName) {
+ private static Integer parseMaxElements(final Max_elements_stmtContext ctx, final String moduleName) {
Integer result = null;
try {
for (int i = 0; i < ctx.getChildCount(); i++) {
* context to parse
* @return true if value is 'true', false otherwise
*/
- public static boolean parseYinValue(Argument_stmtContext ctx) {
+ public static boolean parseYinValue(final Argument_stmtContext ctx) {
boolean yinValue = false;
outer: for (int i = 0; i < ctx.getChildCount(); i++) {
ParseTree yin = ctx.getChild(i);
* name of current module
* @return RefineHolder object representing this refine statement
*/
- public static RefineHolder parseRefine(Refine_stmtContext refineCtx, String moduleName) {
+ public static RefineHolder parseRefine(final Refine_stmtContext refineCtx, final String moduleName) {
final String refineTarget = stringFromNode(refineCtx);
final RefineHolder refine = new RefineHolder(moduleName, refineCtx.getStart().getLine(), refineTarget);
for (int i = 0; i < refineCtx.getChildCount(); i++) {
return refine;
}
- private static void parseRefineDefault(RefineHolder refine, ParseTree refineStmt) {
+ private static void parseRefineDefault(final RefineHolder refine, final ParseTree refineStmt) {
for (int i = 0; i < refineStmt.getChildCount(); i++) {
ParseTree refineArg = refineStmt.getChild(i);
if (refineArg instanceof Description_stmtContext) {
}
}
- private static RefineHolder parseRefine(RefineHolder refine, Refine_leaf_stmtsContext refineStmt) {
+ private static RefineHolder parseRefine(final RefineHolder refine, final Refine_leaf_stmtsContext refineStmt) {
for (int i = 0; i < refineStmt.getChildCount(); i++) {
ParseTree refineArg = refineStmt.getChild(i);
if (refineArg instanceof Default_stmtContext) {
return refine;
}
- private static RefineHolder parseRefine(RefineHolder refine, Refine_container_stmtsContext refineStmt) {
+ private static RefineHolder parseRefine(final RefineHolder refine, final Refine_container_stmtsContext refineStmt) {
for (int i = 0; i < refineStmt.getChildCount(); i++) {
ParseTree refineArg = refineStmt.getChild(i);
if (refineArg instanceof Must_stmtContext) {
return refine;
}
- private static RefineHolder parseRefine(RefineHolder refine, Refine_list_stmtsContext refineStmt) {
+ private static RefineHolder parseRefine(final RefineHolder refine, final Refine_list_stmtsContext refineStmt) {
for (int i = 0; i < refineStmt.getChildCount(); i++) {
ParseTree refineArg = refineStmt.getChild(i);
if (refineArg instanceof Must_stmtContext) {
return refine;
}
- private static RefineHolder parseRefine(RefineHolder refine, Refine_leaf_list_stmtsContext refineStmt) {
+ private static RefineHolder parseRefine(final RefineHolder refine, final Refine_leaf_list_stmtsContext refineStmt) {
for (int i = 0; i < refineStmt.getChildCount(); i++) {
ParseTree refineArg = refineStmt.getChild(i);
if (refineArg instanceof Must_stmtContext) {
return refine;
}
- private static RefineHolder parseRefine(RefineHolder refine, Refine_choice_stmtsContext refineStmt) {
+ private static RefineHolder parseRefine(final RefineHolder refine, final Refine_choice_stmtsContext refineStmt) {
for (int i = 0; i < refineStmt.getChildCount(); i++) {
ParseTree refineArg = refineStmt.getChild(i);
if (refineArg instanceof Default_stmtContext) {
return refine;
}
- private static RefineHolder parseRefine(RefineHolder refine, Refine_anyxml_stmtsContext refineStmt) {
+ private static RefineHolder parseRefine(final RefineHolder refine, final Refine_anyxml_stmtsContext refineStmt) {
for (int i = 0; i < refineStmt.getChildCount(); i++) {
ParseTree refineArg = refineStmt.getChild(i);
if (refineArg instanceof Must_stmtContext) {
return refine;
}
- public static String getArgumentString(org.antlr.v4.runtime.ParserRuleContext ctx) {
+ public static String getArgumentString(final org.antlr.v4.runtime.ParserRuleContext ctx) {
List<StringContext> potentialValues = ctx.getRuleContexts(StringContext.class);
checkState(!potentialValues.isEmpty());
return ParserListenerUtils.stringFromStringContext(potentialValues.get(0));
}
- public static <T extends ParserRuleContext> Optional<T> getFirstContext(ParserRuleContext context,Class<T> contextType) {
+ public static <T extends ParserRuleContext> Optional<T> getFirstContext(final ParserRuleContext context,final Class<T> contextType) {
List<T> potential = context.getRuleContexts(contextType);
if(potential.isEmpty()) {
return Optional.absent();
*/
package org.opendaylight.yangtools.yang.parser.util;
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Collections2;
-import com.google.common.io.ByteSource;
+import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
+
import org.apache.commons.io.IOUtils;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.common.base.Function;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+import com.google.common.collect.Collections2;
+import com.google.common.io.ByteSource;
+
public final class ParserUtils {
private static final Logger LOG = LoggerFactory.getLogger(ParserUtils.class);
+ private static final Splitter SLASH_SPLITTER = Splitter.on('/');
+ private static final Splitter COLON_SPLITTER = Splitter.on(':');
private ParserUtils() {
}
- public static Collection<ByteSource> streamsToByteSources(Collection<InputStream> streams) {
- return Collections2.transform(streams, new Function<InputStream, ByteSource>() {
- @Override
- public ByteSource apply(final InputStream input) {
- return new ByteSource() {
- @Override
- public InputStream openStream() throws IOException {
- return NamedByteArrayInputStream.create(input);
- }
- };
- }
- });
+ public static Collection<ByteSource> streamsToByteSources(final Collection<InputStream> streams) throws IOException {
+ Collection<ByteSource> result = new HashSet<>();
+ for (InputStream stream : streams) {
+ result.add(new ByteSourceImpl(stream));
+ }
+ return result;
}
public static ByteSource fileToByteSource(final File file) {
};
}
- public static Collection<ByteSource> filesToByteSources(Collection<File> streams) throws FileNotFoundException {
+ public static Collection<ByteSource> filesToByteSources(final Collection<File> streams) throws FileNotFoundException {
return Collections2.transform(streams, new Function<File, ByteSource>() {
@Override
public ByteSource apply(final File input) {
* @param sourceToBuilder
* source to module mapping
*/
- public static void setSourceToBuilder(Map<ByteSource, ModuleBuilder> sourceToBuilder) throws IOException {
+ public static void setSourceToBuilder(final Map<ByteSource, ModuleBuilder> sourceToBuilder) throws IOException {
for (Map.Entry<ByteSource, ModuleBuilder> entry : sourceToBuilder.entrySet()) {
ModuleBuilder builder = entry.getValue();
ByteSource source = entry.getKey();
* @param qname
* one or more qnames added to base path
* @return new SchemaPath from given path and qname
+ *
+ * @deprecated Use {@link SchemaPath#createChild(QName...)} instead.
*/
- public static SchemaPath createSchemaPath(SchemaPath schemaPath, QName... qname) {
+ @Deprecated
+ public static SchemaPath createSchemaPath(final SchemaPath schemaPath, final QName... qname) {
List<QName> path = new ArrayList<>(schemaPath.getPath());
path.addAll(Arrays.asList(qname));
- return new SchemaPath(path, schemaPath.isAbsolute());
+ return SchemaPath.create(path, schemaPath.isAbsolute());
}
/**
* prefix associated with import
* @return ModuleImport based on given prefix
*/
- public static ModuleImport getModuleImport(ModuleBuilder builder, String prefix) {
+ public static ModuleImport getModuleImport(final ModuleBuilder builder, final String prefix) {
for (ModuleImport mi : builder.getModuleImports()) {
if (mi.getPrefix().equals(prefix)) {
return mi;
* current line in yang model
* @return module builder if found, null otherwise
*/
- public static ModuleBuilder findModuleFromBuilders(Map<String, TreeMap<Date, ModuleBuilder>> modules,
- ModuleBuilder module, String prefix, int line) {
+ public static ModuleBuilder findModuleFromBuilders(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
+ final ModuleBuilder module, final String prefix, final int line) {
ModuleBuilder dependentModule = null;
Date dependentModuleRevision = null;
* current line in yang model
* @return module based on given prefix if found in context, null otherwise
*/
- public static Module findModuleFromContext(SchemaContext context, ModuleBuilder currentModule, String prefix,
- int line) {
+ public static Module findModuleFromContext(final SchemaContext context, final ModuleBuilder currentModule, final String prefix,
+ final int line) {
if (context == null) {
throw new YangParseException(currentModule.getName(), line, "Cannot find module with prefix '" + prefix
+ "'.");
* XPath as String
* @return SchemaPath from given String
*/
- public static SchemaPath parseXPathString(String xpathString) {
- boolean absolute = xpathString.startsWith("/");
- String[] splittedPath = xpathString.split("/");
- List<QName> path = new ArrayList<QName>();
- QName name;
- for (String pathElement : splittedPath) {
+ public static SchemaPath parseXPathString(final String xpathString) {
+ final boolean absolute = xpathString.indexOf('/') == 0;
+
+ final List<QName> path = new ArrayList<QName>();
+ for (String pathElement : SLASH_SPLITTER.split(xpathString)) {
if (pathElement.length() > 0) {
- String[] splittedElement = pathElement.split(":");
- if (splittedElement.length == 1) {
- name = new QName(null, null, null, splittedElement[0]);
+ final Iterator<String> it = COLON_SPLITTER.split(pathElement).iterator();
+ final String s = it.next();
+
+ final QName name;
+ if (it.hasNext()) {
+ name = new QName(null, null, s, it.next());
} else {
- name = new QName(null, null, splittedElement[0], splittedElement[1]);
+ name = new QName(null, null, null, s);
}
path.add(name);
}
}
- return new SchemaPath(path, absolute);
+ return SchemaPath.create(path, absolute);
}
/**
* @param target
* augmentation target node
*/
- public static void fillAugmentTarget(AugmentationSchemaBuilder augment, Builder target) {
+ public static void fillAugmentTarget(final AugmentationSchemaBuilder augment, final Builder target) {
if (target instanceof DataNodeContainerBuilder) {
fillAugmentTarget(augment, (DataNodeContainerBuilder) target);
} else if (target instanceof ChoiceBuilder) {
* @param target
* augmentation target node
*/
- private static void fillAugmentTarget(AugmentationSchemaBuilder augment, DataNodeContainerBuilder target) {
+ private static void fillAugmentTarget(final AugmentationSchemaBuilder augment, final DataNodeContainerBuilder target) {
for (DataSchemaNodeBuilder child : augment.getChildNodeBuilders()) {
DataSchemaNodeBuilder childCopy = CopyUtils.copy(child, target, false);
if (augment.getParent() instanceof UsesNodeBuilder) {
* @param target
* augmentation target choice node
*/
- private static void fillAugmentTarget(AugmentationSchemaBuilder augment, ChoiceBuilder target) {
+ private static void fillAugmentTarget(final AugmentationSchemaBuilder augment, final ChoiceBuilder target) {
for (DataSchemaNodeBuilder builder : augment.getChildNodeBuilders()) {
DataSchemaNodeBuilder childCopy = CopyUtils.copy(builder, target, false);
if (augment.getParent() instanceof UsesNodeBuilder) {
*
* @param node
*/
- private static void setNodeAugmenting(DataSchemaNodeBuilder node) {
+ private static void setNodeAugmenting(final DataSchemaNodeBuilder node) {
node.setAugmenting(true);
if (node instanceof DataNodeContainerBuilder) {
DataNodeContainerBuilder dataNodeChild = (DataNodeContainerBuilder) node;
*
* @param node
*/
- public static void setNodeAddedByUses(GroupingMember node) {
+ public static void setNodeAddedByUses(final GroupingMember node) {
node.setAddedByUses(true);
if (node instanceof DataNodeContainerBuilder) {
DataNodeContainerBuilder dataNodeChild = (DataNodeContainerBuilder) node;
* @param config
* new config value
*/
- public static void setNodeConfig(DataSchemaNodeBuilder node, Boolean config) {
+ public static void setNodeConfig(final DataSchemaNodeBuilder node, final Boolean config) {
if (node instanceof ContainerSchemaNodeBuilder || node instanceof LeafSchemaNodeBuilder
|| node instanceof LeafListSchemaNodeBuilder || node instanceof ListSchemaNodeBuilder
|| node instanceof ChoiceBuilder || node instanceof AnyXmlBuilder) {
}
}
- public static DataSchemaNodeBuilder findSchemaNode(List<QName> path, SchemaNodeBuilder parentNode) {
+ public static DataSchemaNodeBuilder findSchemaNode(final List<QName> path, final SchemaNodeBuilder parentNode) {
DataSchemaNodeBuilder node = null;
SchemaNodeBuilder parent = parentNode;
int i = 0;
return node;
}
- public static SchemaNodeBuilder findSchemaNodeInModule(List<QName> pathToNode, ModuleBuilder module) {
+ public static SchemaNodeBuilder findSchemaNodeInModule(final List<QName> pathToNode, final ModuleBuilder module) {
List<QName> path = new ArrayList<>(pathToNode);
QName first = path.remove(0);
* path to augment target
* @return true if augmentation process succeed, false otherwise
*/
- public static boolean processAugmentation(AugmentationSchemaBuilder augment, ModuleBuilder firstNodeParent) {
+ public static boolean processAugmentation(final AugmentationSchemaBuilder augment, final ModuleBuilder firstNodeParent) {
List<QName> path = augment.getTargetPath().getPath();
Builder targetNode = findSchemaNodeInModule(path, firstNodeParent);
if (targetNode == null) {
return true;
}
- public static IdentitySchemaNodeBuilder findBaseIdentity(Map<String, TreeMap<Date, ModuleBuilder>> modules,
- ModuleBuilder module, String baseString, int line) {
- IdentitySchemaNodeBuilder result = null;
- if (baseString.contains(":")) {
- String[] splittedBase = baseString.split(":");
- if (splittedBase.length > 2) {
+ public static IdentitySchemaNodeBuilder findBaseIdentity(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
+ final ModuleBuilder module, final String baseString, final int line) {
+
+ // FIXME: optimize indexOf() away?
+ if (baseString.indexOf(':') != -1) {
+ final Iterator<String> it = COLON_SPLITTER.split(baseString).iterator();
+ final String prefix = it.next();
+ final String name = it.next();
+
+ if (it.hasNext()) {
throw new YangParseException(module.getName(), line, "Failed to parse identityref base: " + baseString);
}
- String prefix = splittedBase[0];
- String name = splittedBase[1];
+
ModuleBuilder dependentModule = findModuleFromBuilders(modules, module, prefix, line);
- if (dependentModule != null) {
- result = findIdentity(dependentModule.getAddedIdentities(), name);
+ if (dependentModule == null) {
+ return null;
}
+
+ return findIdentity(dependentModule.getAddedIdentities(), name);
} else {
- result = findIdentity(module.getAddedIdentities(), baseString);
+ return findIdentity(module.getAddedIdentities(), baseString);
}
- return result;
}
- public static IdentitySchemaNodeBuilder findIdentity(Set<IdentitySchemaNodeBuilder> identities, String name) {
+ public static IdentitySchemaNodeBuilder findIdentity(final Set<IdentitySchemaNodeBuilder> identities, final String name) {
for (IdentitySchemaNodeBuilder identity : identities) {
if (identity.getQName().getLocalName().equals(name)) {
return identity;
* @param node
* @return builder of module where this node is defined
*/
- public static ModuleBuilder getParentModule(Builder node) {
+ public static ModuleBuilder getParentModule(final Builder node) {
if (node instanceof ModuleBuilder) {
return (ModuleBuilder) node;
}
return parentModule;
}
- public static Set<DataSchemaNodeBuilder> wrapChildNodes(String moduleName, int line, Set<DataSchemaNode> nodes,
- SchemaPath parentPath, URI ns, Date rev, String pref) {
+ public static Set<DataSchemaNodeBuilder> wrapChildNodes(final String moduleName, final int line, final Set<DataSchemaNode> nodes,
+ final SchemaPath parentPath, final URI ns, final Date rev, final String pref) {
Set<DataSchemaNodeBuilder> result = new HashSet<>();
for (DataSchemaNode node : nodes) {
return result;
}
- public static DataSchemaNodeBuilder wrapChildNode(String moduleName, int line, DataSchemaNode node,
- SchemaPath parentPath, QName qname) {
- List<QName> path = new ArrayList<>(parentPath.getPath());
- path.add(qname);
- SchemaPath schemaPath = new SchemaPath(path, parentPath.isAbsolute());
+ public static DataSchemaNodeBuilder wrapChildNode(final String moduleName, final int line, final DataSchemaNode node,
+ final SchemaPath parentPath, final QName qname) {
+
+ final SchemaPath schemaPath = parentPath.createChild(qname);
if (node instanceof AnyXmlSchemaNode) {
return new AnyXmlBuilder(moduleName, line, qname, schemaPath, ((AnyXmlSchemaNode) node));
}
}
- public static Set<GroupingBuilder> wrapGroupings(String moduleName, int line, Set<GroupingDefinition> nodes,
- SchemaPath parentPath, URI ns, Date rev, String pref) {
+ public static Set<GroupingBuilder> wrapGroupings(final String moduleName, final int line, final Set<GroupingDefinition> nodes,
+ final SchemaPath parentPath, final URI ns, final Date rev, final String pref) {
Set<GroupingBuilder> result = new HashSet<>();
for (GroupingDefinition node : nodes) {
QName qname = new QName(ns, rev, pref, node.getQName().getLocalName());
- List<QName> path = new ArrayList<>(parentPath.getPath());
- path.add(qname);
- SchemaPath schemaPath = new SchemaPath(path, parentPath.isAbsolute());
+ SchemaPath schemaPath = parentPath.createChild(qname);
result.add(new GroupingBuilderImpl(moduleName, line, qname, schemaPath, node));
}
return result;
}
- public static Set<TypeDefinitionBuilder> wrapTypedefs(String moduleName, int line, DataNodeContainer dataNode,
- SchemaPath parentPath, URI ns, Date rev, String pref) {
+ public static Set<TypeDefinitionBuilder> wrapTypedefs(final String moduleName, final int line, final DataNodeContainer dataNode,
+ final SchemaPath parentPath, final URI ns, final Date rev, final String pref) {
Set<TypeDefinition<?>> nodes = dataNode.getTypeDefinitions();
Set<TypeDefinitionBuilder> result = new HashSet<>();
for (TypeDefinition<?> node : nodes) {
QName qname = new QName(ns, rev, pref, node.getQName().getLocalName());
List<QName> path = new ArrayList<>(parentPath.getPath());
path.add(qname);
- SchemaPath schemaPath = new SchemaPath(path, parentPath.isAbsolute());
+ SchemaPath schemaPath = SchemaPath.create(path, parentPath.isAbsolute());
result.add(new TypeDefinitionBuilderImpl(moduleName, line, qname, schemaPath, ((ExtendedType) node)));
}
return result;
}
- public static List<UnknownSchemaNodeBuilder> wrapUnknownNodes(String moduleName, int line,
- List<UnknownSchemaNode> nodes, SchemaPath parentPath, URI ns, Date rev, String pref) {
+ public static List<UnknownSchemaNodeBuilder> wrapUnknownNodes(final String moduleName, final int line,
+ final List<UnknownSchemaNode> nodes, final SchemaPath parentPath, final URI ns, final Date rev, final String pref) {
List<UnknownSchemaNodeBuilder> result = new ArrayList<>();
for (UnknownSchemaNode node : nodes) {
QName qname = new QName(ns, rev, pref, node.getQName().getLocalName());
List<QName> path = new ArrayList<>(parentPath.getPath());
path.add(qname);
- SchemaPath schemaPath = new SchemaPath(path, parentPath.isAbsolute());
+ SchemaPath schemaPath = SchemaPath.create(path, parentPath.isAbsolute());
result.add(new UnknownSchemaNodeBuilder(moduleName, line, qname, schemaPath, node));
}
return result;
}
+ private static final class ByteSourceImpl extends ByteSource {
+ private final String toString;
+ private final ByteArrayOutputStream output = new ByteArrayOutputStream();
+
+ private ByteSourceImpl(InputStream input) throws IOException {
+ toString = input.toString();
+ IOUtils.copy(input, output);
+ }
+
+ @Override
+ public InputStream openStream() throws IOException {
+ return new NamedByteArrayInputStream(output.toByteArray(), toString);
+ }
+ }
+
}
*/
package org.opendaylight.yangtools.yang.validator;
-import java.text.DateFormat;
import java.text.ParseException;
-import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yang_version_stmtContext;
+import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
import org.opendaylight.yangtools.yang.parser.util.YangValidationException;
import com.google.common.collect.Sets;
private BasicValidations() {
}
- static void checkNotPresentBoth(ParseTree parent, Class<? extends ParseTree> childType1,
- Class<? extends ParseTree> childType2) {
+ static void checkNotPresentBoth(final ParseTree parent, final Class<? extends ParseTree> childType1,
+ final Class<? extends ParseTree> childType2) {
if (BasicValidations.checkPresentChildOfTypeSafe(parent, childType1, true)
&& BasicValidations.checkPresentChildOfTypeSafe(parent, childType2, false)) {
ValidationUtil.ex(ValidationUtil.f("(In (sub)module:%s) Both %s and %s statement present in %s:%s",
}
}
- static void checkOnlyPermittedValues(ParseTree ctx, Set<String> permittedValues) {
+ static void checkOnlyPermittedValues(final ParseTree ctx, final Set<String> permittedValues) {
String mandatory = ValidationUtil.getName(ctx);
String rootParentName = ValidationUtil.getRootParentName(ctx);
}
}
- static void checkUniquenessInNamespace(ParseTree stmt, Set<String> uniques) {
+ static void checkUniquenessInNamespace(final ParseTree stmt, final Set<String> uniques) {
String name = ValidationUtil.getName(stmt);
String rootParentName = ValidationUtil.getRootParentName(stmt);
* Check if only one module or submodule is present in session(one yang
* file)
*/
- static void checkOnlyOneModulePresent(String moduleName, String globalId) {
+ static void checkOnlyOneModulePresent(final String moduleName, final String globalId) {
if (globalId != null) {
ValidationUtil.ex(ValidationUtil.f("Multiple (sub)modules per file"));
}
}
- static void checkPresentYangVersion(ParseTree ctx, String moduleName) {
+ static void checkPresentYangVersion(final ParseTree ctx, final String moduleName) {
if (!checkPresentChildOfTypeSafe(ctx, Yang_version_stmtContext.class, true)) {
ValidationUtil.ex(ValidationUtil.f(
"Yang version statement not present in module:%s, Validating as yang version:%s", moduleName,
}
}
- static void checkDateFormat(ParseTree stmt, DateFormat format) {
+ static void checkDateFormat(final ParseTree stmt) {
try {
- format.parse(ValidationUtil.getName(stmt));
+ SimpleDateFormatUtil.getRevisionFormat().parse(ValidationUtil.getName(stmt));
} catch (ParseException e) {
String exceptionMessage = ValidationUtil.f(
"(In (sub)module:%s) %s:%s, invalid date format expected date format is:%s",
ValidationUtil.getRootParentName(stmt), ValidationUtil.getSimpleStatementName(stmt.getClass()),
- ValidationUtil.getName(stmt), new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
+ ValidationUtil.getName(stmt), SimpleDateFormatUtil.getRevisionFormat().format(new Date()));
ValidationUtil.ex(exceptionMessage);
}
}
private static Pattern identifierPattern = Pattern.compile("[a-zA-Z_][a-zA-Z0-9_.-]*");
- static void checkIdentifier(ParseTree statement) {
+ static void checkIdentifier(final ParseTree statement) {
checkIdentifierInternal(statement, ValidationUtil.getName(statement));
}
- static void checkIdentifierInternal(ParseTree statement, String name) {
+ static void checkIdentifierInternal(final ParseTree statement, final String name) {
if (!identifierPattern.matcher(name).matches()) {
String message = ValidationUtil.f("%s statement identifier:%s is not in required format:%s",
private static Pattern prefixedIdentifierPattern = Pattern.compile("(.+):(.+)");
- static void checkPrefixedIdentifier(ParseTree statement) {
+ static void checkPrefixedIdentifier(final ParseTree statement) {
checkPrefixedIdentifierInternal(statement, ValidationUtil.getName(statement));
}
- private static void checkPrefixedIdentifierInternal(ParseTree statement, String id) {
+ private static void checkPrefixedIdentifierInternal(final ParseTree statement, final String id) {
Matcher matcher = prefixedIdentifierPattern.matcher(id);
if (matcher.matches()) {
}
}
- static void checkSchemaNodeIdentifier(ParseTree statement) {
+ static void checkSchemaNodeIdentifier(final ParseTree statement) {
String id = ValidationUtil.getName(statement);
try {
String getMessage();
}
- static void checkPresentChildOfTypeInternal(ParseTree parent, Set<Class<? extends ParseTree>> expectedChildType,
- MessageProvider message, boolean atMostOne) {
+ static void checkPresentChildOfTypeInternal(final ParseTree parent, final Set<Class<? extends ParseTree>> expectedChildType,
+ final MessageProvider message, final boolean atMostOne) {
if (!checkPresentChildOfTypeSafe(parent, expectedChildType, atMostOne)) {
String str = atMostOne ? "(Expected exactly one statement) " + message.getMessage() : message.getMessage();
ValidationUtil.ex(str);
}
static void checkPresentChildOfType(final ParseTree parent, final Class<? extends ParseTree> expectedChildType,
- boolean atMostOne) {
+ final boolean atMostOne) {
// Construct message in checkPresentChildOfTypeInternal only if
// validaiton fails, not in advance
*/
private static class MessageProviderForSetOfChildTypes implements MessageProvider {
- private Set<Class<? extends ParseTree>> expectedChildTypes;
- private ParseTree parent;
+ private final Set<Class<? extends ParseTree>> expectedChildTypes;
+ private final ParseTree parent;
- public MessageProviderForSetOfChildTypes(Set<Class<? extends ParseTree>> expectedChildTypes, ParseTree parent) {
+ public MessageProviderForSetOfChildTypes(final Set<Class<? extends ParseTree>> expectedChildTypes, final ParseTree parent) {
this.expectedChildTypes = expectedChildTypes;
this.parent = parent;
}
};
static void checkPresentChildOfTypes(final ParseTree parent,
- final Set<Class<? extends ParseTree>> expectedChildTypes, boolean atMostOne) {
+ final Set<Class<? extends ParseTree>> expectedChildTypes, final boolean atMostOne) {
// Construct message in checkPresentChildOfTypeInternal only if
// validaiton fails, not in advance
checkPresentChildOfTypeInternal(parent, expectedChildTypes, message, atMostOne);
}
- static boolean checkPresentChildOfTypeSafe(ParseTree parent, Set<Class<? extends ParseTree>> expectedChildType,
- boolean atMostOne) {
+ static boolean checkPresentChildOfTypeSafe(final ParseTree parent, final Set<Class<? extends ParseTree>> expectedChildType,
+ final boolean atMostOne) {
int foundChildrenOfType = ValidationUtil.countPresentChildrenOfType(parent, expectedChildType);
return atMostOne ? foundChildrenOfType == 1 ? true : false : foundChildrenOfType != 0 ? true : false;
}
- static boolean checkPresentChildOfTypeSafe(ParseTree parent, Class<? extends ParseTree> expectedChildType,
- boolean atMostOne) {
+ static boolean checkPresentChildOfTypeSafe(final ParseTree parent, final Class<? extends ParseTree> expectedChildType,
+ final boolean atMostOne) {
int foundChildrenOfType = ValidationUtil.countPresentChildrenOfType(parent, expectedChildType);
return atMostOne ? foundChildrenOfType == 1 ? true : false : foundChildrenOfType != 0 ? true : false;
}
- static List<String> getAndCheckUniqueKeys(ParseTree ctx) {
+ static List<String> getAndCheckUniqueKeys(final ParseTree ctx) {
String key = ValidationUtil.getName(ctx);
ParseTree parent = ctx.getParent();
String rootParentName = ValidationUtil.getRootParentName(ctx);
import java.net.URI;
import java.net.URISyntaxException;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
+import java.util.HashSet;
import java.util.Set;
import org.antlr.v4.runtime.tree.ParseTree;
-import org.opendaylight.yangtools.antlrv4.code.gen.*;
+import org.opendaylight.yangtools.antlrv4.code.gen.YangParser;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Anyxml_stmtContext;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Argument_stmtContext;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Augment_stmtContext;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Unique_stmtContext;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Uses_stmtContext;
import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Yin_element_argContext;
+import org.opendaylight.yangtools.antlrv4.code.gen.YangParserBaseListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
*/
final class YangModelBasicValidationListener extends YangParserBaseListener {
private static final Logger LOGGER = LoggerFactory.getLogger(YangModelBasicValidationListener.class);
- private final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
-
- private final Set<String> uniquePrefixes;
- private final Set<String> uniqueImports;
- private final Set<String> uniqueIncludes;
+ private final Set<String> uniquePrefixes = new HashSet<>();
+ private final Set<String> uniqueImports = new HashSet<>();
+ private final Set<String> uniqueIncludes = new HashSet<>();
private String globalModuleId;
- YangModelBasicValidationListener() {
- super();
- uniquePrefixes = Sets.newHashSet();
- uniqueImports = Sets.newHashSet();
- uniqueIncludes = Sets.newHashSet();
- }
-
/**
* Constraints:
* <ol>
* </ol>
*/
@Override
- public void enterModule_stmt(Module_stmtContext ctx) {
+ public void enterModule_stmt(final Module_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
* </ol>
*/
@Override
- public void enterSubmodule_stmt(Submodule_stmtContext ctx) {
+ public void enterSubmodule_stmt(final Submodule_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
* </ol>
*/
@Override
- public void enterSubmodule_header_stmts(Submodule_header_stmtsContext ctx) {
+ public void enterSubmodule_header_stmts(final Submodule_header_stmtsContext ctx) {
BasicValidations.checkPresentChildOfType(ctx, Belongs_to_stmtContext.class, true);
// check Yang version present, if not log
* </ol>
*/
@Override
- public void enterModule_header_stmts(Module_header_stmtsContext ctx) {
+ public void enterModule_header_stmts(final Module_header_stmtsContext ctx) {
String moduleName = ValidationUtil.getRootParentName(ctx);
BasicValidations.checkPresentChildOfType(ctx, Namespace_stmtContext.class, true);
* </ol>
*/
@Override
- public void enterRevision_stmt(Revision_stmtContext ctx) {
- BasicValidations.checkDateFormat(ctx, SIMPLE_DATE_FORMAT);
+ public void enterRevision_stmt(final Revision_stmtContext ctx) {
+ BasicValidations.checkDateFormat(ctx);
}
* </ol>
*/
@Override
- public void enterBelongs_to_stmt(Belongs_to_stmtContext ctx) {
+ public void enterBelongs_to_stmt(final Belongs_to_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
BasicValidations.checkPresentChildOfType(ctx, Prefix_stmtContext.class, true);
* </ol>
*/
@Override
- public void enterNamespace_stmt(Namespace_stmtContext ctx) {
+ public void enterNamespace_stmt(final Namespace_stmtContext ctx) {
String namespaceName = ValidationUtil.getName(ctx);
String rootParentName = ValidationUtil.getRootParentName(ctx);
* </ol>
*/
@Override
- public void enterImport_stmt(Import_stmtContext ctx) {
+ public void enterImport_stmt(final Import_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
* </ol>
*/
@Override
- public void enterRevision_date_stmt(Revision_date_stmtContext ctx) {
- BasicValidations.checkDateFormat(ctx, SIMPLE_DATE_FORMAT);
+ public void enterRevision_date_stmt(final Revision_date_stmtContext ctx) {
+ BasicValidations.checkDateFormat(ctx);
}
/**
* </ol>
*/
@Override
- public void enterInclude_stmt(Include_stmtContext ctx) {
+ public void enterInclude_stmt(final Include_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
* </ol>
*/
@Override
- public void enterYang_version_stmt(YangParser.Yang_version_stmtContext ctx) {
+ public void enterYang_version_stmt(final YangParser.Yang_version_stmtContext ctx) {
String version = ValidationUtil.getName(ctx);
String rootParentName = ValidationUtil.getRootParentName(ctx);
if (!version.equals(BasicValidations.SUPPORTED_YANG_VERSION)) {
* </ol>
*/
@Override
- public void enterPrefix_stmt(Prefix_stmtContext ctx) {
+ public void enterPrefix_stmt(final Prefix_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
* </ol>
*/
@Override
- public void enterTypedef_stmt(Typedef_stmtContext ctx) {
+ public void enterTypedef_stmt(final Typedef_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
* </ol>
*/
@Override
- public void enterType_stmt(Type_stmtContext ctx) {
+ public void enterType_stmt(final Type_stmtContext ctx) {
BasicValidations.checkPrefixedIdentifier(ctx);
}
* </ol>
*/
@Override
- public void enterContainer_stmt(Container_stmtContext ctx) {
+ public void enterContainer_stmt(final Container_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
}
* </ol>
*/
@Override
- public void enterLeaf_stmt(Leaf_stmtContext ctx) {
+ public void enterLeaf_stmt(final Leaf_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
BasicValidations.checkPresentChildOfType(ctx, Type_stmtContext.class, true);
* </ol>
*/
@Override
- public void enterLeaf_list_stmt(Leaf_list_stmtContext ctx) {
+ public void enterLeaf_list_stmt(final Leaf_list_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
* </ol>
*/
@Override
- public void enterOrdered_by_arg(Ordered_by_argContext ctx) {
+ public void enterOrdered_by_arg(final Ordered_by_argContext ctx) {
BasicValidations.checkOnlyPermittedValues(ctx, PERMITTED_ORDER_BY_ARGS);
}
* </ol>
*/
@Override
- public void enterList_stmt(List_stmtContext ctx) {
+ public void enterList_stmt(final List_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
// TODO check: "if config==true then key must be present" could be
// performed
* </ol>
*/
@Override
- public void enterKey_stmt(Key_stmtContext ctx) {
+ public void enterKey_stmt(final Key_stmtContext ctx) {
BasicValidations.getAndCheckUniqueKeys(ctx);
}
* </ol>
*/
@Override
- public void enterUnique_stmt(Unique_stmtContext ctx) {
+ public void enterUnique_stmt(final Unique_stmtContext ctx) {
BasicValidations.getAndCheckUniqueKeys(ctx);
}
* </ol>
*/
@Override
- public void enterChoice_stmt(Choice_stmtContext ctx) {
+ public void enterChoice_stmt(final Choice_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
BasicValidations.checkNotPresentBoth(ctx, Mandatory_stmtContext.class, Default_stmtContext.class);
* </ol>
*/
@Override
- public void enterCase_stmt(Case_stmtContext ctx) {
+ public void enterCase_stmt(final Case_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
}
* </ol>
*/
@Override
- public void enterMandatory_arg(Mandatory_argContext ctx) {
+ public void enterMandatory_arg(final Mandatory_argContext ctx) {
BasicValidations.checkOnlyPermittedValues(ctx, PERMITTED_BOOLEAN_ARGS);
}
* </ol>
*/
@Override
- public void enterAnyxml_stmt(Anyxml_stmtContext ctx) {
+ public void enterAnyxml_stmt(final Anyxml_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
}
* </ol>
*/
@Override
- public void enterGrouping_stmt(Grouping_stmtContext ctx) {
+ public void enterGrouping_stmt(final Grouping_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
}
* </ol>
*/
@Override
- public void enterUses_stmt(Uses_stmtContext ctx) {
+ public void enterUses_stmt(final Uses_stmtContext ctx) {
BasicValidations.checkPrefixedIdentifier(ctx);
}
* </ol>
*/
@Override
- public void enterRefine_stmt(Refine_stmtContext ctx) {
+ public void enterRefine_stmt(final Refine_stmtContext ctx) {
BasicValidations.checkSchemaNodeIdentifier(ctx);
}
* </ol>
*/
@Override
- public void enterRpc_stmt(Rpc_stmtContext ctx) {
+ public void enterRpc_stmt(final Rpc_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
}
* </ol>
*/
@Override
- public void enterNotification_stmt(Notification_stmtContext ctx) {
+ public void enterNotification_stmt(final Notification_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
}
* </ol>
*/
@Override
- public void enterAugment_stmt(Augment_stmtContext ctx) {
+ public void enterAugment_stmt(final Augment_stmtContext ctx) {
BasicValidations.checkSchemaNodeIdentifier(ctx);
}
* </ol>
*/
@Override
- public void enterIdentity_stmt(Identity_stmtContext ctx) {
+ public void enterIdentity_stmt(final Identity_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
}
* </ol>
*/
@Override
- public void enterBase_stmt(Base_stmtContext ctx) {
+ public void enterBase_stmt(final Base_stmtContext ctx) {
BasicValidations.checkPrefixedIdentifier(ctx);
}
* </ol>
*/
@Override
- public void enterYin_element_arg(Yin_element_argContext ctx) {
+ public void enterYin_element_arg(final Yin_element_argContext ctx) {
BasicValidations.checkOnlyPermittedValues(ctx, PERMITTED_BOOLEAN_ARGS);
}
* </ol>
*/
@Override
- public void enterExtension_stmt(Extension_stmtContext ctx) {
+ public void enterExtension_stmt(final Extension_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
}
* </ol>
*/
@Override
- public void enterArgument_stmt(Argument_stmtContext ctx) {
+ public void enterArgument_stmt(final Argument_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
}
* </ol>
*/
@Override
- public void enterFeature_stmt(Feature_stmtContext ctx) {
+ public void enterFeature_stmt(final Feature_stmtContext ctx) {
BasicValidations.checkIdentifier(ctx);
}
* </ol>
*/
@Override
- public void enterIf_feature_stmt(If_feature_stmtContext ctx) {
+ public void enterIf_feature_stmt(final If_feature_stmtContext ctx) {
BasicValidations.checkPrefixedIdentifier(ctx);
}
* </ol>
*/
@Override
- public void enterDeviation_stmt(Deviation_stmtContext ctx) {
+ public void enterDeviation_stmt(final Deviation_stmtContext ctx) {
BasicValidations.checkSchemaNodeIdentifier(ctx);
Set<Class<? extends ParseTree>> types = Sets.newHashSet();
* </ol>
*/
@Override
- public void enterConfig_arg(Config_argContext ctx) {
+ public void enterConfig_arg(final Config_argContext ctx) {
BasicValidations.checkOnlyPermittedValues(ctx, PERMITTED_BOOLEAN_ARGS);
}
* </ol>
*/
@Override
- public void enterStatus_arg(Status_argContext ctx) {
+ public void enterStatus_arg(final Status_argContext ctx) {
BasicValidations.checkOnlyPermittedValues(ctx, PERMITTED_STATUS_ARGS);
}
*/
package org.opendaylight.yangtools.yang.parser.impl;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import java.io.FileNotFoundException;
import java.net.URI;
AugmentationSchema augment = augmentations.iterator().next();
assertNotNull(augment);
- expectedSchemaPath = new SchemaPath(qnames, true);
+ expectedSchemaPath = SchemaPath.create(qnames, true);
assertEquals(expectedSchemaPath, augment.getTargetPath());
Set<DataSchemaNode> augmentChildren = augment.getChildNodes();
QName qname = new QName(fooNS, fooRev, foo, "ds0ChannelNumber");
qnames.add(qname);
assertEquals(qname, ds0ChannelNumber.getQName());
- expectedSchemaPath = new SchemaPath(qnames, true);
+ expectedSchemaPath = SchemaPath.create(qnames, true);
assertEquals(expectedSchemaPath, ds0ChannelNumber.getPath());
assertFalse(ds0ChannelNumber.isAugmenting());
// type of leaf ds0ChannelNumber
QName typeQName = BaseTypes.constructQName("string");
List<QName> typePath = Collections.singletonList(typeQName);
- expectedSchemaPath = new SchemaPath(typePath, true);
+ expectedSchemaPath = SchemaPath.create(typePath, true);
assertEquals(expectedSchemaPath, ds0ChannelNumber.getType().getPath());
// leaf interface-id
qname = new QName(fooNS, fooRev, foo, "interface-id");
assertEquals(qname, interfaceId.getQName());
qnames.set(3, qname);
- expectedSchemaPath = new SchemaPath(qnames, true);
+ expectedSchemaPath = SchemaPath.create(qnames, true);
assertEquals(expectedSchemaPath, interfaceId.getPath());
assertFalse(interfaceId.isAugmenting());
qname = new QName(fooNS, fooRev, foo, "schemas");
assertEquals(qname, schemas.getQName());
qnames.set(3, qname);
- expectedSchemaPath = new SchemaPath(qnames, true);
+ expectedSchemaPath = SchemaPath.create(qnames, true);
assertEquals(expectedSchemaPath, schemas.getPath());
assertFalse(schemas.isAugmenting());
qname = new QName(fooNS, fooRev, foo, "odl");
assertEquals(qname, odl.getQName());
qnames.set(3, qname);
- expectedSchemaPath = new SchemaPath(qnames, true);
+ expectedSchemaPath = SchemaPath.create(qnames, true);
assertEquals(expectedSchemaPath, odl.getPath());
assertFalse(odl.isAugmenting());
ContainerSchemaNode augmentHolder = (ContainerSchemaNode) ifEntry.getDataChildByName("augment-holder");
TestUtils.checkIsAugmenting(augmentHolder, true);
assertEquals(q2, augmentHolder.getQName());
- expectedPath = new SchemaPath(qnames, true);
+ expectedPath = SchemaPath.create(qnames, true);
assertEquals(expectedPath, augmentHolder.getPath());
// foo.yang
QName qname = new QName(fooNS, fooRev, foo, "ds0ChannelNumber");
assertEquals(qname, ds0ChannelNumber.getQName());
qnames.add(qname);
- expectedPath = new SchemaPath(qnames, true);
+ expectedPath = SchemaPath.create(qnames, true);
assertEquals(expectedPath, ds0ChannelNumber.getPath());
// leaf interface-id
qname = new QName(fooNS, fooRev, foo, "interface-id");
assertEquals(qname, interfaceId.getQName());
qnames.set(3, qname);
- expectedPath = new SchemaPath(qnames, true);
+ expectedPath = SchemaPath.create(qnames, true);
assertEquals(expectedPath, interfaceId.getPath());
// container schemas
qname = new QName(fooNS, fooRev, foo, "schemas");
assertEquals(qname, schemas.getQName());
qnames.set(3, qname);
- expectedPath = new SchemaPath(qnames, true);
+ expectedPath = SchemaPath.create(qnames, true);
assertEquals(expectedPath, schemas.getPath());
// choice odl
qname = new QName(fooNS, fooRev, foo, "odl");
assertEquals(qname, odl.getQName());
qnames.set(3, qname);
- expectedPath = new SchemaPath(qnames, true);
+ expectedPath = SchemaPath.create(qnames, true);
assertEquals(expectedPath, odl.getPath());
}
QName qname = new QName(fooNS, fooRev, foo, "id");
assertEquals(qname, id.getQName());
qnames.add(qname);
- expectedPath = new SchemaPath(qnames, true);
+ expectedPath = SchemaPath.create(qnames, true);
assertEquals(expectedPath, id.getPath());
Set<DataSchemaNode> idChildren = id.getChildNodes();
assertEquals(1, idChildren.size());
qname = new QName(fooNS, fooRev, foo, "node1");
assertEquals(qname, node1.getQName());
qnames.set(4, qname);
- expectedPath = new SchemaPath(qnames, true);
+ expectedPath = SchemaPath.create(qnames, true);
assertEquals(expectedPath, node1.getPath());
Set<DataSchemaNode> node1Children = node1.getChildNodes();
assertTrue(node1Children.isEmpty());
qname = new QName(fooNS, fooRev, foo, "node2");
assertEquals(qname, node2.getQName());
qnames.set(4, qname);
- expectedPath = new SchemaPath(qnames, true);
+ expectedPath = SchemaPath.create(qnames, true);
assertEquals(expectedPath, node2.getPath());
Set<DataSchemaNode> node2Children = node2.getChildNodes();
assertTrue(node2Children.isEmpty());
qname = new QName(fooNS, fooRev, foo, "node3");
assertEquals(qname, node3.getQName());
qnames.set(4, qname);
- expectedPath = new SchemaPath(qnames, true);
+ expectedPath = SchemaPath.create(qnames, true);
assertEquals(expectedPath, node3.getPath());
Set<DataSchemaNode> node3Children = node3.getChildNodes();
assertEquals(1, node3Children.size());
qnames.add(new QName(fooNS, fooRev, foo, "id"));
LeafSchemaNode caseIdChild = (LeafSchemaNode) idChildren.iterator().next();
assertNotNull(caseIdChild);
- expectedPath = new SchemaPath(qnames, true);
+ expectedPath = SchemaPath.create(qnames, true);
assertEquals(expectedPath, caseIdChild.getPath());
// case node3 child
qnames.set(5, new QName(fooNS, fooRev, foo, "node3"));
ContainerSchemaNode caseNode3Child = (ContainerSchemaNode) node3Children.iterator().next();
assertNotNull(caseNode3Child);
- expectedPath = new SchemaPath(qnames, true);
+ expectedPath = SchemaPath.create(qnames, true);
assertEquals(expectedPath, caseNode3Child.getPath());
}
// case attach
qnames[3] = new QName(NS_FOO, revision, "f", "attach");
assertEquals(qnames[3], attach.getQName());
- expectedPath = new SchemaPath(Arrays.asList(qnames), true);
+ expectedPath = SchemaPath.create(Arrays.asList(qnames), true);
assertEquals(expectedPath, attach.getPath());
Set<DataSchemaNode> attachChildren = attach.getChildNodes();
assertEquals(1, attachChildren.size());
// case create
qnames[3] = new QName(NS_FOO, revision, "f", "create");
assertEquals(qnames[3], create.getQName());
- expectedPath = new SchemaPath(Arrays.asList(qnames), true);
+ expectedPath = SchemaPath.create(Arrays.asList(qnames), true);
assertEquals(expectedPath, create.getPath());
Set<DataSchemaNode> createChildren = create.getChildNodes();
assertEquals(1, createChildren.size());
// case attach
qnames[3] = new QName(NS_FOO, revision, "f", "destroy");
assertEquals(qnames[3], destroy.getQName());
- expectedPath = new SchemaPath(Arrays.asList(qnames), true);
+ expectedPath = SchemaPath.create(Arrays.asList(qnames), true);
assertEquals(expectedPath, destroy.getPath());
Set<DataSchemaNode> destroyChildren = destroy.getChildNodes();
assertEquals(1, destroyChildren.size());
import static org.junit.Assert.assertEquals;
-import java.io.*;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
import java.net.URI;
-import java.text.*;
-import java.util.*;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.*;
+import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.ModuleImport;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
final class TestUtils {
}
- public static Set<Module> loadModules(URI resourceDirectory) throws FileNotFoundException {
+ public static Set<Module> loadModules(final URI resourceDirectory) throws FileNotFoundException {
final YangModelParser parser = new YangParserImpl();
final File testDir = new File(resourceDirectory);
final String[] fileList = testDir.list();
return parser.parseYangModels(testFiles);
}
- public static Set<Module> loadModules(List<InputStream> input) throws IOException {
+ public static Set<Module> loadModules(final List<InputStream> input) throws IOException {
final YangModelParser parser = new YangParserImpl();
final Set<Module> modules = new HashSet<>(parser.parseYangModelsFromStreams(input));
for (InputStream stream : input) {
return modules;
}
- public static Module findModule(Set<Module> modules, String moduleName) {
+ public static Module findModule(final Set<Module> modules, final String moduleName) {
Module result = null;
for (Module module : modules) {
if (module.getName().equals(moduleName)) {
return result;
}
- public static ModuleImport findImport(Set<ModuleImport> imports, String prefix) {
+ public static ModuleImport findImport(final Set<ModuleImport> imports, final String prefix) {
ModuleImport result = null;
for (ModuleImport moduleImport : imports) {
if (moduleImport.getPrefix().equals(prefix)) {
return result;
}
- public static TypeDefinition<?> findTypedef(Set<TypeDefinition<?>> typedefs, String name) {
+ public static TypeDefinition<?> findTypedef(final Set<TypeDefinition<?>> typedefs, final String name) {
TypeDefinition<?> result = null;
for (TypeDefinition<?> td : typedefs) {
if (td.getQName().getLocalName().equals(name)) {
return result;
}
- public static SchemaPath createPath(boolean absolute, URI namespace, Date revision, String prefix, String... names) {
+ public static SchemaPath createPath(final boolean absolute, final URI namespace, final Date revision, final String prefix, final String... names) {
List<QName> path = new ArrayList<>();
for (String name : names) {
path.add(new QName(namespace, revision, prefix, name));
}
- return new SchemaPath(path, absolute);
+ return SchemaPath.create(path, absolute);
}
- public static Date createDate(String date) {
+ public static Date createDate(final String date) {
Date result;
final DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
* @param expected
* expected value
*/
- public static void checkIsAugmenting(DataSchemaNode node, boolean expected) {
+ public static void checkIsAugmenting(final DataSchemaNode node, final boolean expected) {
assertEquals(expected, node.isAugmenting());
if (node instanceof DataNodeContainer) {
for (DataSchemaNode child : ((DataNodeContainer) node).getChildNodes()) {
* @param expected
* expected value
*/
- public static void checkIsAddedByUses(DataSchemaNode node, boolean expected) {
+ public static void checkIsAddedByUses(final DataSchemaNode node, final boolean expected) {
assertEquals(expected, node.isAddedByUses());
if (node instanceof DataNodeContainer) {
for (DataSchemaNode child : ((DataNodeContainer) node).getChildNodes()) {
}
}
- public static void checkIsAddedByUses(GroupingDefinition node, boolean expected) {
+ public static void checkIsAddedByUses(final GroupingDefinition node, final boolean expected) {
assertEquals(expected, node.isAddedByUses());
if (node instanceof DataNodeContainer) {
for (DataSchemaNode child : ((DataNodeContainer) node).getChildNodes()) {
}
}
- public static List<Module> findModules(Set<Module> modules, String moduleName) {
+ public static List<Module> findModules(final Set<Module> modules, final String moduleName) {
List<Module> result = new ArrayList<>();
for (Module module : modules) {
if (module.getName().equals(moduleName)) {
*/
package org.opendaylight.yangtools.yang.parser.impl;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import java.io.FileNotFoundException;
import java.net.URI;
assertNotNull(pcreq);
QName expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "pcreq");
path.offer(expectedQName);
- SchemaPath expectedPath = new SchemaPath(path, true);
+ SchemaPath expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, pcreq.getPath());
Set<DataSchemaNode> childNodes = pcreq.getChildNodes();
assertEquals(4, childNodes.size());
assertNotNull(version);
expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "version");
path.offer(expectedQName);
- expectedPath = new SchemaPath(path, true);
+ expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, version.getPath());
expectedQName = new QName(GD_NS, GD_REV, GD_PREF, "protocol-version");
path.offer(expectedQName);
- expectedPath = new SchemaPath(Lists.newArrayList(expectedQName), true);
+ expectedPath = SchemaPath.create(Lists.newArrayList(expectedQName), true);
assertEquals(expectedPath, version.getType().getPath());
assertEquals(Uint8.getInstance(), version.getType().getBaseType());
assertTrue(version.isAddedByUses());
path.pollLast();
path.pollLast();
path.offer(expectedQName);
- expectedPath = new SchemaPath(path, true);
+ expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, type.getPath());
expectedQName = new QName(GD_NS, GD_REV, GD_PREF, "int-ext");
path.offer(expectedQName);
- expectedPath = new SchemaPath(Lists.newArrayList(expectedQName), true);
+ expectedPath = SchemaPath.create(Lists.newArrayList(expectedQName), true);
assertEquals(expectedPath, type.getType().getPath());
UnionType union = (UnionType)type.getType().getBaseType();
assertEquals(BaseTypes.schemaPath(BaseTypes.constructQName("union")), union.getPath());
path.pollLast();
path.pollLast();
path.offer(expectedQName);
- expectedPath = new SchemaPath(path, true);
+ expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, requests.getPath());
assertFalse(requests.isAddedByUses());
childNodes = requests.getChildNodes();
assertNotNull(rp);
expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "rp");
path.offer(expectedQName);
- expectedPath = new SchemaPath(path, true);
+ expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, rp.getPath());
assertFalse(rp.isAddedByUses());
childNodes = rp.getChildNodes();
expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "processing-rule");
assertEquals(expectedQName, processingRule.getQName());
path.offer(expectedQName);
- expectedPath = new SchemaPath(path, true);
+ expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, processingRule.getPath());
assertEquals(BooleanType.getInstance(), processingRule.getType());
assertTrue(processingRule.isAddedByUses());
assertEquals(expectedQName, ignore.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath = new SchemaPath(path, true);
+ expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, ignore.getPath());
assertEquals(BooleanType.getInstance(), ignore.getType());
assertTrue(ignore.isAddedByUses());
assertEquals(expectedQName, priority.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath = new SchemaPath(path, true);
+ expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, priority.getPath());
expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "uint8");
path.offer(expectedQName);
- expectedPath = new SchemaPath(path, true);
+ expectedPath = SchemaPath.create(path, true);
// TODO
//assertEquals(expectedPath, priority.getType().getPath());
assertEquals(Uint8.getInstance(), priority.getType().getBaseType());
path.pollLast();
path.pollLast();
path.offer(expectedQName);
- expectedPath = new SchemaPath(path, true);
+ expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, box.getPath());
assertTrue(box.isAddedByUses());
// * |-- |-- |-- |-- container order
expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "order");
assertEquals(expectedQName, order.getQName());
path.offer(expectedQName);
- expectedPath = new SchemaPath(path, true);
+ expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, order.getPath());
assertTrue(order.isAddedByUses());
assertTrue(order.isAugmenting());
expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "delete");
assertEquals(expectedQName, delete.getQName());
path.offer(expectedQName);
- expectedPath = new SchemaPath(path, true);
+ expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, delete.getPath());
assertEquals(Uint32.getInstance(), delete.getType());
assertTrue(delete.isAddedByUses());
assertEquals(expectedQName, setup.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath = new SchemaPath(path, true);
+ expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, setup.getPath());
assertEquals(Uint32.getInstance(), setup.getType());
assertTrue(setup.isAddedByUses());
path.pollLast();
path.pollLast();
path.offer(expectedQName);
- expectedPath = new SchemaPath(path, true);
+ expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, pke.getPath());
assertFalse(pke.isAddedByUses());
// * |-- |-- |-- path-key
expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "path-key");
assertEquals(expectedQName, pathKey.getQName());
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, pathKey.getPath());
assertFalse(pathKey.isAddedByUses());
assertEquals(3, pathKey.getChildNodes().size());
expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "processing-rule");
assertEquals(expectedQName, processingRule.getQName());
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, processingRule.getPath());
assertEquals(BooleanType.getInstance(), processingRule.getType());
assertTrue(processingRule.isAddedByUses());
assertEquals(expectedQName, ignore.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, ignore.getPath());
assertEquals(BooleanType.getInstance(), ignore.getType());
assertTrue(ignore.isAddedByUses());
assertEquals(expectedQName, pathKeys.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, pathKeys.getPath());
assertTrue(pathKeys.isAddedByUses());
childNodes = pathKeys.getChildNodes();
expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "version");
assertEquals(expectedQName, version.getQName());
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, version.getPath());
assertTrue(version.getType() instanceof ExtendedType);
assertEquals(Uint8.getInstance(), version.getType().getBaseType());
assertEquals(expectedQName, type.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, type.getPath());
assertTrue(type.getType() instanceof ExtendedType);
assertTrue(type.isAddedByUses());
path.pollLast();
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, sc.getPath());
assertFalse(sc.isAddedByUses());
// * |-- |-- |-- container p2p
expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "p2p");
assertEquals(expectedQName, p2p.getQName());
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, p2p.getPath());
assertFalse(p2p.isAddedByUses());
// * |-- |-- |-- |-- container endpoints
expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "endpoints");
assertEquals(expectedQName, endpoints.getQName());
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, endpoints.getPath());
assertFalse(endpoints.isAddedByUses());
// * |-- |-- |-- |-- |-- leaf processing-rule
expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "processing-rule");
assertEquals(expectedQName, processingRule.getQName());
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, processingRule.getPath());
assertEquals(BooleanType.getInstance(), processingRule.getType());
assertTrue(processingRule.isAddedByUses());
assertEquals(expectedQName, ignore.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, ignore.getPath());
assertEquals(BooleanType.getInstance(), ignore.getType());
assertTrue(ignore.isAddedByUses());
assertEquals(expectedQName, box.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, box.getPath());
assertTrue(box.isAddedByUses());
// * |-- |-- |-- |-- |-- choice address-family
assertEquals(expectedQName, af.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, af.getPath());
assertTrue(af.isAddedByUses());
// * |-- |-- |-- |-- container reported-route
path.pollLast();
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, reportedRoute.getPath());
assertFalse(reportedRoute.isAddedByUses());
// * |-- |-- |-- |-- |-- leaf processing-rule
expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "processing-rule");
assertEquals(expectedQName, processingRule.getQName());
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, processingRule.getPath());
assertEquals(BooleanType.getInstance(), processingRule.getType());
assertTrue(processingRule.isAddedByUses());
assertEquals(expectedQName, ignore.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, ignore.getPath());
assertEquals(BooleanType.getInstance(), ignore.getType());
assertTrue(ignore.isAddedByUses());
assertEquals(expectedQName, subobjects.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, subobjects.getPath());
assertTrue(subobjects.isAddedByUses());
// * |-- |-- |-- |-- |-- container bandwidth
assertEquals(expectedQName, bandwidth.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, bandwidth.getPath());
assertFalse(bandwidth.isAddedByUses());
// * |-- |-- |-- |-- container bandwidth
path.pollLast();
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, bandwidth.getPath());
assertTrue(bandwidth.isAddedByUses());
// * |-- |-- |-- |-- |-- leaf processing-rule
expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "processing-rule");
assertEquals(expectedQName, processingRule.getQName());
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, processingRule.getPath());
assertEquals(BooleanType.getInstance(), processingRule.getType());
assertTrue(processingRule.isAddedByUses());
assertEquals(expectedQName, ignore.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, ignore.getPath());
assertEquals(BooleanType.getInstance(), ignore.getType());
assertTrue(ignore.isAddedByUses());
assertEquals(expectedQName, bandwidth.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, bandwidthInner.getPath());
assertTrue(bandwidthInner.isAddedByUses());
// * |-- list svec
path.pollLast();
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, svec.getPath());
assertFalse(svec.isAddedByUses());
// * |-- |-- leaf link-diverse
expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "link-diverse");
assertEquals(expectedQName, linkDiverse.getQName());
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, linkDiverse.getPath());
assertEquals(BooleanType.getInstance(), linkDiverse.getType());
assertTrue(linkDiverse.isAddedByUses());
assertEquals(expectedQName, processingRule.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, processingRule.getPath());
assertEquals(BooleanType.getInstance(), processingRule.getType());
assertTrue(processingRule.isAddedByUses());
assertEquals(expectedQName, ignore.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, ignore.getPath());
assertEquals(BooleanType.getInstance(), ignore.getType());
assertTrue(ignore.isAddedByUses());
assertEquals(expectedQName, metric.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, metric.getPath());
assertFalse(metric.isAddedByUses());
// * |-- |-- |-- leaf metric-type
expectedQName = new QName(UG_NS, UG_REV, UG_PREF, "metric-type");
assertEquals(expectedQName, metricType.getQName());
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, metricType.getPath());
assertEquals(Uint8.getInstance(), metricType.getType());
assertTrue(metricType.isAddedByUses());
assertEquals(expectedQName, box.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, box.getPath());
assertTrue(box.isAddedByUses());
// * |-- |-- |-- leaf processing-rule
assertEquals(expectedQName, processingRule.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, processingRule.getPath());
assertEquals(BooleanType.getInstance(), processingRule.getType());
assertTrue(processingRule.isAddedByUses());
assertEquals(expectedQName, ignore.getQName());
path.pollLast();
path.offer(expectedQName);
- expectedPath= new SchemaPath(path, true);
+ expectedPath= SchemaPath.create(path, true);
assertEquals(expectedPath, ignore.getPath());
assertEquals(BooleanType.getInstance(), ignore.getType());
assertTrue(ignore.isAddedByUses());
assertNotNull(intExt);
List<QName> path = Lists.newArrayList(new QName(GD_NS, GD_REV, GD_PREF, "int-ext"));
- SchemaPath expectedPath = new SchemaPath(path, true);
+ SchemaPath expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, intExt.getPath());
UnionType union = (UnionType)intExt.getBaseType();
assertNotNull(pv);
QName q1 = BaseTypes.constructQName("union");
- expectedPath = new SchemaPath(Lists.newArrayList(q1), true);
+ expectedPath = SchemaPath.create(Lists.newArrayList(q1), true);
assertEquals(expectedPath, union.getPath());
}
*/
package org.opendaylight.yangtools.yang.parser.impl;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.text.DateFormat;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.*;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.MustDefinition;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.Status;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.UsesNode;
public class YangParserSimpleTest {
private final URI snNS = URI.create("urn:opendaylight:simple-nodes");
private Date rev;
private final String prefix = "sn";
- private SchemaPath createPath(String... names) {
+ private SchemaPath createPath(final String... names) {
try {
rev = new SimpleDateFormat("yyyy-MM-dd").parse("2013-07-30");
} catch (ParseException e) {
for (String name : names) {
path.add(new QName(ns, rev, prefix, name));
}
- return new SchemaPath(path, true);
+ return SchemaPath.create(path, true);
}
}
*/
package org.opendaylight.yangtools.yang.parser.impl;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.util.Uint32;
import org.opendaylight.yangtools.yang.model.util.UnionType;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
public class YangParserTest {
public static final String FS = File.separator;
List<QName> path = new ArrayList<>();
path.add(new QName(barNS, barRev, "br", "interfaces"));
path.add(new QName(barNS, barRev, "br", "ifEntry"));
- SchemaPath expectedPath = new SchemaPath(path, true);
+ SchemaPath expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, dev.getTargetPath());
assertEquals(Deviate.ADD, dev.getDeviate());
assertSetEquals(newModules, ctx.getModules());
}
- private void checkOrder(Collection<Module> modules) {
+ private void checkOrder(final Collection<Module> modules) {
Iterator<Module> it = modules.iterator();
Module m = it.next();
assertEquals("m2", m.getName());
assertEquals("m1", m.getName());
}
- private void assertSetEquals(Set<Module> s1, Set<Module> s2) {
+ private void assertSetEquals(final Set<Module> s1, final Set<Module> s2) {
assertEquals(s1, s2);
Iterator<Module> it = s1.iterator();
for (Module m : s2) {
import org.junit.Ignore;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.*;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Deviation;
import org.opendaylight.yangtools.yang.model.api.Deviation.Deviate;
+import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
+import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.MustDefinition;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.UsesNode;
import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
import org.opendaylight.yangtools.yang.model.util.ExtendedType;
QName qname = new QName(URI.create("urn:opendaylight.baz"), simpleDateFormat.parse("2013-02-27"), "baz",
"target");
path.add(qname);
- SchemaPath expectedPath = new SchemaPath(path, true);
+ SchemaPath expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, usesNode.getGroupingPath());
// test refine
List<QName> path = new ArrayList<>();
path.add(new QName(expectedNS, expectedRev, "bar", "interfaces"));
path.add(new QName(expectedNS, expectedRev, "bar", "ifEntry"));
- SchemaPath expectedPath = new SchemaPath(path, true);
+ SchemaPath expectedPath = SchemaPath.create(path, true);
assertEquals(expectedPath, dev.getTargetPath());
assertEquals(Deviate.ADD, dev.getDeviate());
import java.net.URI;
import java.net.URISyntaxException;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
import org.junit.Test;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.*;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.Status;
+import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
import org.opendaylight.yangtools.yang.parser.builder.impl.UnknownSchemaNodeBuilder;
List<QName> qnamesA = new ArrayList<>();
qnamesA.add(qnameA1);
qnamesA.add(qnameA2);
- SchemaPath schemaPathA = new SchemaPath(qnamesA, true);
+ SchemaPath schemaPathA = SchemaPath.create(qnamesA, true);
QName qnameB = new QName(uriB, new Date(5000000), "some name");
List<QName> qnamesB = new ArrayList<>();
qnamesB.add(qnameB1);
qnamesB.add(qnameB2);
- SchemaPath schemaPathB = new SchemaPath(qnamesB, true);
+ SchemaPath schemaPathB = SchemaPath.create(qnamesB, true);
BitImpl biB = null;
BitImpl biA = new BitImpl(55L, qnameA, schemaPathA, "description", "reference", Status.CURRENT, null);
rh1.setReference("reference");
}
- private URI getUri(String uri) {
+ private URI getUri(final String uri) {
URI simpleUri = null;
boolean instantionated = false;
try {
List<QName> qnamesB = new ArrayList<>();
qnamesA.add(qnameA);
qnamesB.add(qnameB);
- SchemaPath schemaPathB = new SchemaPath(qnamesB, true);
+ SchemaPath schemaPathB = SchemaPath.create(qnamesB, true);
UnknownSchemaNodeBuilder usnb = new UnknownSchemaNodeBuilder("usnb", 151, new QName(simpleUri, "tst"), schemaPathB);
UnknownSchemaNodeBuilder usnb1 = new UnknownSchemaNodeBuilder("usnb", 151, new QName(simpleUri, "tst"), schemaPathB);